From e981442a7e10b588aab7286128ac6d3be729d3d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:17:06 +0000 Subject: [PATCH 1/7] feat(service-automation): resolve bare flow names by (package, name) through the package-scoped resolver The flow index and the activation ledger projection consult the package (ADR-0150 D3/D4). A subflow or map child named inside a package flow resolves from that package: its own flow, else the one holder in its declared dependency closure, else a refusal naming every candidate. A name two packages hold is refused at registration instead of arming one of them. The ledger projection switches off the (package, name) a row names. Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 Co-authored-by: Claude --- .../services/service-automation/package.json | 2 +- .../services/service-automation/src/engine.ts | 94 +++++- .../src/flow-activation-projection.ts | 65 ++++ .../src/flow-definitions.ts | 20 +- .../flow-package-scoped-resolution.test.ts | 290 ++++++++++++++++++ .../services/service-automation/src/index.ts | 4 + .../services/service-automation/src/plugin.ts | 46 ++- pnpm-lock.yaml | 6 +- 8 files changed, 515 insertions(+), 12 deletions(-) create mode 100644 packages/services/service-automation/src/flow-activation-projection.ts create mode 100644 packages/services/service-automation/src/flow-package-scoped-resolution.test.ts diff --git a/packages/services/service-automation/package.json b/packages/services/service-automation/package.json index 8ff9a0fb62a..a7b520278e0 100644 --- a/packages/services/service-automation/package.json +++ b/packages/services/service-automation/package.json @@ -30,6 +30,7 @@ "@objectstack/formula": "workspace:*", "@objectstack/metadata-core": "workspace:*", "@objectstack/metadata-protocol": "workspace:*", + "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", "@objectstack/plugin-auth": "workspace:*", "@objectstack/spec": "workspace:*", @@ -38,7 +39,6 @@ "devDependencies": { "@objectstack/driver-sql": "workspace:*", "@objectstack/metadata-core": "workspace:*", - "@objectstack/objectql": "workspace:*", "@objectstack/plugin-audit": "workspace:*", "@objectstack/plugin-security": "workspace:*", "@objectstack/plugin-sharing": "workspace:*", diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 0d024d71bbc..952613960e3 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -224,6 +224,11 @@ import { refuseCustomerAuthoredToggle, } from './subflow-guards.js'; import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-guard.js'; +// [ADR-0150 D3/D4] The one package-scoped resolver's answer, read through the +// reader the host attaches (`setFlowNameResolver`), and the activation +// projection keyed by `(package, name)`. +import type { PackageScopedRefusal, PackageScopedResolution } from '@objectstack/objectql'; +import { FlowActivationProjection } from './flow-activation-projection.js'; import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; // [#25222] The consumed-suspension restore's bodies: journaling a consumed // suspension, resolving its witnesses, and restoring, peeking at or inspecting @@ -2567,6 +2572,17 @@ export interface FlowContender { */ export type PackagedFlowSource = (name: string) => string | undefined; +/** + * [ADR-0150 D3] A reader over the ONE package-scoped resolver: which item the + * bare flow name `name` means for a caller of package `callerPackageId` + * (`null` for a caller with no package). The automation plugin attaches + * `resolvePackageScopedName` from `@objectstack/objectql` over the ObjectQL + * registry ({@link AutomationEngine.setFlowNameResolver}); `undefined` means + * the host serves no registry to ask, and the engine's own flow map answers as + * before. ⛔ Never a second implementation of the rule. + */ +export type FlowNameResolver = (name: string, callerPackageId: string | null) => PackageScopedResolution | undefined; + /** * [#28405] The stored body of flow `name` whose content identity is * `checksum` ({@link SuspendedRun.flowChecksum}), as the metadata history @@ -2759,7 +2775,10 @@ export class AutomationEngine implements IAutomationService { * boot read is required anyway, `execute()` consults its result rather * than issuing a datasource read on every single flow run. */ - private flowLedgerDisabled = new Set(); + // [ADR-0150 D4] Keyed by `(package, name)`: a row switches off the flow of + // the package it names, read against the package that ships the name + // today — see {@link FlowActivationProjection}. + private flowLedgerDisabled = new FlowActivationProjection((name) => this.packagedFlowOwner(name)); /** * The durable ledger behind {@link flowLedgerDisabled}. `null` until a host * attaches one via {@link setFlowActivationStore} — an engine with no @@ -2774,6 +2793,13 @@ export class AutomationEngine implements IAutomationService { * no flow a managed package loaded. */ private packagedFlowSource?: PackagedFlowSource; + /** + * [ADR-0150 D3] The reader that answers which item a bare flow name means + * for a caller — see {@link setFlowNameResolver}. `undefined` until a host + * attaches one; with none, the engine's own flow map is the only holder it + * knows, as before. + */ + private flowNameResolver?: FlowNameResolver; /** [#20790] The write-only flow credential channel — see {@link setFlowCredentialSource}. */ private flowCredentialSource?: FlowCredentialSource; /** [#20281 stage ③] The connector sync executor — see {@link setConnectorPullSource}. */ @@ -4531,6 +4557,13 @@ export class AutomationEngine implements IAutomationService { if (refusal) throw new Error(refusal.message); } + // [ADR-0150 D3/D4] The engine arms one flow per bare name, so a name + // the resolver cannot answer for a caller with no package — two + // packages hold it — is refused here, naming every holder, before + // anything is armed. ⛔ Never an arming by package id or by arrival. + const nameRefusal = this.flowNameRefusal(name, null); + if (nameRefusal) throw new Error(nameRefusal.message); + // Version history management const history = this.flowVersionHistory.get(name) ?? []; history.push({ @@ -4926,6 +4959,58 @@ export class AutomationEngine implements IAutomationService { return this.packagedFlowOwner(name) !== undefined; } + /** + * [ADR-0150 D3] Attach the reader over the one package-scoped resolver + * ({@link FlowNameResolver}). The automation plugin calls this at `init()` + * with a reader that asks the ObjectQL registry at question time, never at + * boot, for {@link setPackagedFlowSource}'s reason. + * + * Two seams read it, and only these two: + * + * - {@link registerFlow} asks it for a caller with no package before it + * arms a name, so a name two packages hold is refused, naming both, + * instead of arming one of them. The engine keeps one armed slot per + * bare name, and nothing picks between two holders. + * - {@link execute} asks it for the caller's package: the package that + * ships the flow whose run names the child (a `subflow` or `map` node's + * `flowName`, carried on the run's context as `flowName`), or no + * package for a door, a trigger or any caller outside a run. A refusal + * is the answer, naming every candidate; nothing is executed. + * + * A name the registry holds nothing under (a flow registered straight into + * the engine) has one holder, the engine's own flow map, and resolves to + * it as before. + */ + setFlowNameResolver(resolver: FlowNameResolver | undefined): void { + this.flowNameResolver = resolver; + } + + /** + * [ADR-0150 D3] The resolver's refusal of the bare flow name `name` for a + * caller of package `callerPackageId` (`null`: no package), or `undefined` + * when the name resolves, names nothing in the registry, or no resolver is + * attached. Read-only; records nothing. + */ + private flowNameRefusal(name: string, callerPackageId: string | null): PackageScopedRefusal | undefined { + const resolution = this.flowNameResolver?.(name, callerPackageId); + return resolution?.status === 'refused' ? resolution : undefined; + } + + /** + * [ADR-0150 D3] The package a call of {@link execute} comes from: the + * package that ships the flow whose run made the call — `context.flowName`, + * which the engine stamps on every run's context + * (`resolveRunContext`), so a `subflow` or `map` child carries its parent's + * name — or `null` for a caller outside a run, and for a run of a flow no + * package ships (an environment-authored flow resolves as a caller with no + * package, ADR-0150 D3). + */ + private flowCallerPackage(context: AutomationContext | undefined): string | null { + const caller = context?.flowName; + if (typeof caller !== 'string' || caller === '') return null; + return this.packagedFlowOwner(caller) ?? null; + } + /** * [#20790] Attach the write-only flow credential channel. The automation * plugin calls this at `init()`, before any flow is registered. With none @@ -6130,6 +6215,13 @@ export class AutomationEngine implements IAutomationService { async execute(flowName: string, context?: AutomationContext): Promise { const startTime = Date.now(); + // [ADR-0150 D3] The bare name resolves for the caller's package first: + // a run of package P's flow reaches P's own flow, else the one holder + // in P's declared dependency closure; anything else is refused with + // every candidate named, and nothing runs. Never dispatched, so no + // `status`, for the reason the disabled exit below states. + const nameRefusal = this.flowNameRefusal(flowName, this.flowCallerPackage(context)); + if (nameRefusal) return { success: false, error: nameRefusal.message }; const flow = this.flows.get(flowName); if (!flow) { diff --git a/packages/services/service-automation/src/flow-activation-projection.ts b/packages/services/service-automation/src/flow-activation-projection.ts new file mode 100644 index 00000000000..f99cc6081cf --- /dev/null +++ b/packages/services/service-automation/src/flow-activation-projection.ts @@ -0,0 +1,65 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D4, "activation ledger"] The engine's local projection of the + * activation ledger's `active: false` rows for flows, keyed by + * `(package, name)`: a switch belongs to the packaged flow it was flipped on, + * never to whatever item bears that name later. + * + * The ledger row has always carried the package (`FlowActivationRow.packageId`, + * the loader's set's owner the toggle door attributes it to); the projection + * used to drop it and keep a set of bare names. Now it keeps the pair, and a + * question about a flow name is answered for the package that ships that name + * today ({@link FlowActivationProjection.has}). + * + * ⛔ It is still a projection, never a source (ADR-0126 §7.2): its only + * writers are `hydrateFlowActivations` (from the ledger) and `toggleFlow` + * (after the durable write), exactly as for the set it replaces. + */ +export class FlowActivationProjection { + /** Flow name → the packages whose row switches it off; `''` is a row naming no package. */ + private readonly rows = new Map>(); + + /** + * @param holderOf - the package that ships the flow `name` today (the + * engine's `packagedFlowOwner`, the loader's set), or `undefined` when + * no reader can say. + */ + constructor(private readonly holderOf: (name: string) => string | undefined) {} + + /** + * Is the flow `name` switched off by a ledger row? A row naming no package + * binds to the name's one holder (ADR-0150 D8: backfilled from the one + * holder), so it switches the name off as before. A row naming a package + * switches off that package's flow of the name, and only it: a row of + * another package, kept for a flow this deployment no longer ships under + * it, never switches off a different package's same-named flow. When no + * reader can say which package ships the name, every row of the name + * still switches it off — the projection never arms a flow on a guess. + */ + has(name: string): boolean { + const packages = this.rows.get(name); + if (!packages || packages.size === 0) return false; + if (packages.has('')) return true; + const holder = this.holderOf(name); + return holder === undefined ? true : packages.has(holder); + } + + /** Record a row switching `(packageId, name)` off. */ + add(name: string, packageId?: string): void { + let packages = this.rows.get(name); + if (!packages) { + packages = new Set(); + this.rows.set(name, packages); + } + packages.add(packageId ?? ''); + } + + /** Record that `(packageId, name)` is switched on (its row is active, or gone). */ + delete(name: string, packageId?: string): void { + const packages = this.rows.get(name); + if (!packages) return; + packages.delete(packageId ?? ''); + if (packages.size === 0) this.rows.delete(name); + } +} diff --git a/packages/services/service-automation/src/flow-definitions.ts b/packages/services/service-automation/src/flow-definitions.ts index 30d2f0f2755..c5cae992fe8 100644 --- a/packages/services/service-automation/src/flow-definitions.ts +++ b/packages/services/service-automation/src/flow-definitions.ts @@ -463,16 +463,20 @@ export async function hydrateFlowActivations(this: Pick l; + return l; +} + +const manifest = (id: string, deps: string[] = []) => ({ + id, + name: id, + version: '1.0.0', + type: 'app', + namespace: id.split('.').pop()!, + ...(deps.length > 0 ? { dependencies: Object.fromEntries(deps.map((d) => [d, '^1.0.0'])) } : {}), +}) as never; + +/** start → mark → end: the `mark` node records that this flow ran. */ +function leaf(name: string) { + return { + name, + label: name, + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'mark', type: 'mark', label: 'Mark', config: {} }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'mark' }, + { id: 'e2', source: 'mark', target: 'end' }, + ], + }; +} + +/** start → subflow(child) → end. */ +function caller(name: string, child: string) { + return { + name, + label: name, + type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: {} }, + { id: 'call', type: 'subflow', label: 'Call', config: { flowName: child } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'call' }, + { id: 'e2', source: 'call', target: 'end' }, + ], + }; +} + +let registry: SchemaRegistry; +let engine: AutomationEngine; +/** The loader's set: which package ships each flow name (the engine's `packagedFlowOwner`). */ +let loaderSet: Record; +/** The flows whose `mark` node ran, in order. */ +let ran: string[]; + +const install = (id: string, deps: string[] = []) => registry.installPackage(manifest(id, deps), 'code'); + +/** Package `packageId` ships flow `body`: in its registry slot, the loader's set and the engine. */ +function ship(packageId: string, body: { name: string }) { + registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId); + loaderSet[body.name] = packageId; + engine.registerFlow(body.name, body); +} + +/** The environment authored flow `body`: a package-less row in the bare slot, and the engine. */ +function author(body: { name: string }) { + registry.registerItem('flow', { ...body, _provenance: 'org' }, 'name' as never); + engine.registerFlow(body.name, body); +} + +beforeEach(() => { + registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + loaderSet = {}; + ran = []; + engine = new AutomationEngine(silentLogger()); + const ctx = { + logger: silentLogger(), + getService(name: string) { + if (name === 'objectql') return { registry }; + throw new Error(`no ${name}`); + }, + } as any; + installBuiltinNodes(engine, ctx); + engine.registerNodeExecutor({ + type: 'mark', + async execute(_node: unknown, variables: Map) { + ran.push(String(variables.get('$flowName'))); + return { success: true }; + }, + } as unknown as NodeExecutor); + engine.setPackagedFlowSource((name) => loaderSet[name]); + engine.setFlowNameResolver(flowNameResolver(ctx)); +}); + +describe('ADR-0150 D3 — a subflow named inside a package resolves from that package', () => { + it("reaches the caller package's own flow", async () => { + install(P); + ship(P, leaf('notify')); + ship(P, caller('process', 'notify')); + const result = await engine.execute('process'); + expect(result.success).toBe(true); + expect(ran).toEqual(['notify']); + }); + + it("reaches the one holder in the caller package's declared dependency closure", async () => { + install(A); + install(P, [A]); + ship(A, leaf('notify')); + ship(P, caller('process', 'notify')); + const result = await engine.execute('process'); + expect(result.success).toBe(true); + expect(ran).toEqual(['notify']); + }); + + it('an environment-authored caller reaches the one package holder (a caller with no package)', async () => { + install(A); + ship(A, leaf('notify')); + author(caller('my_process', 'notify')); + const result = await engine.execute('my_process'); + expect(result.success).toBe(true); + expect(ran).toEqual(['notify']); + }); + + it('a flow the registry holds nothing under has one holder, the engine, and still resolves', async () => { + install(P); + engine.registerFlow('engine_only', leaf('engine_only')); + ship(P, caller('process', 'engine_only')); + const result = await engine.execute('process'); + expect(result.success).toBe(true); + expect(ran).toEqual(['engine_only']); + }); +}); + +describe('red line 1 — resolution never loosens: a package caller is never served outside its closure', () => { + it('D3 (a): a name only an environment-authored flow holds is refused for a package caller, naming the environment', async () => { + install(P); + author(leaf('welcome')); + ship(P, caller('process', 'welcome')); + const result = await engine.execute('process'); + expect(result.success).toBe(false); + expect(result.error).toContain('held outside the declared dependency closure of package "com.acme.caller"'); + expect(result.error).toContain('the environment (an item authored in this environment, bound to no package)'); + expect(ran).toEqual([]); + }); + + it("D3 step 3: a name only a package outside the caller's closure holds is refused, naming that package", async () => { + install(Q); + install(P); + ship(Q, leaf('notify')); + ship(P, caller('process', 'notify')); + const result = await engine.execute('process'); + expect(result.success).toBe(false); + expect(result.error).toContain('held outside the declared dependency closure of package "com.acme.caller"'); + expect(result.error).toContain('com.acme.stranger'); + expect(ran).toEqual([]); + }); + + it('control: the same child, run by a door (a caller with no package), resolves environment-wide', async () => { + install(P); + author(leaf('welcome')); + const result = await engine.execute('welcome'); + expect(result.success).toBe(true); + expect(ran).toEqual(['welcome']); + }); +}); + +describe('red line 2 — ambiguity is reported, never guessed', () => { + it('a name two packages hold is refused at registration, naming both, and nothing is armed', async () => { + install(A); + install(Q); + registry.registerItem('flow', { ...leaf('notify'), _packageId: A }, 'name' as never, A); + registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); + expect(() => engine.registerFlow('notify', leaf('notify'))).toThrow( + /held by 2 packages in this environment[\s\S]*com\.acme\.alpha[\s\S]*com\.acme\.stranger/, + ); + expect(await engine.getFlow('notify')).toBeNull(); + }); + + it('control: a name one package holds arms as before', async () => { + install(A); + ship(A, leaf('notify')); + expect(await engine.getFlow('notify')).not.toBeNull(); + }); +}); + +describe('reading (b) — bare-name behaviour is unchanged for a name with one holder', () => { + it('a door runs a packaged flow by its bare name', async () => { + install(A); + ship(A, leaf('notify')); + const result = await engine.execute('notify'); + expect(result.success).toBe(true); + expect(ran).toEqual(['notify']); + }); + + it('with no resolver attached, a subflow reaches an environment flow as before', async () => { + engine.setFlowNameResolver(undefined); + install(P); + author(leaf('welcome')); + ship(P, caller('process', 'welcome')); + const result = await engine.execute('process'); + expect(result.success).toBe(true); + expect(ran).toEqual(['welcome']); + }); +}); + +describe('ADR-0150 D4 — the activation ledger switches off the (package, name) it names', () => { + it("a row naming the shipping package switches its flow off; another package's row does not", async () => { + install(A); + ship(A, leaf('notify')); + const store = new InMemoryFlowActivationStore(); + await store.setActive({ name: 'notify', packageId: Q, active: false }); + engine.setFlowActivationStore(store); + expect(await engine.hydrateFlowActivations()).toEqual([]); + expect((await engine.execute('notify')).success).toBe(true); + + await store.setActive({ name: 'notify', packageId: A, active: false }); + expect(await engine.hydrateFlowActivations()).toEqual(['notify']); + expect(await engine.execute('notify')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); + }); + + it('the toggle door writes and reads the row under the shipping package', async () => { + install(A); + ship(A, leaf('notify')); + const store = new InMemoryFlowActivationStore(); + engine.setFlowActivationStore(store); + await engine.toggleFlow('notify', false); + expect(await store.list()).toEqual([{ name: 'notify', packageId: A, active: false }]); + expect(await engine.execute('notify')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); + await engine.toggleFlow('notify', true); + expect((await engine.execute('notify')).success).toBe(true); + }); +}); + +describe('FlowActivationProjection', () => { + it('a row naming no package binds to the one holder', () => { + const projection = new FlowActivationProjection(() => A); + projection.add('notify'); + expect(projection.has('notify')).toBe(true); + projection.delete('notify'); + expect(projection.has('notify')).toBe(false); + }); + + it("answers for the package that ships the name, never another package's row", () => { + const projection = new FlowActivationProjection(() => A); + projection.add('notify', Q); + expect(projection.has('notify')).toBe(false); + projection.add('notify', A); + expect(projection.has('notify')).toBe(true); + }); + + it('with no reader to say who ships the name, every row of it still switches it off', () => { + const projection = new FlowActivationProjection(() => undefined); + projection.add('notify', Q); + expect(projection.has('notify')).toBe(true); + }); +}); diff --git a/packages/services/service-automation/src/index.ts b/packages/services/service-automation/src/index.ts index 0a0d5675909..6c1d01ca887 100644 --- a/packages/services/service-automation/src/index.ts +++ b/packages/services/service-automation/src/index.ts @@ -74,6 +74,10 @@ export type { // method is barrel-reachable, so a host building a custom composition // needs the name to hand it the loader's set. PackagedFlowSource, + // [ADR-0150 D3] The reader `AutomationEngine.setFlowNameResolver` takes — + // barrel-reachable through that method, for a host composing its own + // registry over the one package-scoped resolver. + FlowNameResolver, // [#28405] The reader `AutomationEngine.setFlowHistorySource` takes — // barrel-reachable through that method, for a host composing its own // metadata history. diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 1d4f72bd940..8c283d407bf 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -21,7 +21,10 @@ import { postureEnforcesWall, type TenancyPosture } from '@objectstack/spec/secu import type { MetadataMutationEvent, SysMetadataEngine } from '@objectstack/metadata-protocol'; import { SysMetadataRepository, shadowedStoredRowsOf } from '@objectstack/metadata-protocol'; import { AutomationEngine } from './engine.js'; -import type { AutomationEngineOptions, FlowHistorySource, RefusalI18nService, RunSummaryLogLevel } from './engine.js'; +import type { AutomationEngineOptions, FlowHistorySource, FlowNameResolver, RefusalI18nService, RunSummaryLogLevel } from './engine.js'; +// [ADR-0150 D3] The ONE package-scoped resolver, read through its exports only +// — never a second implementation of the rule in this package. +import { resolvePackageScopedName, type PackageScopedRegistry } from '@objectstack/objectql'; import { describeThrownForLog, thrownMessageText } from './thrown-cause-diagnostics.js'; import { defaultEnvCredentialResolver, type CredentialResolver } from './credential-resolver.js'; import { registerFlowCredentialRedactor } from './flow-credential-projection.js'; @@ -1142,6 +1145,42 @@ export function packagedFlowReader(ctx: Pick): (nam }; } +/** The registry members the package-scoped resolver reads ({@link PackageScopedRegistry}). */ +const PACKAGE_SCOPED_REGISTRY_MEMBERS = [ + 'getPackage', + 'getAllPackages', + 'packageScopedHoldersOf', + 'getPackageScopedItem', + 'getEnvironmentScopedItem', +] as const; + +/** + * [ADR-0150 D3] The engine's reader over the one package-scoped resolver: + * `resolvePackageScopedName` from `@objectstack/objectql`, asked of the + * registry ObjectQL serves, for the `flow` type. See + * `AutomationEngine.setFlowNameResolver` for the two seams that read it. + * + * Resolved at QUESTION time, never at boot, for {@link packagedFlowReader}'s + * reason. A composition with no ObjectQL — or whose registry offers none of + * the package-scoped reads — has no registry to ask, so the answer is + * `undefined` and the engine's own flow map answers as before: no item is + * named that the engine does not hold, and nothing is guessed. + */ +export function flowNameResolver(ctx: Pick): FlowNameResolver { + return (name, callerPackageId) => { + let registry: Partial> | undefined; + try { + registry = ctx.getService<{ registry?: typeof registry }>('objectql')?.registry; + } catch { + return undefined; + } + if (!registry || PACKAGE_SCOPED_REGISTRY_MEMBERS.some((member) => typeof registry![member] !== 'function')) { + return undefined; + } + return resolvePackageScopedName(registry as unknown as PackageScopedRegistry, { type: 'flow', name, callerPackageId }); + }; +} + /** * [#28405, ADR-0009 §2.1] The engine's reader of a flow's stored versions by * content identity: the metadata repository's `getByHash` over @@ -1761,6 +1800,11 @@ export class AutomationServicePlugin implements Plugin { // See `packagedFlowReader`. this.engine.setPackagedFlowSource(packagedFlowReader(ctx)); + // [ADR-0150 D3] Which item a bare flow name means, for a caller of a + // package or of none, is the one package-scoped resolver's answer over + // the ObjectQL registry, read at question time. See `flowNameResolver`. + this.engine.setFlowNameResolver(flowNameResolver(ctx)); + // [#28405] A waiting run resumes on the flow body it started on, read // back from the metadata history once the flow was republished. See // `flowHistoryReader`. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2ae1a87a2f3..c54d8102e75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2801,6 +2801,9 @@ importers: '@objectstack/metadata-protocol': specifier: workspace:* version: link:../../metadata-protocol + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects @@ -2817,9 +2820,6 @@ importers: '@objectstack/driver-sql': specifier: workspace:* version: link:../../drivers/driver-sql - '@objectstack/objectql': - specifier: workspace:* - version: link:../../objectql '@objectstack/plugin-audit': specifier: workspace:* version: link:../../plugins/plugin-audit From 68b6ca0aafbdf7c4f8471cc22764668b58b795d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:24:05 +0000 Subject: [PATCH 2/7] chore(changeset): declare the package-scoped flow resolution narrowing Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 Co-authored-by: Claude --- .../31672-flow-package-scoped-resolution.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .changeset/31672-flow-package-scoped-resolution.md diff --git a/.changeset/31672-flow-package-scoped-resolution.md b/.changeset/31672-flow-package-scoped-resolution.md new file mode 100644 index 00000000000..bd438d82f73 --- /dev/null +++ b/.changeset/31672-flow-package-scoped-resolution.md @@ -0,0 +1,19 @@ +--- +'@objectstack/service-automation': patch +--- + +feat(service-automation)!: the flow index and the activation ledger consult on (package, name), through the one package-scoped resolver (ADR-0150 D3/D4) + +Clause-②: no (narrowing) — a `subflow` or `map` node inside a packaged flow names its child by a bare name, and that name now resolves from the package that ships the flow (ADR-0150 D3): its own flow, else the one holder in its declared dependency closure (plus `sys`), else a refusal naming every candidate. Two cases that run today are refused: a name only an environment-authored flow holds (D3 (a)), and a name only a package outside the caller's declared closure holds (D3 step 3). No door, request or response shape, error code or status changes. One answer moves the other way, for a stale ledger row only: a row naming package Q no longer switches off package P's same-named flow (below). +Metadata-protocol: none + + + +**BREAKING** for a packaged flow whose `subflow` or `map` node names a flow its package cannot reach: one authored in the environment, or one shipped by a package it does not declare a dependency on. Measured first-party: 0 (every `subflow` / `map` `flowName` in this repository names a flow of its own package). + +- **Before.** The engine looked the child up by its bare name alone, whoever held it. +- **Now.** The child resolves from the calling flow's package through `resolvePackageScopedName` (`@objectstack/objectql`). A refused call fails the node with the resolver's sentence, which names every holder and the remedy; the child never runs. +- **Unchanged.** A child the calling package holds, or that one package in its declared closure holds, runs as before. A door, a trigger or any caller outside a run resolves environment-wide, so every bare name with one holder answers as before. A flow the registry knows nothing of (registered straight into the engine) has one holder and runs as before. An engine with no ObjectQL registry answers as before. +- **Also.** A flow name two packages hold is refused at registration, naming both, instead of arming the lexicographically first package's flow. Phase 1's one-holder refusal (ADR-0048 §3.4) already refuses the second holder at install, so no deployment reaches it today. The activation ledger's projection is keyed by `(package, name)`: a row switches off the flow of the package it names. So a row left by package Q for a name package P now ships no longer switches P's flow off; it is reachable only when one package's flow name passes to another package. A row that names no package, or any row when the engine cannot tell which package ships the name, switches the name off as before. + +**The remedy.** Declare a dependency on the package that ships the child (ADR-0141), or ship the child in the calling package. For an environment-authored child, move it into a package the caller depends on. From e94f303d2ad07b726af67b6e7b901fd6fad9d537 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:58:43 +0000 Subject: [PATCH 3/7] fix(service-automation): hold back the two-holder flow refusal; type the projection's receiver A flow name two packages hold reaches the engine only from a deployment that held the clash before phase 1, sealed at its cold boot with a warning. Refusing it is a maintainer ruling still open, and phase 1's cold-boot pins read it as armed, so the engine now acts only on the resolver's outside-closure refusal (D3 (a), D3 step 3) and the arming gate in registerFlow is left out. The activation projection's Set receiver is annotated so the tenant-audit census can place its delete(). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 --- .../31672-flow-package-scoped-resolution.md | 4 +- .../services/service-automation/src/engine.ts | 60 +++++++++++-------- .../src/flow-activation-projection.ts | 2 +- .../flow-package-scoped-resolution.test.ts | 23 ++----- 4 files changed, 43 insertions(+), 46 deletions(-) diff --git a/.changeset/31672-flow-package-scoped-resolution.md b/.changeset/31672-flow-package-scoped-resolution.md index bd438d82f73..6950b42d95f 100644 --- a/.changeset/31672-flow-package-scoped-resolution.md +++ b/.changeset/31672-flow-package-scoped-resolution.md @@ -13,7 +13,7 @@ Metadata-protocol: none - **Before.** The engine looked the child up by its bare name alone, whoever held it. - **Now.** The child resolves from the calling flow's package through `resolvePackageScopedName` (`@objectstack/objectql`). A refused call fails the node with the resolver's sentence, which names every holder and the remedy; the child never runs. -- **Unchanged.** A child the calling package holds, or that one package in its declared closure holds, runs as before. A door, a trigger or any caller outside a run resolves environment-wide, so every bare name with one holder answers as before. A flow the registry knows nothing of (registered straight into the engine) has one holder and runs as before. An engine with no ObjectQL registry answers as before. -- **Also.** A flow name two packages hold is refused at registration, naming both, instead of arming the lexicographically first package's flow. Phase 1's one-holder refusal (ADR-0048 §3.4) already refuses the second holder at install, so no deployment reaches it today. The activation ledger's projection is keyed by `(package, name)`: a row switches off the flow of the package it names. So a row left by package Q for a name package P now ships no longer switches P's flow off; it is reachable only when one package's flow name passes to another package. A row that names no package, or any row when the engine cannot tell which package ships the name, switches the name off as before. +- **Unchanged.** A flow name two packages hold — only a deployment that held the clash before phase 1 reaches one, sealed at its cold boot with a warning — is answered as before: refusing it awaits the maintainer's ruling (#31677). A child the calling package holds, or that one package in its declared closure holds, runs as before. A door, a trigger or any caller outside a run resolves environment-wide, so every bare name with one holder answers as before. A flow the registry knows nothing of (registered straight into the engine) has one holder and runs as before. An engine with no ObjectQL registry answers as before. +- **Also.** The activation ledger's projection is keyed by `(package, name)`: a row switches off the flow of the package it names. So a row left by package Q for a name package P now ships no longer switches P's flow off; it is reachable only when one package's flow name passes to another package. A row that names no package, or any row when the engine cannot tell which package ships the name, switches the name off as before. **The remedy.** Declare a dependency on the package that ships the child (ADR-0141), or ship the child in the calling package. For an environment-authored child, move it into a package the caller depends on. diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 952613960e3..e8779eb34da 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -227,7 +227,11 @@ import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-g // [ADR-0150 D3/D4] The one package-scoped resolver's answer, read through the // reader the host attaches (`setFlowNameResolver`), and the activation // projection keyed by `(package, name)`. -import type { PackageScopedRefusal, PackageScopedResolution } from '@objectstack/objectql'; +import type { + PackageScopedRefusal, + PackageScopedRefusalReason, + PackageScopedResolution, +} from '@objectstack/objectql'; import { FlowActivationProjection } from './flow-activation-projection.js'; import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; // [#25222] The consumed-suspension restore's bodies: journaling a consumed @@ -2583,6 +2587,23 @@ export type PackagedFlowSource = (name: string) => string | undefined; */ export type FlowNameResolver = (name: string, callerPackageId: string | null) => PackageScopedResolution | undefined; +/** + * [ADR-0150 D3] The resolver's refusals the engine acts on: a package caller + * whose bare name is held only outside its declared dependency closure — by + * an environment-authored flow (D3 (a)) or by a package it does not declare + * (D3 step 3). + * + * The two `ambiguous-*` refusals — a name two packages hold — are held back. + * Phase 1 refuses a second package holder at install, so such a name reaches + * the engine only from a deployment that held the clash before phase 1, whose + * cold boot seals it with a warning (`BARE_NAME_COLD_BOOT_MODE = 'warn'`). + * Whether that clash is refused is the maintainer's ruling (#31677); until + * then this seam leaves it exactly as it was before this reader existed, and + * the ruling adds the two reasons here and the arming gate in + * {@link AutomationEngine.registerFlow}. + */ +const FLOW_NAME_REFUSALS_ACTED_ON: ReadonlySet = new Set(['outside-closure']); + /** * [#28405] The stored body of flow `name` whose content identity is * `checksum` ({@link SuspendedRun.flowChecksum}), as the metadata history @@ -4557,13 +4578,6 @@ export class AutomationEngine implements IAutomationService { if (refusal) throw new Error(refusal.message); } - // [ADR-0150 D3/D4] The engine arms one flow per bare name, so a name - // the resolver cannot answer for a caller with no package — two - // packages hold it — is refused here, naming every holder, before - // anything is armed. ⛔ Never an arming by package id or by arrival. - const nameRefusal = this.flowNameRefusal(name, null); - if (nameRefusal) throw new Error(nameRefusal.message); - // Version history management const history = this.flowVersionHistory.get(name) ?? []; history.push({ @@ -4965,17 +4979,12 @@ export class AutomationEngine implements IAutomationService { * with a reader that asks the ObjectQL registry at question time, never at * boot, for {@link setPackagedFlowSource}'s reason. * - * Two seams read it, and only these two: - * - * - {@link registerFlow} asks it for a caller with no package before it - * arms a name, so a name two packages hold is refused, naming both, - * instead of arming one of them. The engine keeps one armed slot per - * bare name, and nothing picks between two holders. - * - {@link execute} asks it for the caller's package: the package that - * ships the flow whose run names the child (a `subflow` or `map` node's - * `flowName`, carried on the run's context as `flowName`), or no - * package for a door, a trigger or any caller outside a run. A refusal - * is the answer, naming every candidate; nothing is executed. + * One seam reads it: {@link execute} asks it for the caller's package — + * the package that ships the flow whose run names the child (a `subflow` + * or `map` node's `flowName`, carried on the run's context as `flowName`), + * or no package for a door, a trigger or any caller outside a run. A + * refusal the engine acts on ({@link FLOW_NAME_REFUSALS_ACTED_ON}) is the + * answer, naming every candidate; nothing is executed. * * A name the registry holds nothing under (a flow registered straight into * the engine) has one holder, the engine's own flow map, and resolves to @@ -4988,12 +4997,15 @@ export class AutomationEngine implements IAutomationService { /** * [ADR-0150 D3] The resolver's refusal of the bare flow name `name` for a * caller of package `callerPackageId` (`null`: no package), or `undefined` - * when the name resolves, names nothing in the registry, or no resolver is - * attached. Read-only; records nothing. + * when the name resolves, names nothing in the registry, is refused for a + * reason held back ({@link FLOW_NAME_REFUSALS_ACTED_ON}), or no resolver + * is attached. Read-only; records nothing. */ private flowNameRefusal(name: string, callerPackageId: string | null): PackageScopedRefusal | undefined { const resolution = this.flowNameResolver?.(name, callerPackageId); - return resolution?.status === 'refused' ? resolution : undefined; + return resolution?.status === 'refused' && FLOW_NAME_REFUSALS_ACTED_ON.has(resolution.reason) + ? resolution + : undefined; } /** @@ -6217,8 +6229,8 @@ export class AutomationEngine implements IAutomationService { const startTime = Date.now(); // [ADR-0150 D3] The bare name resolves for the caller's package first: // a run of package P's flow reaches P's own flow, else the one holder - // in P's declared dependency closure; anything else is refused with - // every candidate named, and nothing runs. Never dispatched, so no + // in P's declared dependency closure; a name held only outside that + // closure is refused with every candidate named, and nothing runs. Never dispatched, so no // `status`, for the reason the disabled exit below states. const nameRefusal = this.flowNameRefusal(flowName, this.flowCallerPackage(context)); if (nameRefusal) return { success: false, error: nameRefusal.message }; diff --git a/packages/services/service-automation/src/flow-activation-projection.ts b/packages/services/service-automation/src/flow-activation-projection.ts index f99cc6081cf..5e9b990d65c 100644 --- a/packages/services/service-automation/src/flow-activation-projection.ts +++ b/packages/services/service-automation/src/flow-activation-projection.ts @@ -57,7 +57,7 @@ export class FlowActivationProjection { /** Record that `(packageId, name)` is switched on (its row is active, or gone). */ delete(name: string, packageId?: string): void { - const packages = this.rows.get(name); + const packages: Set | undefined = this.rows.get(name); if (!packages) return; packages.delete(packageId ?? ''); if (packages.size === 0) this.rows.delete(name); diff --git a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts index c9a8902fae1..2f096422e05 100644 --- a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts +++ b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts @@ -13,6 +13,10 @@ * The epic's red lines are the `red line` cases. Each refusal pin was ablated * once (the engine's gate put back to "no refusal", the pin read red, * restored); the readings are in the PR body, not kept as test files. + * + * Red line 2's refusal of a name two packages hold is held back for the + * maintainer's ruling on a deployment sealed with such a clash (#31677; see + * `FLOW_NAME_REFUSALS_ACTED_ON` in the engine), so its pins land with it. */ import { describe, it, expect, beforeEach, vi } from 'vitest'; @@ -198,25 +202,6 @@ describe('red line 1 — resolution never loosens: a package caller is never ser }); }); -describe('red line 2 — ambiguity is reported, never guessed', () => { - it('a name two packages hold is refused at registration, naming both, and nothing is armed', async () => { - install(A); - install(Q); - registry.registerItem('flow', { ...leaf('notify'), _packageId: A }, 'name' as never, A); - registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); - expect(() => engine.registerFlow('notify', leaf('notify'))).toThrow( - /held by 2 packages in this environment[\s\S]*com\.acme\.alpha[\s\S]*com\.acme\.stranger/, - ); - expect(await engine.getFlow('notify')).toBeNull(); - }); - - it('control: a name one package holds arms as before', async () => { - install(A); - ship(A, leaf('notify')); - expect(await engine.getFlow('notify')).not.toBeNull(); - }); -}); - describe('reading (b) — bare-name behaviour is unchanged for a name with one holder', () => { it('a door runs a packaged flow by its bare name', async () => { install(A); From 9ed34ab5f9a031a3384c02b6261f4c06bd87239c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:07:38 +0000 Subject: [PATCH 4/7] fix(service-automation): report a held-back flow-name refusal once per name and caller Holding back the act on a name two packages hold waits for the maintainer's ruling; the report does not. The engine now warns once per (name, caller) with the resolver's sentence naming every candidate, and says the flow precedence's pick still runs until that ruling. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 --- .../services/service-automation/src/engine.ts | 52 +++++++++++++++---- .../flow-package-scoped-resolution.test.ts | 38 +++++++++++++- 2 files changed, 78 insertions(+), 12 deletions(-) diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index e8779eb34da..cb67ba725a4 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -227,10 +227,11 @@ import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-g // [ADR-0150 D3/D4] The one package-scoped resolver's answer, read through the // reader the host attaches (`setFlowNameResolver`), and the activation // projection keyed by `(package, name)`. -import type { - PackageScopedRefusal, - PackageScopedRefusalReason, - PackageScopedResolution, +import { + describePackageScopedHolder, + type PackageScopedRefusal, + type PackageScopedRefusalReason, + type PackageScopedResolution, } from '@objectstack/objectql'; import { FlowActivationProjection } from './flow-activation-projection.js'; import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; @@ -2598,9 +2599,11 @@ export type FlowNameResolver = (name: string, callerPackageId: string | null) => * the engine only from a deployment that held the clash before phase 1, whose * cold boot seals it with a warning (`BARE_NAME_COLD_BOOT_MODE = 'warn'`). * Whether that clash is refused is the maintainer's ruling (#31677); until - * then this seam leaves it exactly as it was before this reader existed, and - * the ruling adds the two reasons here and the arming gate in - * {@link AutomationEngine.registerFlow}. + * then this seam leaves the ACT exactly as it was before this reader existed, + * and the ruling adds the two reasons here and the arming gate in + * {@link AutomationEngine.registerFlow}. The REPORT is never held back: a + * held-back refusal is warned once per `(name, caller)`, naming every + * candidate ({@link AutomationEngine.reportHeldBackFlowRefusal}). */ const FLOW_NAME_REFUSALS_ACTED_ON: ReadonlySet = new Set(['outside-closure']); @@ -2821,6 +2824,11 @@ export class AutomationEngine implements IAutomationService { * knows, as before. */ private flowNameResolver?: FlowNameResolver; + /** + * [ADR-0150 D3, #31677] The `(name, caller)` pairs whose held-back + * refusal has been warned — see {@link reportHeldBackFlowRefusal}. + */ + private heldBackFlowRefusalsReported = new Set(); /** [#20790] The write-only flow credential channel — see {@link setFlowCredentialSource}. */ private flowCredentialSource?: FlowCredentialSource; /** [#20281 stage ③] The connector sync executor — see {@link setConnectorPullSource}. */ @@ -5003,9 +5011,33 @@ export class AutomationEngine implements IAutomationService { */ private flowNameRefusal(name: string, callerPackageId: string | null): PackageScopedRefusal | undefined { const resolution = this.flowNameResolver?.(name, callerPackageId); - return resolution?.status === 'refused' && FLOW_NAME_REFUSALS_ACTED_ON.has(resolution.reason) - ? resolution - : undefined; + if (resolution?.status !== 'refused') return undefined; + if (FLOW_NAME_REFUSALS_ACTED_ON.has(resolution.reason)) return resolution; + this.reportHeldBackFlowRefusal(resolution); + return undefined; + } + + /** + * [ADR-0150 D3, #31677] A refusal the engine does not act on yet is still + * reported: warned once per `(name, caller)`, with the resolver's sentence + * naming every candidate and the fact that the flow precedence's pick + * still runs until the maintainer rules (#31677 Q1). Holding back the act + * is the ruling's to lift; the report never waits for it. + */ + private reportHeldBackFlowRefusal(refusal: PackageScopedRefusal): void { + const key = JSON.stringify([refusal.name, refusal.callerPackageId]); + if (this.heldBackFlowRefusalsReported.has(key)) return; + this.heldBackFlowRefusalsReported.add(key); + this.logger.warn( + `[Automation] ${refusal.message} Until the maintainer rules on #31677 (Q1), this refusal is held back ` + + 'and the flow precedence\'s pick still runs.', + { + flow: refusal.name, + callerPackageId: refusal.callerPackageId, + reason: refusal.reason, + candidates: refusal.candidates.map(describePackageScopedHolder), + }, + ); } /** diff --git a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts index 2f096422e05..8f404a859b3 100644 --- a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts +++ b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts @@ -16,7 +16,8 @@ * * Red line 2's refusal of a name two packages hold is held back for the * maintainer's ruling on a deployment sealed with such a clash (#31677; see - * `FLOW_NAME_REFUSALS_ACTED_ON` in the engine), so its pins land with it. + * `FLOW_NAME_REFUSALS_ACTED_ON` in the engine), so its pins land with it — + * but never its report: the `held back` case pins the warning. */ import { describe, it, expect, beforeEach, vi } from 'vitest'; @@ -85,6 +86,8 @@ function caller(name: string, child: string) { let registry: SchemaRegistry; let engine: AutomationEngine; +/** The engine's own logger, so its warnings are readable. */ +let engineLogger: ReturnType; /** The loader's set: which package ships each flow name (the engine's `packagedFlowOwner`). */ let loaderSet: Record; /** The flows whose `mark` node ran, in order. */ @@ -110,7 +113,8 @@ beforeEach(() => { registry.logLevel = 'silent'; loaderSet = {}; ran = []; - engine = new AutomationEngine(silentLogger()); + engineLogger = silentLogger(); + engine = new AutomationEngine(engineLogger); const ctx = { logger: silentLogger(), getService(name: string) { @@ -202,6 +206,36 @@ describe('red line 1 — resolution never loosens: a package caller is never ser }); }); +describe('red line 2, held back (#31677) — the act waits for the ruling, the report does not', () => { + it('a name two packages hold is warned once per (name, caller), naming every candidate', async () => { + install(A); + install(Q); + install(P, [A, Q]); + registry.registerItem('flow', { ...leaf('notify'), _packageId: A }, 'name' as never, A); + registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); + loaderSet.notify = A; + engine.registerFlow('notify', leaf('notify')); + ship(P, caller('process', 'notify')); + + const heldBack = () => + engineLogger.warn.mock.calls.filter((call: unknown[]) => String(call[0]).includes('#31677')); + expect((await engine.execute('notify')).success).toBe(true); + expect((await engine.execute('notify')).success).toBe(true); + expect((await engine.execute('process')).success).toBe(true); + expect((await engine.execute('process')).success).toBe(true); + + const warned = heldBack(); + expect(warned).toHaveLength(2); + expect(warned.map((call: unknown[]) => (call[1] as { callerPackageId: string | null }).callerPackageId)) + .toEqual([null, P]); + for (const [message] of warned) { + expect(message).toContain('the flow precedence\'s pick still runs'); + expect(message).toContain('com.acme.alpha'); + expect(message).toContain('com.acme.stranger'); + } + }); +}); + describe('reading (b) — bare-name behaviour is unchanged for a name with one holder', () => { it('a door runs a packaged flow by its bare name', async () => { install(A); From c3116d289189b50fe6496940aa5e67a4b63a2f95 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:14:43 +0000 Subject: [PATCH 5/7] fix(service-automation): a stale activation row keeps the flow off and is reported A ledger row whose package no longer holds the flow name is stale: it keeps switching the name's current holder off, as before rows were keyed, and is warned once naming both packages and the remedy (switch the flow again, which writes the holder's own row). A row of a package that still holds the name keys only that package's flow, and the holder's own row, in either state, decides for it. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 --- .../services/service-automation/src/engine.ts | 18 ++- .../src/flow-activation-projection.ts | 107 +++++++++++++----- .../flow-package-scoped-resolution.test.ts | 54 ++++++++- 3 files changed, 144 insertions(+), 35 deletions(-) diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index cb67ba725a4..3f660d548d9 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2802,7 +2802,23 @@ export class AutomationEngine implements IAutomationService { // [ADR-0150 D4] Keyed by `(package, name)`: a row switches off the flow of // the package it names, read against the package that ships the name // today — see {@link FlowActivationProjection}. - private flowLedgerDisabled = new FlowActivationProjection((name) => this.packagedFlowOwner(name)); + private flowLedgerDisabled = new FlowActivationProjection({ + holderOf: (name) => this.packagedFlowOwner(name), + // A package still holds `name` when the resolver reaches that + // package's OWN flow for it; no resolver, no answer: stale. + stillHolds: (name, packageId) => { + const resolution = this.flowNameResolver?.(name, packageId); + return resolution?.status === 'resolved' && resolution.via === 'own'; + }, + reportStale: ({ name, rowPackageId, holderPackageId }) => + this.logger.warn( + `[Automation] The flow "${name}" is switched off by an activation row of package "${rowPackageId}", ` + + `which no longer holds that name; package "${holderPackageId}" ships it today. The row still ` + + 'switches the flow off. To keep it off or turn it on, switch the flow again: that writes ' + + `package "${holderPackageId}"'s own row.`, + { flow: name, rowPackageId, holderPackageId }, + ), + }); /** * The durable ledger behind {@link flowLedgerDisabled}. `null` until a host * attaches one via {@link setFlowActivationStore} — an engine with no diff --git a/packages/services/service-automation/src/flow-activation-projection.ts b/packages/services/service-automation/src/flow-activation-projection.ts index 5e9b990d65c..4cf79d48a63 100644 --- a/packages/services/service-automation/src/flow-activation-projection.ts +++ b/packages/services/service-automation/src/flow-activation-projection.ts @@ -3,8 +3,7 @@ /** * [ADR-0150 D4, "activation ledger"] The engine's local projection of the * activation ledger's `active: false` rows for flows, keyed by - * `(package, name)`: a switch belongs to the packaged flow it was flipped on, - * never to whatever item bears that name later. + * `(package, name)`: a switch belongs to the packaged flow it was flipped on. * * The ledger row has always carried the package (`FlowActivationRow.packageId`, * the loader's set's owner the toggle door attributes it to); the projection @@ -16,50 +15,100 @@ * writers are `hydrateFlowActivations` (from the ledger) and `toggleFlow` * (after the durable write), exactly as for the set it replaces. */ -export class FlowActivationProjection { - /** Flow name → the packages whose row switches it off; `''` is a row naming no package. */ - private readonly rows = new Map>(); +export interface FlowActivationProjectionReaders { + /** + * The package that ships the flow `name` today (the engine's + * `packagedFlowOwner`, the loader's set), or `undefined` when no reader + * can say. + */ + readonly holderOf: (name: string) => string | undefined; + /** + * Does package `packageId` still hold a flow named `name` of its own? + * `false` when it cannot be read: the row is then stale, and a stale row + * still switches the name off (never armed on a guess). + */ + readonly stillHolds: (name: string, packageId: string) => boolean; + /** + * A stale row switched the name's current holder off: reported once per + * `(name, row package)` by the projection. + */ + readonly reportStale: (stale: { name: string; rowPackageId: string; holderPackageId: string }) => void; +} +export class FlowActivationProjection { /** - * @param holderOf - the package that ships the flow `name` today (the - * engine's `packagedFlowOwner`, the loader's set), or `undefined` when - * no reader can say. + * Flow name → package → is that package's row `active: false`? `''` is a + * row naming no package. A package's row is kept in either state, so the + * holder's own row decides for it. */ - constructor(private readonly holderOf: (name: string) => string | undefined) {} + private readonly rows = new Map>(); + /** The `(name, row package)` pairs whose stale row has been reported. */ + private readonly staleReported = new Set(); + + constructor(private readonly readers: FlowActivationProjectionReaders) {} /** - * Is the flow `name` switched off by a ledger row? A row naming no package - * binds to the name's one holder (ADR-0150 D8: backfilled from the one - * holder), so it switches the name off as before. A row naming a package - * switches off that package's flow of the name, and only it: a row of - * another package, kept for a flow this deployment no longer ships under - * it, never switches off a different package's same-named flow. When no - * reader can say which package ships the name, every row of the name - * still switches it off — the projection never arms a flow on a guess. + * Is the flow `name` switched off by a ledger row? + * + * - The row of the package that ships the name decides, in either state. + * - Else a row naming no package binds to the name's one holder (ADR-0150 + * D8: backfilled from the one holder), so it switches the name off. + * - A row naming another package that still holds a flow of that name + * keys only that package's flow (D4), so it does not switch this one + * off. + * - A row naming a package that no longer holds the name is stale: it + * still switches the name's current holder off, as it did before rows + * were keyed, and it is reported once — the remedy is to switch the + * flow again, which writes the holder's own row. + * - When no reader can say which package ships the name, every + * switched-off row of the name switches it off. */ has(name: string): boolean { const packages = this.rows.get(name); if (!packages || packages.size === 0) return false; - if (packages.has('')) return true; - const holder = this.holderOf(name); - return holder === undefined ? true : packages.has(holder); + const holder = this.readers.holderOf(name); + if (holder !== undefined && packages.has(holder)) return packages.get(holder) === true; + if (packages.get('') === true) return true; + for (const [rowPackageId, off] of packages) { + if (!off || rowPackageId === '') continue; + if (holder === undefined) return true; + if (this.readers.stillHolds(name, rowPackageId)) continue; + const key = JSON.stringify([name, rowPackageId]); + if (!this.staleReported.has(key)) { + this.staleReported.add(key); + this.readers.reportStale({ name, rowPackageId, holderPackageId: holder }); + } + return true; + } + return false; } /** Record a row switching `(packageId, name)` off. */ add(name: string, packageId?: string): void { - let packages = this.rows.get(name); - if (!packages) { - packages = new Set(); - this.rows.set(name, packages); - } - packages.add(packageId ?? ''); + this.rowsOf(name).set(packageId ?? '', true); } - /** Record that `(packageId, name)` is switched on (its row is active, or gone). */ + /** + * Record that `(packageId, name)` is switched on: its row is active. With + * no package, the row naming no package is gone. + */ delete(name: string, packageId?: string): void { - const packages: Set | undefined = this.rows.get(name); + if (packageId !== undefined) { + this.rowsOf(name).set(packageId, false); + return; + } + const packages: Map | undefined = this.rows.get(name); if (!packages) return; - packages.delete(packageId ?? ''); + packages.delete(''); if (packages.size === 0) this.rows.delete(name); } + + private rowsOf(name: string): Map { + let packages: Map | undefined = this.rows.get(name); + if (!packages) { + packages = new Map(); + this.rows.set(name, packages); + } + return packages; + } } diff --git a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts index 8f404a859b3..b0dc94b4033 100644 --- a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts +++ b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts @@ -257,20 +257,49 @@ describe('reading (b) — bare-name behaviour is unchanged for a name with one h }); describe('ADR-0150 D4 — the activation ledger switches off the (package, name) it names', () => { - it("a row naming the shipping package switches its flow off; another package's row does not", async () => { + const staleWarnings = () => + engineLogger.warn.mock.calls.filter((call: unknown[]) => String(call[0]).includes('no longer holds that name')); + + it("a row naming the shipping package switches its flow off; a row of another package that still holds the name does not", async () => { install(A); + install(Q); ship(A, leaf('notify')); + // Q holds a flow of the same name too (a sealed clash); the engine armed A's. + registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); const store = new InMemoryFlowActivationStore(); await store.setActive({ name: 'notify', packageId: Q, active: false }); engine.setFlowActivationStore(store); expect(await engine.hydrateFlowActivations()).toEqual([]); expect((await engine.execute('notify')).success).toBe(true); + expect(staleWarnings()).toHaveLength(0); await store.setActive({ name: 'notify', packageId: A, active: false }); expect(await engine.hydrateFlowActivations()).toEqual(['notify']); expect(await engine.execute('notify')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); }); + it('a stale row — its package no longer holds the name — still switches the holder off, warned once naming both and the remedy', async () => { + install(A); + install(Q); + ship(A, leaf('notify')); + const store = new InMemoryFlowActivationStore(); + await store.setActive({ name: 'notify', packageId: Q, active: false }); + engine.setFlowActivationStore(store); + expect(await engine.hydrateFlowActivations()).toEqual(['notify']); + expect(await engine.execute('notify')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); + expect(await engine.execute('notify')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); + const warned = staleWarnings(); + expect(warned).toHaveLength(1); + expect(warned[0][0]).toContain('package "com.acme.stranger"'); + expect(warned[0][0]).toContain('package "com.acme.alpha" ships it today'); + expect(warned[0][0]).toContain('switch the flow again'); + + // The remedy: switching the flow writes the holder's own row. + await engine.toggleFlow('notify', true); + expect((await engine.execute('notify')).success).toBe(true); + expect(await store.list()).toContainEqual({ name: 'notify', packageId: A, active: true }); + }); + it('the toggle door writes and reads the row under the shipping package', async () => { install(A); ship(A, leaf('notify')); @@ -285,24 +314,39 @@ describe('ADR-0150 D4 — the activation ledger switches off the (package, name) }); describe('FlowActivationProjection', () => { + const readers = (holder: string | undefined, holds: string[] = [], reported: unknown[] = []) => ({ + holderOf: () => holder, + stillHolds: (_name: string, packageId: string) => holds.includes(packageId), + reportStale: (stale: unknown) => void reported.push(stale), + }); + it('a row naming no package binds to the one holder', () => { - const projection = new FlowActivationProjection(() => A); + const projection = new FlowActivationProjection(readers(A)); projection.add('notify'); expect(projection.has('notify')).toBe(true); projection.delete('notify'); expect(projection.has('notify')).toBe(false); }); - it("answers for the package that ships the name, never another package's row", () => { - const projection = new FlowActivationProjection(() => A); + it("a row of another package that still holds the name keys only that package", () => { + const projection = new FlowActivationProjection(readers(A, [Q])); projection.add('notify', Q); expect(projection.has('notify')).toBe(false); projection.add('notify', A); expect(projection.has('notify')).toBe(true); }); + it('a stale row switches the holder off and is reported once', () => { + const reported: unknown[] = []; + const projection = new FlowActivationProjection(readers(A, [], reported)); + projection.add('notify', Q); + expect(projection.has('notify')).toBe(true); + expect(projection.has('notify')).toBe(true); + expect(reported).toEqual([{ name: 'notify', rowPackageId: Q, holderPackageId: A }]); + }); + it('with no reader to say who ships the name, every row of it still switches it off', () => { - const projection = new FlowActivationProjection(() => undefined); + const projection = new FlowActivationProjection(readers(undefined)); projection.add('notify', Q); expect(projection.has('notify')).toBe(true); }); From c2f20313c111d6928ba72870c4b87f9502352aba Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:25:27 +0000 Subject: [PATCH 6/7] feat(service-automation): refuse a flow name two packages hold, a sealed clash included The maintainer ruled that a name two packages held before phase 1 is refused like any other two-holder name. The engine now refuses arming such a name and refuses running it, naming both holders, in place of the interim warning; the phase-1 dogfood pins on the sealed clash now read neither flow armed and the refusal in the boot log. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 --- .../31672-flow-package-scoped-resolution.md | 7 +- ...ame-one-holder-flow-family.dogfood.test.ts | 20 ++-- .../services/service-automation/src/engine.ts | 94 +++++-------------- .../flow-package-scoped-resolution.test.ts | 71 ++++++++------ 4 files changed, 84 insertions(+), 108 deletions(-) diff --git a/.changeset/31672-flow-package-scoped-resolution.md b/.changeset/31672-flow-package-scoped-resolution.md index 6950b42d95f..65beabd97dd 100644 --- a/.changeset/31672-flow-package-scoped-resolution.md +++ b/.changeset/31672-flow-package-scoped-resolution.md @@ -4,7 +4,7 @@ feat(service-automation)!: the flow index and the activation ledger consult on (package, name), through the one package-scoped resolver (ADR-0150 D3/D4) -Clause-②: no (narrowing) — a `subflow` or `map` node inside a packaged flow names its child by a bare name, and that name now resolves from the package that ships the flow (ADR-0150 D3): its own flow, else the one holder in its declared dependency closure (plus `sys`), else a refusal naming every candidate. Two cases that run today are refused: a name only an environment-authored flow holds (D3 (a)), and a name only a package outside the caller's declared closure holds (D3 step 3). No door, request or response shape, error code or status changes. One answer moves the other way, for a stale ledger row only: a row naming package Q no longer switches off package P's same-named flow (below). +Clause-②: no (narrowing) — a `subflow` or `map` node inside a packaged flow names its child by a bare name, and that name now resolves from the package that ships the flow (ADR-0150 D3): its own flow, else the one holder in its declared dependency closure (plus `sys`), else a refusal naming every candidate. Three cases that run today are refused: a name only an environment-authored flow holds (D3 (a)); a name only a package outside the caller's declared closure holds (D3 step 3); and a flow name two packages hold, which only a deployment sealed with a clash that predates phase 1 reaches (#31677 Q1, ruled A). No door, request or response shape, error code or status changes. One answer moves the other way, in a sealed clash only: an activation row of package Q, which still holds the flow name beside package P, no longer switches off P's same-named flow (below). Metadata-protocol: none @@ -13,7 +13,8 @@ Metadata-protocol: none - **Before.** The engine looked the child up by its bare name alone, whoever held it. - **Now.** The child resolves from the calling flow's package through `resolvePackageScopedName` (`@objectstack/objectql`). A refused call fails the node with the resolver's sentence, which names every holder and the remedy; the child never runs. -- **Unchanged.** A flow name two packages hold — only a deployment that held the clash before phase 1 reaches one, sealed at its cold boot with a warning — is answered as before: refusing it awaits the maintainer's ruling (#31677). A child the calling package holds, or that one package in its declared closure holds, runs as before. A door, a trigger or any caller outside a run resolves environment-wide, so every bare name with one holder answers as before. A flow the registry knows nothing of (registered straight into the engine) has one holder and runs as before. An engine with no ObjectQL registry answers as before. -- **Also.** The activation ledger's projection is keyed by `(package, name)`: a row switches off the flow of the package it names. So a row left by package Q for a name package P now ships no longer switches P's flow off; it is reachable only when one package's flow name passes to another package. A row that names no package, or any row when the engine cannot tell which package ships the name, switches the name off as before. +- **Unchanged.** A child the calling package holds, or that one package in its declared closure holds, runs as before. A door, a trigger or any caller outside a run resolves environment-wide, so every bare name with one holder answers as before. A flow the registry knows nothing of (registered straight into the engine) has one holder and runs as before. An engine with no ObjectQL registry answers as before. +- **Also.** The activation ledger's projection is keyed by `(package, name)`. The row of the package that ships the name decides for it, in either state. A row of another package that still holds a flow of that name keys only that package's flow, so it no longer switches the shipping package's flow off; only a deployment sealed with a pre-phase-1 clash has two such holders. A stale row, one whose package no longer holds the name, still switches the name off as before, and the engine now warns once naming both packages and the remedy: switch the flow again, which writes the shipping package's own row. A row that names no package, or any row when the engine cannot tell which package ships the name, switches the name off as before. +- **Also, a name two packages hold.** It is refused at registration, naming both, instead of arming the lexicographically first package's flow, and a run of it is refused the same way. Phase 1 refuses a second holder at install, so only a deployment that held the clash before phase 1 reaches this: its cold boot still seals with a warning (`BARE_NAME_COLD_BOOT_MODE = 'warn'`), and now neither flow is armed; the boot log names both. Measured first-party: 0 (across every boot of the dogfood battery, the cold boot's bare-name warning names one flow, the QA fixture's `qa_shared_flow`). The remedy is the warning's: rename one of the two flows. **The remedy.** Declare a dependency on the package that ships the child (ADR-0141), or ship the child in the calling package. For an environment-authored child, move it into a package the caller depends on. diff --git a/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts b/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts index 6328cb5582f..96fe4610537 100644 --- a/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts +++ b/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts @@ -15,11 +15,13 @@ // `AppPlugin` packages, `alpha` and `beta`, shipping one flow, one webhook, // one connector and one email template under the same names — boots, and // logs ONE bare-name warning line naming all four, both packages and the -// rename for every name; the automation engine's own flow precedence -// keeps arming one of the two flows, as before; +// rename for every name; the automation engine arms NEITHER of the two +// flows and logs the refusal naming both (ADR-0150 D3, #31677 Q1 ruled A: +// a name two packages held before phase 1 is refused like any other +// two-holder name); // - `POST /marketplace/install-local` of a third package declaring the held // flow name is 422 PLUGIN_REGISTER_FAILED naming both holders and the -// rename, installs nothing, and the engine keeps serving the armed flow; +// rename, installs nothing, and the engine still arms neither flow; // - the same door refusing a package that declares the held webhook name and // the showcase's own flow and email template names, naming the showcase; // - CONTROL: a package declaring fresh names installs — and so does one @@ -196,13 +198,15 @@ describe('one package holder per flow, webhook, connector and email template nam expect(line).not.toContain(BUILT_IN_TPL); expect(line).not.toContain(baseline!); expect(await packageIds(), 'both packages booted').toEqual(expect.arrayContaining(['com.qa.bare.alpha', 'com.qa.bare.beta'])); - // Unchanged by the rule: the automation engine's precedence still arms one flow, naming both. - expect(bootLines.some((l) => l.includes(`Flow name collision: '${FLOW}'`) && l.includes('com.qa.bare.alpha') && l.includes('com.qa.bare.beta'))).toBe(true); - expect(await armedFlowLabel(FLOW)).toBe('alpha flow'); + // [ADR-0150 D3, #31677 Q1] The automation engine arms neither flow: the arming is refused, naming both. + expect(bootLines.some((l) => + l.includes('failed to register flow') && l.includes(`"${FLOW}"`) && l.includes('held by 2 packages') + && l.includes('com.qa.bare.alpha') && l.includes('com.qa.bare.beta'))).toBe(true); + expect(await armedFlowLabel(FLOW)).toBeUndefined(); expect(await declaredWebhookPackage(HOOK)).toBe('com.qa.bare.alpha'); }); - it('install-local of a third package declaring a held flow name is 422 PLUGIN_REGISTER_FAILED naming both holders and the rename; nothing is installed, the armed flow is untouched', async () => { + it('install-local of a third package declaring a held flow name is 422 PLUGIN_REGISTER_FAILED naming both holders and the rename; nothing is installed, and neither flow is armed', async () => { const before = await packageIds(); const { status, body } = await installLocal(inline('gamma', { flows: [flow('gamma')] })); expect([status, codeOf(body)], JSON.stringify(body)).toEqual([422, 'PLUGIN_REGISTER_FAILED']); @@ -212,7 +216,7 @@ describe('one package holder per flow, webhook, connector and email template nam expect(message).toContain('com.qa.bare.beta'); expect(message).toContain(`"gamma_${FLOW}"`); expect(await packageIds(), 'the package list is unchanged').toEqual(before); - expect(await armedFlowLabel(FLOW)).toBe('alpha flow'); + expect(await armedFlowLabel(FLOW)).toBeUndefined(); }); it('install-local of a package declaring the held webhook name and the showcase\'s own flow and email template names is refused, naming the showcase', async () => { diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 3f660d548d9..810c7807648 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -227,12 +227,7 @@ import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-g // [ADR-0150 D3/D4] The one package-scoped resolver's answer, read through the // reader the host attaches (`setFlowNameResolver`), and the activation // projection keyed by `(package, name)`. -import { - describePackageScopedHolder, - type PackageScopedRefusal, - type PackageScopedRefusalReason, - type PackageScopedResolution, -} from '@objectstack/objectql'; +import type { PackageScopedRefusal, PackageScopedResolution } from '@objectstack/objectql'; import { FlowActivationProjection } from './flow-activation-projection.js'; import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; // [#25222] The consumed-suspension restore's bodies: journaling a consumed @@ -2588,25 +2583,6 @@ export type PackagedFlowSource = (name: string) => string | undefined; */ export type FlowNameResolver = (name: string, callerPackageId: string | null) => PackageScopedResolution | undefined; -/** - * [ADR-0150 D3] The resolver's refusals the engine acts on: a package caller - * whose bare name is held only outside its declared dependency closure — by - * an environment-authored flow (D3 (a)) or by a package it does not declare - * (D3 step 3). - * - * The two `ambiguous-*` refusals — a name two packages hold — are held back. - * Phase 1 refuses a second package holder at install, so such a name reaches - * the engine only from a deployment that held the clash before phase 1, whose - * cold boot seals it with a warning (`BARE_NAME_COLD_BOOT_MODE = 'warn'`). - * Whether that clash is refused is the maintainer's ruling (#31677); until - * then this seam leaves the ACT exactly as it was before this reader existed, - * and the ruling adds the two reasons here and the arming gate in - * {@link AutomationEngine.registerFlow}. The REPORT is never held back: a - * held-back refusal is warned once per `(name, caller)`, naming every - * candidate ({@link AutomationEngine.reportHeldBackFlowRefusal}). - */ -const FLOW_NAME_REFUSALS_ACTED_ON: ReadonlySet = new Set(['outside-closure']); - /** * [#28405] The stored body of flow `name` whose content identity is * `checksum` ({@link SuspendedRun.flowChecksum}), as the metadata history @@ -2840,11 +2816,6 @@ export class AutomationEngine implements IAutomationService { * knows, as before. */ private flowNameResolver?: FlowNameResolver; - /** - * [ADR-0150 D3, #31677] The `(name, caller)` pairs whose held-back - * refusal has been warned — see {@link reportHeldBackFlowRefusal}. - */ - private heldBackFlowRefusalsReported = new Set(); /** [#20790] The write-only flow credential channel — see {@link setFlowCredentialSource}. */ private flowCredentialSource?: FlowCredentialSource; /** [#20281 stage ③] The connector sync executor — see {@link setConnectorPullSource}. */ @@ -4602,6 +4573,13 @@ export class AutomationEngine implements IAutomationService { if (refusal) throw new Error(refusal.message); } + // [ADR-0150 D3/D4, #31677 Q1] The engine arms one flow per bare name, so + // a name the resolver cannot answer for a caller with no package — two + // packages hold it — is refused here, naming every holder, before + // anything is armed. ⛔ Never an arming by package id or by arrival. + const nameRefusal = this.flowNameRefusal(name, null); + if (nameRefusal) throw new Error(nameRefusal.message); + // Version history management const history = this.flowVersionHistory.get(name) ?? []; history.push({ @@ -5003,12 +4981,19 @@ export class AutomationEngine implements IAutomationService { * with a reader that asks the ObjectQL registry at question time, never at * boot, for {@link setPackagedFlowSource}'s reason. * - * One seam reads it: {@link execute} asks it for the caller's package — - * the package that ships the flow whose run names the child (a `subflow` - * or `map` node's `flowName`, carried on the run's context as `flowName`), - * or no package for a door, a trigger or any caller outside a run. A - * refusal the engine acts on ({@link FLOW_NAME_REFUSALS_ACTED_ON}) is the - * answer, naming every candidate; nothing is executed. + * Two seams read it, and only these two: + * + * - {@link registerFlow} asks it for a caller with no package before it + * arms a name, so a name two packages hold is refused, naming both, + * instead of arming one of them — a deployment sealed at its cold boot + * with a clash that predates phase 1 included (#31677 Q1, ruled A). + * The engine keeps one armed slot per bare name, and nothing picks + * between two holders. + * - {@link execute} asks it for the caller's package: the package that + * ships the flow whose run names the child (a `subflow` or `map` node's + * `flowName`, carried on the run's context as `flowName`), or no + * package for a door, a trigger or any caller outside a run. A refusal + * is the answer, naming every candidate; nothing is executed. * * A name the registry holds nothing under (a flow registered straight into * the engine) has one holder, the engine's own flow map, and resolves to @@ -5021,39 +5006,12 @@ export class AutomationEngine implements IAutomationService { /** * [ADR-0150 D3] The resolver's refusal of the bare flow name `name` for a * caller of package `callerPackageId` (`null`: no package), or `undefined` - * when the name resolves, names nothing in the registry, is refused for a - * reason held back ({@link FLOW_NAME_REFUSALS_ACTED_ON}), or no resolver - * is attached. Read-only; records nothing. + * when the name resolves, names nothing in the registry, or no resolver is + * attached. Read-only; records nothing. */ private flowNameRefusal(name: string, callerPackageId: string | null): PackageScopedRefusal | undefined { const resolution = this.flowNameResolver?.(name, callerPackageId); - if (resolution?.status !== 'refused') return undefined; - if (FLOW_NAME_REFUSALS_ACTED_ON.has(resolution.reason)) return resolution; - this.reportHeldBackFlowRefusal(resolution); - return undefined; - } - - /** - * [ADR-0150 D3, #31677] A refusal the engine does not act on yet is still - * reported: warned once per `(name, caller)`, with the resolver's sentence - * naming every candidate and the fact that the flow precedence's pick - * still runs until the maintainer rules (#31677 Q1). Holding back the act - * is the ruling's to lift; the report never waits for it. - */ - private reportHeldBackFlowRefusal(refusal: PackageScopedRefusal): void { - const key = JSON.stringify([refusal.name, refusal.callerPackageId]); - if (this.heldBackFlowRefusalsReported.has(key)) return; - this.heldBackFlowRefusalsReported.add(key); - this.logger.warn( - `[Automation] ${refusal.message} Until the maintainer rules on #31677 (Q1), this refusal is held back ` - + 'and the flow precedence\'s pick still runs.', - { - flow: refusal.name, - callerPackageId: refusal.callerPackageId, - reason: refusal.reason, - candidates: refusal.candidates.map(describePackageScopedHolder), - }, - ); + return resolution?.status === 'refused' ? resolution : undefined; } /** @@ -6277,8 +6235,8 @@ export class AutomationEngine implements IAutomationService { const startTime = Date.now(); // [ADR-0150 D3] The bare name resolves for the caller's package first: // a run of package P's flow reaches P's own flow, else the one holder - // in P's declared dependency closure; a name held only outside that - // closure is refused with every candidate named, and nothing runs. Never dispatched, so no + // in P's declared dependency closure; anything else is refused with + // every candidate named, and nothing runs. Never dispatched, so no // `status`, for the reason the disabled exit below states. const nameRefusal = this.flowNameRefusal(flowName, this.flowCallerPackage(context)); if (nameRefusal) return { success: false, error: nameRefusal.message }; diff --git a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts index b0dc94b4033..2d2bfca121e 100644 --- a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts +++ b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts @@ -13,11 +13,7 @@ * The epic's red lines are the `red line` cases. Each refusal pin was ablated * once (the engine's gate put back to "no refusal", the pin read red, * restored); the readings are in the PR body, not kept as test files. - * - * Red line 2's refusal of a name two packages hold is held back for the - * maintainer's ruling on a deployment sealed with such a clash (#31677; see - * `FLOW_NAME_REFUSALS_ACTED_ON` in the engine), so its pins land with it — - * but never its report: the `held back` case pins the warning. + */ import { describe, it, expect, beforeEach, vi } from 'vitest'; @@ -206,33 +202,46 @@ describe('red line 1 — resolution never loosens: a package caller is never ser }); }); -describe('red line 2, held back (#31677) — the act waits for the ruling, the report does not', () => { - it('a name two packages hold is warned once per (name, caller), naming every candidate', async () => { +describe('red line 2 — ambiguity is reported, never guessed', () => { + it('a name two packages hold is refused at registration, naming both, and nothing is armed', async () => { install(A); install(Q); - install(P, [A, Q]); registry.registerItem('flow', { ...leaf('notify'), _packageId: A }, 'name' as never, A); registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); - loaderSet.notify = A; - engine.registerFlow('notify', leaf('notify')); - ship(P, caller('process', 'notify')); + expect(() => engine.registerFlow('notify', leaf('notify'))).toThrow( + /held by 2 packages in this environment[\s\S]*com\.acme\.alpha[\s\S]*com\.acme\.stranger/, + ); + expect(await engine.getFlow('notify')).toBeNull(); + }); - const heldBack = () => - engineLogger.warn.mock.calls.filter((call: unknown[]) => String(call[0]).includes('#31677')); - expect((await engine.execute('notify')).success).toBe(true); - expect((await engine.execute('notify')).success).toBe(true); - expect((await engine.execute('process')).success).toBe(true); - expect((await engine.execute('process')).success).toBe(true); + it('a door run of a name armed before a second package took it (a sealed clash) is refused, naming both', async () => { + install(A); + install(Q); + ship(A, leaf('notify')); + registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); + const result = await engine.execute('notify'); + expect(result.success).toBe(false); + expect(result.error).toMatch(/held by 2 packages in this environment[\s\S]*com\.acme\.alpha[\s\S]*com\.acme\.stranger/); + expect(ran).toEqual([]); + }); - const warned = heldBack(); - expect(warned).toHaveLength(2); - expect(warned.map((call: unknown[]) => (call[1] as { callerPackageId: string | null }).callerPackageId)) - .toEqual([null, P]); - for (const [message] of warned) { - expect(message).toContain('the flow precedence\'s pick still runs'); - expect(message).toContain('com.acme.alpha'); - expect(message).toContain('com.acme.stranger'); - } + it("a package caller whose declared closure holds the name twice is refused, naming both", async () => { + install(A); + install(Q); + install(P, [A, Q]); + ship(A, leaf('notify')); + registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); + ship(P, caller('process', 'notify')); + const result = await engine.execute('process'); + expect(result.success).toBe(false); + expect(result.error).toMatch(/held by 2 packages in the declared dependency closure of package "com\.acme\.caller"/); + expect(ran).toEqual([]); + }); + + it('control: a name one package holds arms as before', async () => { + install(A); + ship(A, leaf('notify')); + expect(await engine.getFlow('notify')).not.toBeNull(); }); }); @@ -264,18 +273,22 @@ describe('ADR-0150 D4 — the activation ledger switches off the (package, name) install(A); install(Q); ship(A, leaf('notify')); - // Q holds a flow of the same name too (a sealed clash); the engine armed A's. + ship(A, caller('process', 'notify')); + // Q holds a flow of the same name too (a sealed clash); the engine armed A's, + // which A's own flow still reaches (its own item, D3 step 1). registry.registerItem('flow', { ...leaf('notify'), _packageId: Q }, 'name' as never, Q); const store = new InMemoryFlowActivationStore(); await store.setActive({ name: 'notify', packageId: Q, active: false }); engine.setFlowActivationStore(store); expect(await engine.hydrateFlowActivations()).toEqual([]); - expect((await engine.execute('notify')).success).toBe(true); + expect((await engine.execute('process')).success).toBe(true); + expect(ran).toEqual(['notify']); expect(staleWarnings()).toHaveLength(0); await store.setActive({ name: 'notify', packageId: A, active: false }); expect(await engine.hydrateFlowActivations()).toEqual(['notify']); - expect(await engine.execute('notify')).toMatchObject({ success: false, code: 'FLOW_DISABLED' }); + expect((await engine.execute('process')).success).toBe(false); + expect(ran).toEqual(['notify']); }); it('a stale row — its package no longer holds the name — still switches the holder off, warned once naming both and the remedy', async () => { From d7a38bb7506645ee24f9ce4a490a76e5723d8be2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 01:33:10 +0000 Subject: [PATCH 7/7] fix(service-automation): read the resolver's registry slice through one reader The merge brought the connector reconcile's own registry slice reader and a second import of the same type. The flow-name reader now asks that one reader too, so the slice the package-scoped resolver needs is checked in one place. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01ADHkmQjmHnuYAuaRd9k252 --- .../services/service-automation/src/plugin.ts | 22 +++++-------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index e395f4e2df7..0c65be51af4 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -24,7 +24,7 @@ import { AutomationEngine } from './engine.js'; import type { AutomationEngineOptions, FlowHistorySource, FlowNameResolver, RefusalI18nService, RunSummaryLogLevel } from './engine.js'; // [ADR-0150 D3] The ONE package-scoped resolver, read through its exports only // — never a second implementation of the rule in this package. -import { resolvePackageScopedName, type PackageScopedRegistry } from '@objectstack/objectql'; +import { resolvePackageScopedName } from '@objectstack/objectql'; import { describeThrownForLog, thrownMessageText } from './thrown-cause-diagnostics.js'; import { defaultEnvCredentialResolver, type CredentialResolver } from './credential-resolver.js'; import { registerFlowCredentialRedactor } from './flow-credential-projection.js'; @@ -1147,15 +1147,6 @@ export function packagedFlowReader(ctx: Pick): (nam }; } -/** The registry members the package-scoped resolver reads ({@link PackageScopedRegistry}). */ -const PACKAGE_SCOPED_REGISTRY_MEMBERS = [ - 'getPackage', - 'getAllPackages', - 'packageScopedHoldersOf', - 'getPackageScopedItem', - 'getEnvironmentScopedItem', -] as const; - /** * [ADR-0150 D3] The engine's reader over the one package-scoped resolver: * `resolvePackageScopedName` from `@objectstack/objectql`, asked of the @@ -1170,16 +1161,15 @@ const PACKAGE_SCOPED_REGISTRY_MEMBERS = [ */ export function flowNameResolver(ctx: Pick): FlowNameResolver { return (name, callerPackageId) => { - let registry: Partial> | undefined; + let registry: PackageScopedRegistry | undefined; try { - registry = ctx.getService<{ registry?: typeof registry }>('objectql')?.registry; + // The same slice reader the connector reconcile asks (E5's `packageScopedRegistryOf`). + registry = packageScopedRegistryOf(ctx.getService<{ registry?: unknown }>('objectql')?.registry); } catch { return undefined; } - if (!registry || PACKAGE_SCOPED_REGISTRY_MEMBERS.some((member) => typeof registry![member] !== 'function')) { - return undefined; - } - return resolvePackageScopedName(registry as unknown as PackageScopedRegistry, { type: 'flow', name, callerPackageId }); + if (!registry) return undefined; + return resolvePackageScopedName(registry, { type: 'flow', name, callerPackageId }); }; }