diff --git a/.changeset/31672-flow-package-scoped-resolution.md b/.changeset/31672-flow-package-scoped-resolution.md new file mode 100644 index 00000000000..65beabd97dd --- /dev/null +++ b/.changeset/31672-flow-package-scoped-resolution.md @@ -0,0 +1,20 @@ +--- +'@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. 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 + + + +**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.** 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 8fcea9a30b1..545486befd4 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,13 +15,14 @@ // `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; the declared webhook's +// rename for every name; the automation engine arms NEITHER of the two +// flows and logs the refusal naming both, and the declared webhook's // by-name read refuses the held name naming both packages (ADR-0150 D3, -// #31677: a clash held from before phase 1 is refused, not first-picked); +// #31677 Q1 ruled A: a clash held from before phase 1 is refused like any +// other two-holder name, not first-picked); // - `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 @@ -224,16 +225,18 @@ 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(); // ADR-0150 D3 (#31677, Q1 ruled A): the webhook the clash held before phase 1 // is no longer served by first registration — the by-name read refuses it, // naming both packages. await expectHeldWebhookRefused(); }); - 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']); @@ -243,7 +246,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 0d024d71bbc..810c7807648 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,26 @@ 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({ + 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 @@ -2774,6 +2809,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 +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({ @@ -4926,6 +4975,60 @@ 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 — 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 + * 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 +6233,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..4cf79d48a63 --- /dev/null +++ b/packages/services/service-automation/src/flow-activation-projection.ts @@ -0,0 +1,114 @@ +// 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. + * + * 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 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 { + /** + * 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. + */ + 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? + * + * - 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; + 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 { + this.rowsOf(name).set(packageId ?? '', true); + } + + /** + * 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 { + if (packageId !== undefined) { + this.rowsOf(name).set(packageId, false); + return; + } + const packages: Map | undefined = this.rows.get(name); + if (!packages) return; + 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-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 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. */ +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 = []; + engineLogger = silentLogger(); + engine = new AutomationEngine(engineLogger); + 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('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([]); + }); + + 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(); + }); +}); + +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', () => { + 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')); + 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('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('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 () => { + 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')); + 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', () => { + 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(readers(A)); + projection.add('notify'); + expect(projection.has('notify')).toBe(true); + projection.delete('notify'); + expect(projection.has('notify')).toBe(false); + }); + + 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(readers(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 2ff161ede91..0c65be51af4 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 } 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'; @@ -1144,6 +1147,32 @@ export function packagedFlowReader(ctx: Pick): (nam }; } +/** + * [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: PackageScopedRegistry | undefined; + try { + // The same slice reader the connector reconcile asks (E5's `packageScopedRegistryOf`). + registry = packageScopedRegistryOf(ctx.getService<{ registry?: unknown }>('objectql')?.registry); + } catch { + return undefined; + } + if (!registry) return undefined; + return resolvePackageScopedName(registry, { 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 @@ -1763,6 +1792,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`.