From fb77475fac94618c058480937162a85f3d41a02e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:35:21 +0000 Subject: [PATCH 01/15] fix(service-automation): a trigger binding does not dispatch a slot whose package is disabled A slot of a flow name two packages hold is judged when its trigger fires: while its package is disabled the run is skipped (said once at info), never substituted, and it dispatches again on re-enable with no re-arm. Slot keys, bindings and the dispatch holder do not move (ADR-0150 D3, seat ruling 6884403301 amendments 3 and 7). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../services/service-automation/src/engine.ts | 53 ++++++++ .../src/flow-slots-per-package.test.ts | 114 ++++++++++++++++++ 2 files changed, 167 insertions(+) diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index f1d40265eb1..a1b58d9187b 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2942,6 +2942,13 @@ export class AutomationEngine implements IAutomationService { private readonly flowSlots = new FlowSlotTable((name) => this.durableFlowHolder(name)?.status === 'refused'); /** [#31696] Slot keys whose trigger decline ({@link activateFlowTrigger}) has been said. */ private readonly sharedSlotTriggerWarned = new Set(); + /** + * [ADR-0150 D3, #33748] The slots (`PACKAGE/NAME`) whose trigger fired + * while their package was disabled, and whose skipped dispatch has been + * said ({@link triggerRun}). A slot leaves the set when it dispatches + * again, so the next disable is said again. + */ + private readonly disabledHolderDispatchSaid = new Set(); /** * [#31696] Where each key a slot change moved off went, for a run still * in flight under its start key ({@link flowKeyNow}). A key moved onto @@ -4413,6 +4420,13 @@ export class AutomationEngine implements IAutomationService { * released (an event the trigger took before the release landed) fires * nothing (`undefined`): the binding under its new key fires it once. A * slot of an unshared name runs through {@link execute}, as before. + * + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A slot of a + * name two packages hold whose package is disabled is not dispatched: no + * flow, no run, never another slot's. Asked when the trigger fires, not + * when it was armed: a runtime disable leaves the slot armed (a disable is + * reversible and moves no key, amendment 7), so the slot dispatches again + * the moment its package is enabled, with no re-arm. */ private triggerRun(armedKey: string): (ctx: AutomationContext) => Promise { const slot = this.flowSlots.slot(armedKey); @@ -4424,6 +4438,26 @@ export class AutomationEngine implements IAutomationService { return undefined; } if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); + if (slot.packageId !== null) { + const said = qualifiedFlowKey(slot.packageId, slot.name); + if (this.isDisabledHolderSlot(slot.name, slot.packageId)) { + // Said once per slot while its package stays disabled, at + // `info`: the skip IS the package switch working, and + // nothing that claims to be persisted is lost. + if (!this.disabledHolderDispatchSaid.has(said)) { + this.disabledHolderDispatchSaid.add(said); + this.logger.info( + `Trigger fired flow '${slot.name}' of package '${slot.packageId}', which is disabled — ` + + 'the flow was not run, no other package\'s flow of the name was run in its place, ' + + 'and no run-history row records it. It runs on its trigger again once the package ' + + 'is enabled.', + { flow: slot.name, package: slot.packageId, slot: key }, + ); + } + return undefined; + } + this.disabledHolderDispatchSaid.delete(said); + } // A trigger seeds `params.flowName` with the key it was armed // under; the run reads its flow's name there, never a slot key. const params = ctx.params as Record | undefined; @@ -5288,6 +5322,25 @@ export class AutomationEngine implements IAutomationService { return 'key' in resolved ? resolved.key : undefined; } + /** + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] Is the slot + * `(packageId, name)` held by a package that is disabled now? Asked of + * the one resolver ({@link flowNameResolver}), with that package as the + * caller: its own holding answers on the served read, and the run's read + * (`servedCaller`) answers `not-found` for it only while the package is + * disabled (amendment 4's caller-first rule). Both readings are needed: + * `not-found` alone would also cover a slot whose package the registry + * does not hold at all, which this question does not judge. No resolver + * attached: nothing is disabled here. + */ + private isDisabledHolderSlot(name: string, packageId: string): boolean { + const resolver = this.flowNameResolver; + if (resolver === undefined) return false; + const held = resolver(name, packageId); + if (held?.status !== 'resolved' || held.via !== 'own') return false; + return resolver(name, packageId, { servedCaller: true })?.status === 'not-found'; + } + /** [#31696] The package of the slot `key` files, or `undefined` (a package-less slot, or none). */ private flowSlotPackage(key: string): string | undefined { return this.flowSlots.slot(key)?.packageId ?? undefined; diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 6a4e7fd9b3f..3dd077dc143 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1069,3 +1069,117 @@ describe('[#33386] a run of a name two slots hold judges the served holders', () expect(answers[goOf(OPS)]).toMatchObject({ success: false, ran: [] }); }); }); + +/** + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A trigger + * binding of a slot whose package is disabled does not dispatch it: no run, + * never another package's flow in its place. Judged when the trigger fires, + * so a runtime disable (both slots stay armed) stops the slot and a re-enable + * dispatches it again with no re-arm. A boot disable arms nothing of the + * disabled package; the re-sync that arms it on enable makes it dispatch. + * The slot keys, the bindings and the dispatch holder do not move + * (amendment 7). A name one package holds is outside the ruling: its trigger + * answers as on `main` (CONTROL). + */ +describe('[#33748] a trigger binding does not dispatch a slot whose package is disabled', () => { + const tagOf = (packageId: string) => packageId.split('.').pop()!; + let armed: Map Promise>; + let started: string[]; + + beforeEach(() => { + armed = new Map(); + started = []; + engine.registerTrigger({ + type: 'record_change', + start: (b: { flowName: string }, callback: (c: unknown) => Promise) => { + started.push(b.flowName); + armed.set(b.flowName, callback); + }, + stop: (key: string) => { armed.delete(key); }, + } as unknown as FlowTrigger); + }); + + /** Fire every armed binding once, as a matching write would; the tags of what ran, sorted. */ + async function fireAll(): Promise { + ran = []; + for (const [key, callback] of armed) await callback({ params: { flowName: key } }); + return [...ran].sort(); + } + + function heldOnly(packageId: string, body: { name: string }): void { + registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId); + loaderSets[body.name] = [...new Set([...(loaderSets[body.name] ?? []), packageId])]; + } + + const skipSaid = () => engineLogger.info.mock.calls.filter(([message]: [string]) => /which is disabled — the flow was not run/.test(message)); + + describe.each([[P1, P2], [P2, P1]].map((order) => [order.map(tagOf).join(' then '), order] as const))('registered %s', (_o, order) => { + it.each([[P1, P2], [P2, P1]])('runtime disable, %s disabled: its slot is not dispatched, the other is; re-enabled, it dispatches again with no re-arm', async (off, on) => { + for (const holder of order) ship(holder, triggered('t', tagOf(holder))); + const bindings = engine.getActiveTriggerBindings(); + const startedBefore = [...started]; + expect([...armed.keys()].sort()).toEqual([`${P1}/t`, `${P2}/t`]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + + registry.disablePackage(off); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(skipSaid()).toHaveLength(1); + expect(skipSaid()[0][1]).toMatchObject({ flow: 't', package: off, slot: `${off}/t` }); + expect(engineLogger.error).not.toHaveBeenCalled(); + // Amendment 7: nothing durable moved, nothing was re-armed or released. + expect(engine.flowSlotKey(off, 't')).toBe(`${off}/t`); + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + expect(engine.flowDispatchHolder('t')).toMatchObject({ claimBare: false }); + expect(engine.getActiveTriggerBindings()).toEqual(bindings); + + registry.enablePackage(off); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + expect(started).toEqual(startedBefore); + // A later disable is said again. + registry.disablePackage(off); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(skipSaid()).toHaveLength(2); + }); + + it('runtime disable, both disabled: no slot is dispatched; each is said once', async () => { + for (const holder of order) ship(holder, triggered('t', tagOf(holder))); + registry.disablePackage(P1); + registry.disablePackage(P2); + expect(await fireAll()).toEqual([]); + expect(await fireAll()).toEqual([]); + expect(skipSaid().map(([, meta]: [string, { package: string }]) => meta.package).sort()).toEqual([P1, P2]); + expect(engine.flowSlotKey(P1, 't')).toBe(`${P1}/t`); + expect(engine.flowSlotKey(P2, 't')).toBe(`${P2}/t`); + }); + + it.each([[P1, P2], [P2, P1]])('boot disable, %s disabled (its flows not armed): it is not dispatched; enabled and re-synced, it is', async (off, on) => { + for (const holder of order) (holder === off ? heldOnly : ship)(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + expect([...armed.keys()].some((key) => key.startsWith(`${off}/`))).toBe(false); + expect(await fireAll()).not.toContain(tagOf(off)); + + // The enable's re-sync registers the package's flow (ADR-0150 D4: one slot per holder). + registry.enablePackage(off); + ship(off, triggered('t', tagOf(off))); + expect([...armed.keys()].sort()).toEqual([`${P1}/t`, `${P2}/t`]); + expect(await fireAll()).toEqual([tagOf(off), tagOf(on)].sort()); + }); + }); + + it('CONTROL — a name two packages hold, nothing disabled: both slots dispatch, nothing is said', async () => { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + expect(await fireAll()).toEqual(['alpha', 'beta']); + expect(skipSaid()).toEqual([]); + }); + + it('CONTROL — a name one package holds: its trigger answers as on `main`, disabled or not (outside the ruling)', async () => { + ship(P1, triggered('solo', 'alpha')); + expect([...armed.keys()]).toEqual(['solo']); + expect(await fireAll()).toEqual(['alpha']); + registry.disablePackage(P1); + expect(await fireAll()).toEqual(['alpha']); + expect(skipSaid()).toEqual([]); + }); +}); From d93d7556a7e0756ff1ac5981a3247bf726c1d439 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:36:37 +0000 Subject: [PATCH 02/15] test(service-automation): pin that only a disabled holder's slot is skipped Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../src/flow-slots-per-package.test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 3dd077dc143..06848390b0c 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1174,6 +1174,15 @@ describe('[#33748] a trigger binding does not dispatch a slot whose package is d expect(skipSaid()).toEqual([]); }); + it('CONTROL — two slots the registry no longer holds the name for (nothing disabled): both dispatch, as on `main`', async () => { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + // The resolver answers `not-found` for either package now; that is not a disable. + registry.unregisterItem('flow', 't'); + expect(await fireAll()).toEqual(['alpha', 'beta']); + expect(skipSaid()).toEqual([]); + }); + it('CONTROL — a name one package holds: its trigger answers as on `main`, disabled or not (outside the ruling)', async () => { ship(P1, triggered('solo', 'alpha')); expect([...armed.keys()]).toEqual(['solo']); From 89a737af683da1498fa1544cdd89d67b9fc14b09 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:37:16 +0000 Subject: [PATCH 03/15] test(service-automation): the not-found control reaches the not-found state Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../service-automation/src/flow-slots-per-package.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 06848390b0c..123b81dc3b6 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1179,6 +1179,9 @@ describe('[#33748] a trigger binding does not dispatch a slot whose package is d ship(P2, triggered('t', 'beta')); // The resolver answers `not-found` for either package now; that is not a disable. registry.unregisterItem('flow', 't'); + registry.unregisterItem('flow', 't'); + expect(flowNameResolver(ctx)('t', P1)).toEqual({ status: 'not-found' }); + expect(flowNameResolver(ctx)('t', P2)).toEqual({ status: 'not-found' }); expect(await fireAll()).toEqual(['alpha', 'beta']); expect(skipSaid()).toEqual([]); }); From e901d721693fd333b19231929c8f688b4b4abe54 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:40:25 +0000 Subject: [PATCH 04/15] chore: changeset for the disabled holder's trigger binding Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .changeset/33748-trigger-disabled-holder.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/33748-trigger-disabled-holder.md diff --git a/.changeset/33748-trigger-disabled-holder.md b/.changeset/33748-trigger-disabled-holder.md new file mode 100644 index 00000000000..573313b7e93 --- /dev/null +++ b/.changeset/33748-trigger-disabled-holder.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation): a trigger binding does not dispatch a slot whose package is disabled + +Clause-②: no +Metadata-protocol: none + +When two packages each ship a flow of the same name, the engine holds one slot per package and arms each slot's trigger (record-change, schedule, time-relative, api inbound hook). Until now a slot whose package was disabled at runtime kept running on its trigger, because the run a trigger fires executed the armed slot without asking whether its package is still served. + +Now the engine asks when the trigger fires. While the slot's package is disabled, the run is skipped: nothing runs, no other package's flow of the name runs in its place, and no run-history row is written. The skip is logged once at `info` per slot while the package stays disabled. When the package is enabled again, the slot runs on its trigger again, with no re-arm. + +Nothing durable moves: slot keys, run keys, the trigger bindings and the dispatch holder stay judged over every holder, so there is nothing to migrate. A flow name only one package ships answers as before. From 630502c22204d051e808c4082a90981b143b2360 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:51:38 +0000 Subject: [PATCH 05/15] fix(service-automation)!: declare the disabled holder's trigger skip as a narrowing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The changeset carries Clause-② no (narrowing), the BREAKING banner, the ADR-0087 not-required marker, and says an event fired while the package is disabled is dropped, not replayed. The single-holder CONTROL reads "as on main today". Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .changeset/33748-trigger-disabled-holder.md | 12 +++++++++--- .../src/flow-slots-per-package.test.ts | 6 +++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.changeset/33748-trigger-disabled-holder.md b/.changeset/33748-trigger-disabled-holder.md index 573313b7e93..ef771a1d1ff 100644 --- a/.changeset/33748-trigger-disabled-holder.md +++ b/.changeset/33748-trigger-disabled-holder.md @@ -2,13 +2,19 @@ '@objectstack/service-automation': patch --- -fix(service-automation): a trigger binding does not dispatch a slot whose package is disabled +fix(service-automation)!: a trigger binding does not dispatch a slot whose package is disabled (ADR-0150 D3) -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: none -When two packages each ship a flow of the same name, the engine holds one slot per package and arms each slot's trigger (record-change, schedule, time-relative, api inbound hook). Until now a slot whose package was disabled at runtime kept running on its trigger, because the run a trigger fires executed the armed slot without asking whether its package is still served. + + +**BREAKING** for a deployment where two packages each ship a flow of the same name and one of them is disabled at runtime: that package's flow no longer runs on its trigger (record-change, schedule, time-relative, or an api inbound hook's queued post). Before this release it kept running. + +When two packages each ship a flow of the same name, the engine holds one slot per package and arms each slot's trigger. Until now a slot whose package was disabled at runtime kept running on its trigger, because the run a trigger fires executed the armed slot without asking whether its package is still served. Now the engine asks when the trigger fires. While the slot's package is disabled, the run is skipped: nothing runs, no other package's flow of the name runs in its place, and no run-history row is written. The skip is logged once at `info` per slot while the package stays disabled. When the package is enabled again, the slot runs on its trigger again, with no re-arm. +An event that fires while the package is disabled is dropped, not replayed when the package is enabled again: a one-shot schedule or time-relative fire that falls inside the disable is lost, as it is for a switched-off flow. + Nothing durable moves: slot keys, run keys, the trigger bindings and the dispatch holder stay judged over every holder, so there is nothing to migrate. A flow name only one package ships answers as before. diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 123b81dc3b6..5d24798de88 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1078,8 +1078,8 @@ describe('[#33386] a run of a name two slots hold judges the served holders', () * dispatches it again with no re-arm. A boot disable arms nothing of the * disabled package; the re-sync that arms it on enable makes it dispatch. * The slot keys, the bindings and the dispatch holder do not move - * (amendment 7). A name one package holds is outside the ruling: its trigger - * answers as on `main` (CONTROL). + * (amendment 7). A name one package holds: its trigger answers as on `main` + * today (CONTROL). */ describe('[#33748] a trigger binding does not dispatch a slot whose package is disabled', () => { const tagOf = (packageId: string) => packageId.split('.').pop()!; @@ -1186,7 +1186,7 @@ describe('[#33748] a trigger binding does not dispatch a slot whose package is d expect(skipSaid()).toEqual([]); }); - it('CONTROL — a name one package holds: its trigger answers as on `main`, disabled or not (outside the ruling)', async () => { + it('CONTROL — a name one package holds: its trigger answers as on `main` today, disabled or not', async () => { ship(P1, triggered('solo', 'alpha')); expect([...armed.keys()]).toEqual(['solo']); expect(await fireAll()).toEqual(['alpha']); From 998cb968887ae4c7c37a5c56ce3604f432299869 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:22:13 +0000 Subject: [PATCH 06/15] fix(service-automation)!: a disabled package's flow of a name it holds alone is not dispatched by its trigger, and the bare entries answer as for no flow A flow name one package holds, that package disabled while the engine still holds its slot (a disable whose re-sync failed or did not run): its trigger binding is not dispatched (said once at info), and execute, getFlow and toggleFlow answer as for a flow the engine does not hold, which is what the namespaced address answers. A re-enable dispatches it again with no re-arm. The durable reads (slot key, dispatch holder, version history) do not move. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .changeset/33905-disabled-sole-holder-flow.md | 25 +++++ .../automation-addressed-route.test.ts | 72 +++++++++++++++ .../services/service-automation/src/engine.ts | 49 +++++++--- .../src/flow-slots-per-package.test.ts | 92 ++++++++++++++++++- 4 files changed, 223 insertions(+), 15 deletions(-) create mode 100644 .changeset/33905-disabled-sole-holder-flow.md diff --git a/.changeset/33905-disabled-sole-holder-flow.md b/.changeset/33905-disabled-sole-holder-flow.md new file mode 100644 index 00000000000..3f488c9f088 --- /dev/null +++ b/.changeset/33905-disabled-sole-holder-flow.md @@ -0,0 +1,25 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation)!: a flow whose only holder's package is disabled is not run by its trigger, and the engine's bare entries answer as for no flow (ADR-0150 D3) + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a deployment where a package that alone ships a flow name is disabled while the automation engine still holds that flow (the re-sync that follows a disable failed or did not run): the flow no longer runs, and the bare entries no longer serve it. Before this release it kept running and was served. + +What moves, for such a flow, while its package is disabled: + +- Its trigger binding (record-change, schedule, time-relative, or an api inbound hook's queued post) ran the flow. Now nothing runs and no run-history row is written; the skip is logged once at `info` per slot. +- `execute(name, …)`, by any caller, a `subflow` or `map` node's call included, ran the flow. It now answers `{ success: false, error: "Flow 'NAME' not found" }`, the answer for a flow the engine does not hold. +- `getFlow(name)` answered the flow. It now answers `null`, so the bare HTTP doors that ask it first (`GET /automation/NAME`, `POST /automation/NAME/trigger`, `POST /automation/trigger/NAME`, `POST /automation/NAME/toggle`, `POST /automation/NAME/clone`, `GET /automation/NAME/runs`) answer `404`, which is what the namespaced address `/automation/NAMESPACE/NAME…` already answered. +- `toggleFlow(name, …)` switched the flow. It now rejects with `Flow 'NAME' not found`. + +Remedy: enable the package. Its flow runs on its trigger again with no re-arm, and the bare entries serve it again. + +An event that fires while the package is disabled is dropped, not replayed when the package is enabled again. + +Nothing durable moves: the slot key, run keys, the trigger binding, the dispatch holder, credentials and the version history stay judged over every holder. Resuming a run parked before the disable is not decided here. A flow no package ships (the environment's own, or one registered straight into the engine) answers as before. diff --git a/packages/runtime/src/domains/automation-addressed-route.test.ts b/packages/runtime/src/domains/automation-addressed-route.test.ts index 65b7251a8cd..a0e79045ea2 100644 --- a/packages/runtime/src/domains/automation-addressed-route.test.ts +++ b/packages/runtime/src/domains/automation-addressed-route.test.ts @@ -636,3 +636,75 @@ describe('[#33386] the by-name doors judge the served holders of a name two pack }); }); }); + +/** + * [ADR-0150 D3, #33905] A flow name one package holds, that package disabled, + * over a real `SchemaRegistry`: its namespaced address is refused `404` at + * admission, before the service is asked. The bare path reaches the engine, + * whose bare entries now answer as for a flow it does not hold (`getFlow` + * `null`, pinned in service-automation's `flow-slots-per-package.test.ts`), + * so each bare door answers what the address answers. The service here + * answers as the engine does for such a flow. + */ +describe('[#33905] a flow whose only holder\'s package is disabled: the bare door answers as its namespaced address (404)', () => { + function registryHolding(disabled: boolean) { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + registry.installPackage({ id: CRM, name: CRM, version: '1.0.0', type: 'app', namespace: 'crm' } as never, 'code'); + registry.registerItem('flow', { name: 'solo', _packageId: CRM }, 'name' as never, CRM); + if (disabled) registry.disablePackage(CRM); + return registry; + } + + function dispatcherOver(registry: SchemaRegistry, held: boolean) { + const automation = { + handlerReady: true, + getFlow: vi.fn(async (name: string) => (held && name === 'solo' ? { name } : null)), + execute: vi.fn(async (name: string) => (held ? { success: true, output: {} } : { success: false, error: `Flow '${name}' not found` })), + toggleFlow: vi.fn(async (name: string) => { if (!held) throw new Error(`Flow '${name}' not found`); }), + listRunsPage: vi.fn(async () => ({ runs: [] as unknown[], hasMore: false })), + getActionDescriptors: vi.fn(() => []), + getFlowRuntimeStates: vi.fn(() => []), + }; + const services: Record = { automation, objectql: { registry } }; + const resolve = (name: string) => services[name]; + const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } }; + const dispatcher = new HttpDispatcher(kernel); + const call = async (path: string, method: string, body: unknown = {}) => { + const answered = await dispatcher.handleAutomation(path, method, body, { request: {}, executionContext: ADMIN } as any, {}); + return { status: answered.response?.status ?? 200, body: answered.response?.body as any }; + }; + return { call, automation }; + } + + const DOORS: ReadonlyArray = [ + ['/solo', '/crm/solo', 'GET', {}], + ['/solo/trigger', '/crm/solo/trigger', 'POST', {}], + ['/trigger/solo', '/trigger/crm/solo', 'POST', {}], + ['/solo/toggle', '/crm/solo/toggle', 'POST', { enabled: false }], + ['/solo/runs', '/crm/solo/runs', 'GET', {}], + ]; + + it('each bare door answers 404 as its namespaced address does; nothing runs or switches (FROM: the bare door served the flow)', async () => { + const { call, automation } = dispatcherOver(registryHolding(true), false); + for (const [bare, addressed, method, body] of DOORS) { + const viaAddress = await call(addressed, method, body); + const viaBare = await call(bare, method, body); + expect([bare, viaBare.status, codeOf(viaBare)]).toEqual([bare, 404, codeOf(viaAddress)]); + expect([addressed, viaAddress.status]).toEqual([addressed, 404]); + } + expect(automation.execute).not.toHaveBeenCalled(); + expect(automation.toggleFlow).not.toHaveBeenCalled(); + expect(automation.listRunsPage).not.toHaveBeenCalled(); + }); + + it('CONTROL — the package enabled: the address is its bare path, and both serve the flow', async () => { + const { call } = dispatcherOver(registryHolding(false), true); + for (const [bare, addressed, method, body] of DOORS) { + const viaAddress = await call(addressed, method, body); + const viaBare = await call(bare, method, body); + expect([bare, viaBare.status]).toEqual([bare, 200]); + expect([addressed, viaAddress.status]).toEqual([addressed, 200]); + } + }); +}); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a1b58d9187b..683aa7e517d 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -4421,12 +4421,15 @@ export class AutomationEngine implements IAutomationService { * nothing (`undefined`): the binding under its new key fires it once. A * slot of an unshared name runs through {@link execute}, as before. * - * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A slot of a - * name two packages hold whose package is disabled is not dispatched: no - * flow, no run, never another slot's. Asked when the trigger fires, not - * when it was armed: a runtime disable leaves the slot armed (a disable is - * reversible and moves no key, amendment 7), so the slot dispatches again - * the moment its package is enabled, with no re-arm. + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A slot whose + * package is disabled is not dispatched: no flow, no run, never another + * slot's. Asked when the trigger fires, not when it was armed: a runtime + * disable leaves the slot armed (a disable is reversible and moves no key, + * amendment 7), so the slot dispatches again the moment its package is + * enabled, with no re-arm. [#33905] The same for the slot of a name one + * package holds (ADR-0150 D3: a disabled package holds no name), which the + * re-sync of the disable withdraws on the normal path; a package-less slot + * is no package's, and runs as before. */ private triggerRun(armedKey: string): (ctx: AutomationContext) => Promise { const slot = this.flowSlots.slot(armedKey); @@ -4437,8 +4440,7 @@ export class AutomationEngine implements IAutomationService { this.logger.debug(`Trigger fired flow '${armedKey}' after it moved or left and was released: not run.`); return undefined; } - if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); - if (slot.packageId !== null) { + if (slot && slot.packageId !== null) { const said = qualifiedFlowKey(slot.packageId, slot.name); if (this.isDisabledHolderSlot(slot.name, slot.packageId)) { // Said once per slot while its package stays disabled, at @@ -4458,6 +4460,7 @@ export class AutomationEngine implements IAutomationService { } this.disabledHolderDispatchSaid.delete(said); } + if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); // A trigger seeds `params.flowName` with the key it was armed // under; the run reads its flow's name there, never a slot key. const params = ctx.params as Record | undefined; @@ -5273,7 +5276,11 @@ export class AutomationEngine implements IAutomationService { if (isSlotKeySpelling(name)) return { key: unfiledFlowKey(name) }; if (!this.flowSlots.isShared(name)) { const refusal = this.flowNameRefusal(name, callerPackageId); - return refusal ? { refusal } : { key: name }; + if (refusal) return { refusal }; + // [#33905] Its one holder's package is disabled: no flow, as for a + // name two packages hold that no served holder reaches. + if (options?.durable !== true && this.isDisabledSoleHolder(name)) return { absent: true }; + return { key: name }; } const resolution = this.flowNameResolver?.(name, callerPackageId, options?.durable === true ? { includeDisabledPackages: true } : { servedCaller: true }); @@ -5312,11 +5319,14 @@ export class AutomationEngine implements IAutomationService { * a name two slots hold is its one served holder's slot, refused naming * the served holders when two or more serve it, and `undefined` (no flow) * when none does. Seat ruling 6884403301, amendment 9: these entries move - * with the doors. + * with the doors. [#33905] A name one package holds whose package is + * disabled is no flow here either ({@link isDisabledSoleHolder}): the + * entries answer as for a flow this engine does not hold, which is the + * namespaced address's answer. */ private servedBareFlowKey(name: string): string | undefined { if (isSlotKeySpelling(name)) return undefined; - if (!this.flowSlots.isShared(name)) return name; + if (!this.flowSlots.isShared(name)) return this.isDisabledSoleHolder(name) ? undefined : name; const resolved = this.resolveFlowKey(name, null); if ('refusal' in resolved) throw new PackageScopedNameRefusedError(resolved.refusal); return 'key' in resolved ? resolved.key : undefined; @@ -5341,6 +5351,20 @@ export class AutomationEngine implements IAutomationService { return resolver(name, packageId, { servedCaller: true })?.status === 'not-found'; } + /** + * [ADR-0150 D3, #33905; #28117 ruling A] Is the one slot of the unshared + * name `name` held by a package that is disabled now + * ({@link isDisabledHolderSlot})? A package-less slot, or none, is not: + * a flow registered straight into the engine, or the environment's own, + * is no package's to disable. Only the entries that read or run a flow + * ask it; the durable reads (slot and run keys, {@link flowDispatchHolder}, + * credentials, history) stay judged over every holder (amendment 7). + */ + private isDisabledSoleHolder(name: string): boolean { + const packageId = this.flowSlotPackage(name); + return packageId !== undefined && this.isDisabledHolderSlot(name, packageId); + } + /** [#31696] The package of the slot `key` files, or `undefined` (a package-less slot, or none). */ private flowSlotPackage(key: string): string | undefined { return this.flowSlots.slot(key)?.packageId ?? undefined; @@ -5826,6 +5850,8 @@ export class AutomationEngine implements IAutomationService { * [#31696] Refused (409, naming both) for a name two packages serve: see * {@link getFlowSlot}. [#33386] Judged over the served holders * ({@link servedBareFlowKey}): one served holder's flow, `null` when none. + * [#33905] `null` too for a name one package holds whose package is + * disabled. */ async getFlow(name: string): Promise { const key = this.servedBareFlowKey(name); @@ -7651,6 +7677,7 @@ export class AutomationEngine implements IAutomationService { const resolved = this.resolveFlowKey(flowName, this.flowCallerPackage(context)); if ('refusal' in resolved) return { success: false, error: resolved.refusal.message }; // [#33386] No served holder reaches the name: as for a flow this engine does not hold. + // [#33905] Nor does a disabled package's flow of a name it holds alone. if ('absent' in resolved) return { success: false, error: `Flow '${flowName}' not found` }; return this.executeKey(resolved.key, context, startTime); } diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 5d24798de88..840a5e29ba1 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1078,8 +1078,8 @@ describe('[#33386] a run of a name two slots hold judges the served holders', () * dispatches it again with no re-arm. A boot disable arms nothing of the * disabled package; the re-sync that arms it on enable makes it dispatch. * The slot keys, the bindings and the dispatch holder do not move - * (amendment 7). A name one package holds: its trigger answers as on `main` - * today (CONTROL). + * (amendment 7). [#33905] A name one package holds is judged the same way + * (ADR-0150 D3: a disabled package holds no name). */ describe('[#33748] a trigger binding does not dispatch a slot whose package is disabled', () => { const tagOf = (packageId: string) => packageId.split('.').pop()!; @@ -1186,12 +1186,96 @@ describe('[#33748] a trigger binding does not dispatch a slot whose package is d expect(skipSaid()).toEqual([]); }); - it('CONTROL — a name one package holds: its trigger answers as on `main` today, disabled or not', async () => { + it('[#33905] a name one package holds, disabled at runtime with its slot left armed: not dispatched, said once; re-enabled, it dispatches with no re-arm (FROM: dispatched while disabled)', async () => { ship(P1, triggered('solo', 'alpha')); expect([...armed.keys()]).toEqual(['solo']); expect(await fireAll()).toEqual(['alpha']); + const bindings = engine.getActiveTriggerBindings(); + const startedBefore = [...started]; + registry.disablePackage(P1); + expect(await fireAll()).toEqual([]); + expect(await fireAll()).toEqual([]); + expect(skipSaid()).toHaveLength(1); + expect(skipSaid()[0][1]).toMatchObject({ flow: 'solo', package: P1, slot: 'solo' }); + expect(engineLogger.error).not.toHaveBeenCalled(); + // Amendment 7: the slot stays armed under its key, nothing released. + expect(engine.flowSlotKey(P1, 'solo')).toBe('solo'); + expect(engine.getActiveTriggerBindings()).toEqual(bindings); + + registry.enablePackage(P1); expect(await fireAll()).toEqual(['alpha']); - expect(skipSaid()).toEqual([]); + expect(started).toEqual(startedBefore); + registry.disablePackage(P1); + expect(await fireAll()).toEqual([]); + expect(skipSaid()).toHaveLength(2); + }); +}); + +/** + * [ADR-0150 D3, #33905; #28117 ruling A] A flow whose only holder's package + * is disabled, while the engine still holds its slot (a disable whose re-sync + * failed or did not run): the engine's bare entries that read or run a flow + * (`execute`, `getFlow`, `toggleFlow`) answer as for a flow this engine does + * not hold, which is what the namespaced address answers (404). The durable + * reads stay judged over every holder (amendment 7): the slot key, the + * dispatch holder and the version history do not move. A package-less flow, + * and an engine with no resolver attached, are CONTROLs. + */ +describe('[#33905] the bare entries of a flow whose only holder\'s package is disabled', () => { + const unheld = async (name: string) => ({ + run: await engine.execute(name), + read: await engine.getFlow(name), + toggle: await engine.toggleFlow(name, false).then(() => 'switched', (err: Error) => err.message), + }); + + it('execute, getFlow and toggleFlow answer as for a name the engine does not hold (FROM: served); re-enabled, they serve it again', async () => { + ship(P1, leaf('solo', 'p1')); + registry.disablePackage(P1); + const answers = await unheld('solo'); + const nothing = await unheld('nope'); + expect(answers).toEqual({ ...nothing, run: { ...nothing.run, error: "Flow 'solo' not found" }, toggle: "Flow 'solo' not found" }); + expect(answers.read).toBeNull(); + expect(answers.run.success).toBe(false); + expect(ran).toEqual([]); + // Amendment 7: the durable reads are judged over every holder, unmoved. + expect(engine.flowSlotKey(P1, 'solo')).toBe('solo'); + expect(engine.flowDispatchHolder('solo')).toEqual({ packageId: P1, claimBare: true }); + expect(engine.getFlowVersionHistory('solo')).toHaveLength(1); + + registry.enablePackage(P1); + expect((await engine.execute('solo')).success).toBe(true); + expect(ran).toEqual(['p1']); + expect(await engine.getFlow('solo')).toMatchObject({ name: 'solo' }); + await expect(engine.toggleFlow('solo', false)).resolves.toBeUndefined(); + }); + + it('a subflow call by the bare name reaches no flow while the package is disabled (FROM: ran)', async () => { + ship(P1, leaf('solo', 'p1')); + engine.registerFlow('go', caller('go', 'solo')); + registry.disablePackage(P1); + expect((await engine.execute('go')).success).toBe(false); + expect(ran).toEqual([]); + registry.enablePackage(P1); + expect((await engine.execute('go')).success).toBe(true); + expect(ran).toEqual(['p1']); + }); + + it('CONTROL — a package-less flow (the environment\'s own, registered straight into the engine) is no package\'s: served while a package is disabled', async () => { + ship(P1, leaf('solo', 'p1')); + engine.registerFlow('env_flow', leaf('env_flow', 'env')); + registry.disablePackage(P1); + expect((await engine.execute('env_flow')).success).toBe(true); + expect(await engine.getFlow('env_flow')).toMatchObject({ name: 'env_flow' }); + expect(ran).toEqual(['env']); + }); + + it('CONTROL — with no resolver attached nothing is disabled: the flow is served as before', async () => { + ship(P1, leaf('solo', 'p1')); + engine.setFlowNameResolver(undefined); + registry.disablePackage(P1); + expect((await engine.execute('solo')).success).toBe(true); + expect(await engine.getFlow('solo')).toMatchObject({ name: 'solo' }); + expect(ran).toEqual(['p1']); }); }); From 9d712d1d6d1bbbb82f157deb2c950d052d7ca56d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:22:14 +0000 Subject: [PATCH 07/15] fix(service-automation): the served holder of a flow name a disabled package also ships keeps its slot key and its trigger A disable is reversible and moves no key. While the registry holds a flow name under two packages and the others are disabled, the served package's lone slot is filed, and stays, under PACKAGE/NAME: the boot pull files it so beside a disabled holder, and the re-sync's withdrawal of the disabled holder's slot no longer re-keys it to the bare name or stops its binding. The M1 decline and its refused-body warning are kept for a body another served package really had refused. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../33893-served-holder-keeps-slot-key.md | 15 ++ .../services/service-automation/src/engine.ts | 28 +++- .../src/flow-slots-per-package.test.ts | 141 ++++++++++++++++++ .../service-automation/src/flow-slots.ts | 38 ++++- 4 files changed, 209 insertions(+), 13 deletions(-) create mode 100644 .changeset/33893-served-holder-keeps-slot-key.md diff --git a/.changeset/33893-served-holder-keeps-slot-key.md b/.changeset/33893-served-holder-keeps-slot-key.md new file mode 100644 index 00000000000..d8a6f0782fa --- /dev/null +++ b/.changeset/33893-served-holder-keeps-slot-key.md @@ -0,0 +1,15 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation): the served holder of a flow name a disabled package also ships keeps its slot key and its trigger + +Clause-②: no +Metadata-protocol: none + +When two packages ship a flow of the same name and one of them is disabled, the engine holds the served package's flow in its own slot, filed under `PACKAGE/NAME`. Two paths lost that slot's trigger: + +- At boot, with one holder disabled, only the served holder's flow is pulled. Its slot was filed under the bare name and declined as if the other package's body had been refused, so its trigger never ran, behind a warning that named a refused body. +- At runtime, the re-sync that follows a disable withdraws the disabled holder's slot. The served slot was moved to the bare name and its trigger binding was stopped, and not armed again. + +Now a disable moves no key: in both cases the served holder's slot stays under `PACKAGE/NAME`, armed, and runs on its trigger; the bare name reaches it as the name's one served holder. Enabling the other package again arms its slot beside it, with no re-arm of the served one. The warning about a refused body is said only when another served package's body really was refused. When the other package's flow leaves the registry (an uninstall) before its slot is withdrawn, the name goes back to its bare key, as before. diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 683aa7e517d..968f0889c4d 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2938,8 +2938,14 @@ export class AutomationEngine implements IAutomationService { */ // [#32183, R4-G] `heldByMany` reads every holder, a disabled package's // included: a disable keeps that package's slot armed, so it never folds - // a shared name back to one bare entry (`main`'s answer). - private readonly flowSlots = new FlowSlotTable((name) => this.durableFlowHolder(name)?.status === 'refused'); + // a shared name back to one bare entry (`main`'s answer). [#33893; + // amendment 7] `coHeldByDisabled`: so is the key of a holder whose + // co-holders are disabled, which the boot pull files alone and a disabled + // co-holder's withdrawal leaves alone; it keeps its qualified key. + private readonly flowSlots = new FlowSlotTable( + (name) => this.durableFlowHolder(name)?.status === 'refused', + (name) => this.durableFlowHolder(name)?.status === 'refused' && this.flowHolder(name)?.status !== 'refused', + ); /** [#31696] Slot keys whose trigger decline ({@link activateFlowTrigger}) has been said. */ private readonly sharedSlotTriggerWarned = new Set(); /** @@ -4199,6 +4205,9 @@ export class AutomationEngine implements IAutomationService { // holds under two packages (the other's body refused, M1) still holds // the bare key, which would read as the name's one holder: it is not // armed, behind this warning, and runs when called by its package. + // [#33893] Both served ({@link loneSharedFlowKey}): beside a disabled + // co-holder the slot is the name's one served holder, filed under its + // qualified key, and is armed; the warning names no refused body. if (this.loneSharedFlowKey(this.flowSlotName(flowName)) === flowName) { if (!this.sharedSlotTriggerWarned.has(flowName)) { this.sharedSlotTriggerWarned.add(flowName); @@ -5381,10 +5390,16 @@ export class AutomationEngine implements IAutomationService { return keys.length > 0 ? keys : [name]; } - /** [M1] The key of `name`'s one slot while the registry holds `name` under two packages, else `undefined`. */ + /** + * [M1] The key of `name`'s one slot while the registry holds `name` under + * two packages SERVED, so another served package's body of it is not held + * here (refused), else `undefined`. [#33893] A co-holder that is only + * disabled is no M1: the slot is the name's one served holder, keeps its + * qualified key (amendment 7) and is armed, and no body was refused. + */ private loneSharedFlowKey(name: string): string | undefined { const keys = this.flowSlots.keysOf(name); - return keys.length === 1 && this.flowSlots.isShared(name) ? keys[0] : undefined; + return keys.length === 1 && this.flowSlots.isShared(name) && this.flowHolder(name)?.status === 'refused' ? keys[0] : undefined; } /** [#31696] Is `key` the key of a slot whose name another slot holds too? */ @@ -5642,7 +5657,10 @@ export class AutomationEngine implements IAutomationService { }; withdrawFlow.call(host, name); // [#31696] The slot goes with its flow; a name left with one slot - // files it under the bare name again. + // files it under the bare name again. [#33893] Not while the registry + // still holds the name under a disabled package (the re-sync of a + // disable withdraws its slot): the served holder keeps its key and + // its binding (amendment 7). this.moveFlowRecords(this.flowSlots.remove(name)); } diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 840a5e29ba1..f5d3c36a296 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1279,3 +1279,144 @@ describe('[#33905] the bare entries of a flow whose only holder\'s package is di expect(ran).toEqual(['p1']); }); }); + +/** + * [ADR-0150 D3/D4, #33893; seat ruling 6884403301, amendment 7] A disable is + * reversible and moves no key. The served holder of a name a disabled + * package co-holds keeps its slot under `PACKAGE/NAME`, armed, and its + * trigger dispatches: when the boot pull registers it alone (the disabled + * holder's flows not pulled), and when the disable's re-sync withdraws the + * disabled holder's slot. The M1 decline and its warning stay for a body + * that really was refused (the `[M1]` pins above). A holder that leaves the + * registry (an uninstall) folds the name back to its bare key, as before + * (CONTROL). + */ +describe('[#33893] the served holder of a name a disabled package co-holds keeps its qualified key, armed', () => { + const tagOf = (packageId: string) => packageId.split('.').pop()!; + let armed: Map Promise>; + let started: string[]; + let stopped: string[]; + + beforeEach(() => { + armed = new Map(); + started = []; + stopped = []; + engine.registerTrigger({ + type: 'record_change', + start: (b: { flowName: string }, callback: (c: unknown) => Promise) => { + started.push(b.flowName); + armed.set(b.flowName, callback); + }, + stop: (key: string) => { + stopped.push(key); + armed.delete(key); + }, + } as unknown as FlowTrigger); + }); + + async function fireAll(): Promise { + ran = []; + for (const [key, callback] of armed) await callback({ params: { flowName: key } }); + return [...ran].sort(); + } + + /** The registry holds `body` under `packageId` (its loader set too); the engine is not handed it. */ + function heldOnly(packageId: string, body: { name: string }): void { + registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId); + loaderSets[body.name] = [...new Set([...(loaderSets[body.name] ?? []), packageId])]; + } + + /** The pull (or the re-sync) hands the engine package `packageId`'s flow, as precedence arms a name two packages hold. */ + function pull(packageId: string, body: { name: string }): void { + engine.registerFlow(body.name, body, { source: 'package', packageId, holder: packageId }); + } + + const refusedBodyWarned = () => engineLogger.warn.mock.calls.filter(([message]: [string]) => /whose body was refused/.test(message)); + + it('FlowSlotTable: beside a disabled co-holder the first slot is filed qualified, and a co-holder\'s removal moves no key', () => { + let coHeldByDisabled = true; + const slots = new FlowSlotTable(() => true, () => coHeldByDisabled); + expect(slots.add({ packageId: P1, name: 'f' })).toEqual({ key: `${P1}/f`, moved: [] }); + expect(slots.isShared('f')).toBe(true); + expect(slots.add({ packageId: P2, name: 'f' })).toEqual({ key: `${P2}/f`, moved: [] }); + expect(slots.remove(`${P2}/f`)).toEqual([]); + expect(slots.keyOf('f', P1)).toBe(`${P1}/f`); + // CONTROL: with no disabled co-holder the removal folds the name back, as before. + slots.add({ packageId: P2, name: 'f' }); + coHeldByDisabled = false; + expect(slots.remove(`${P2}/f`)).toEqual([{ from: `${P1}/f`, to: 'f' }]); + }); + + describe.each([[P1, P2], [P2, P1]].map((order) => [order.map(tagOf).join(' then '), order] as const))('registry holds %s', (_o, order) => { + it.each([[P1, P2], [P2, P1]])('boot disable, %s disabled: the served holder is filed under PACKAGE/NAME, armed and dispatched, with no warning (FROM: bare key, declined behind the refused-body warning)', async (off, on) => { + for (const holder of order) heldOnly(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + pull(on, triggered('t', tagOf(on))); + + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + expect(started).toEqual([`${on}/t`]); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(refusedBodyWarned()).toEqual([]); + expect(engine.flowDispatchHolder(`${on}/t`)).toEqual({ packageId: on, claimBare: false, name: 't' }); + expect(engine.getFlowRegistration('t')).toEqual({ state: 'registered' }); + // The bare name reaches its one served holder. + ran = []; + expect((await engine.execute('t')).success).toBe(true); + expect(ran).toEqual([tagOf(on)]); + + // Enabled, the re-sync registers the other holder: no key moves, nothing is re-armed. + registry.enablePackage(off); + pull(off, triggered('t', tagOf(off))); + expect(started).toEqual([`${on}/t`, `${off}/t`]); + expect(stopped).toEqual([]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + }); + + it.each([[P1, P2], [P2, P1]])('runtime disable of %s, then the re-sync withdraws its slot: the served holder keeps its key and binding and dispatches (FROM: re-keyed to the bare name, its binding stopped)', async (off, on) => { + for (const holder of order) ship(holder, triggered('t', tagOf(holder))); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + started = []; + stopped = []; + + registry.disablePackage(off); + engine.withdrawFlowSlot(off, 't'); + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + expect(engine.flowSlotKey(off, 't')).toBeUndefined(); + expect(stopped).toEqual([`${off}/t`]); + expect([...armed.keys()]).toEqual([`${on}/t`]); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(refusedBodyWarned()).toEqual([]); + expect(engine.flowDispatchHolder(`${on}/t`)).toEqual({ packageId: on, claimBare: false, name: 't' }); + + registry.enablePackage(off); + pull(off, triggered('t', tagOf(off))); + expect(started).toEqual([`${off}/t`]); + expect(stopped).toEqual([`${off}/t`]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + }); + }); + + it('the disabled holder then uninstalled: the served holder keeps its key, and the bare name and its trigger still reach it', async () => { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + registry.disablePackage(P2); + engine.withdrawFlowSlot(P2, 't'); + registry.unregisterItemsByPackage(P2); + expect(engine.flowSlotKey(P1, 't')).toBe(`${P1}/t`); + expect(await fireAll()).toEqual(['alpha']); + ran = []; + expect((await engine.execute('t')).success).toBe(true); + expect(await engine.getFlow('t')).toMatchObject({ name: 't' }); + expect(ran).toEqual(['alpha']); + }); + + it('CONTROL — the other holder uninstalled before its slot is withdrawn: the name folds back to its bare key, as before', async () => { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + registry.unregisterItemsByPackage(P2); + engine.withdrawFlowSlot(P2, 't'); + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect([...armed.keys()]).toEqual(['t']); + expect(await fireAll()).toEqual(['alpha']); + }); +}); diff --git a/packages/services/service-automation/src/flow-slots.ts b/packages/services/service-automation/src/flow-slots.ts index 07af5e5b7c3..f45ffa3f2de 100644 --- a/packages/services/service-automation/src/flow-slots.ts +++ b/packages/services/service-automation/src/flow-slots.ts @@ -15,6 +15,14 @@ * when a name gains or loses its second slot; {@link FlowSlotTable.add} and * {@link FlowSlotTable.remove} answer which keys moved. * + * [#33893; seat ruling 6884403301, amendment 7] A disable is reversible and + * moves no key. While the registry holds a name under two or more packages + * and the others are disabled (`coHeldByDisabled`), a package's lone slot of + * the name is filed, and stays, under its qualified key: the first holder + * the boot pull registers beside a disabled one, and the holder a disabled + * one's withdrawal leaves behind. Such a slot reads as shared + * ({@link FlowSlotTable.isShared}) for as long as it holds that key. + * * Invariant (D4): a package-less slot never sits beside a package slot. A * package arriving for a name a package-less slot holds takes it over * ({@link FlowSlotTable.adopt}), and a package-less registration of a name one @@ -65,8 +73,14 @@ export interface FlowKeyMove { /** The slots one engine holds, and the key each is filed under. */ export class FlowSlotTable { - /** [M1] `heldByMany(name)`: the registry holds `name` under two or more packages (the resolver refuses it with no package). */ - constructor(private readonly heldByMany?: (name: string) => boolean) {} + /** + * @param heldByMany [M1] the registry holds `name` under two or more packages (the resolver refuses it with no package). + * @param coHeldByDisabled [#33893] it does, and at most one of them is served: a lone package slot keeps its qualified key. + */ + constructor( + private readonly heldByMany?: (name: string) => boolean, + private readonly coHeldByDisabled?: (name: string) => boolean, + ) {} private readonly byKey = new Map(); /** name → (package id, `''` for none) → key */ @@ -92,10 +106,15 @@ export class FlowSlotTable { return this.byName.get(name)?.get(packageId ?? ''); } - /** [M1] Is `name` shared: two or more slots hold it, or one does while the registry holds it twice. Every reader asks this. */ + /** + * [M1] Is `name` shared: two or more slots hold it, or one does while the registry holds it twice, or [#33893] + * under its qualified key. Every reader asks this. + */ isShared(name: string): boolean { - const size = this.byName.get(name)?.size ?? 0; - return size > 1 || (size === 1 && this.heldByMany?.(name) === true); + const packages = this.byName.get(name); + const size = packages?.size ?? 0; + if (size !== 1) return size > 1; + return this.heldByMany?.(name) === true || [...packages!.values()][0] !== name; } /** Every key, in arrival order. */ @@ -103,7 +122,7 @@ export class FlowSlotTable { return [...this.byKey.keys()]; } - /** File the slot `(packageId, name)`: its key, and the name's lone slot's move to its qualified key, if any. */ + /** File the slot `(packageId, name)`: its key (qualified for the first one too when `coHeldByDisabled`), and the name's lone slot's move to its qualified key, if any. */ add(slot: FlowSlot): { key: string; moved: FlowKeyMove[] } { const packages = this.byName.get(slot.name) ?? new Map(); const moved: FlowKeyMove[] = []; @@ -116,14 +135,15 @@ export class FlowSlotTable { moved.push({ from: onlyKey, to }); } } - const key = packages.size === 0 || slot.packageId === null ? slot.name : qualifiedFlowKey(slot.packageId, slot.name); + const lone = packages.size === 0 && this.coHeldByDisabled?.(slot.name) !== true; + const key = lone || slot.packageId === null ? slot.name : qualifiedFlowKey(slot.packageId, slot.name); packages.set(slot.packageId ?? '', key); this.byName.set(slot.name, packages); this.byKey.set(key, slot); return { key, moved }; } - /** Drop the slot `key` files: a name left with one slot files it under the bare name again (the move answered). */ + /** Drop the slot `key` files: a name left with one slot files it under the bare name again (the move answered), [#33893] unless `coHeldByDisabled`. */ remove(key: string): FlowKeyMove[] { const slot = this.byKey.get(key); if (!slot) return []; @@ -137,6 +157,8 @@ export class FlowSlotTable { if (packages.size !== 1) return []; const [[onlyPackage, onlyKey]] = [...packages]; if (onlyKey === slot.name) return []; + // [#33893] A disabled holder's slot leaving moves no key of the others. + if (this.coHeldByDisabled?.(slot.name) === true) return []; this.rekey(onlyKey, slot.name); packages.set(onlyPackage, slot.name); return [{ from: onlyKey, to: slot.name }]; From 7c1930560e14d54b16c3345831bc8f5d214ce587 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:08:18 +0000 Subject: [PATCH 08/15] fix(service-automation): the served holder folds back to the bare key once the disabled co-holder is uninstalled A lone slot kept under PACKAGE/NAME beside a disabled co-holder now settles back to the bare name at its next placement once the registry no longer holds the name twice (the uninstall's re-sync re-registers it), through the same record move a withdrawal uses. isShared reads the registry and the slot count again, as on main: a name one package holds is never read as shared, so removal, version history, rollback, withdraw, the bare inbound hook and the credential source serve it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../33893-served-holder-keeps-slot-key.md | 2 +- .../services/service-automation/src/engine.ts | 12 ++++- .../src/flow-slots-per-package.test.ts | 47 ++++++++++++++++--- .../service-automation/src/flow-slots.ts | 28 +++++++---- 4 files changed, 71 insertions(+), 18 deletions(-) diff --git a/.changeset/33893-served-holder-keeps-slot-key.md b/.changeset/33893-served-holder-keeps-slot-key.md index d8a6f0782fa..faa51fbbdca 100644 --- a/.changeset/33893-served-holder-keeps-slot-key.md +++ b/.changeset/33893-served-holder-keeps-slot-key.md @@ -12,4 +12,4 @@ When two packages ship a flow of the same name and one of them is disabled, the - At boot, with one holder disabled, only the served holder's flow is pulled. Its slot was filed under the bare name and declined as if the other package's body had been refused, so its trigger never ran, behind a warning that named a refused body. - At runtime, the re-sync that follows a disable withdraws the disabled holder's slot. The served slot was moved to the bare name and its trigger binding was stopped, and not armed again. -Now a disable moves no key: in both cases the served holder's slot stays under `PACKAGE/NAME`, armed, and runs on its trigger; the bare name reaches it as the name's one served holder. Enabling the other package again arms its slot beside it, with no re-arm of the served one. The warning about a refused body is said only when another served package's body really was refused. When the other package's flow leaves the registry (an uninstall) before its slot is withdrawn, the name goes back to its bare key, as before. +Now a disable moves no key: in both cases the served holder's slot stays under `PACKAGE/NAME`, armed, and runs on its trigger; the bare name reaches it as the name's one served holder. Enabling the other package again arms its slot beside it, with no re-arm of the served one. The warning about a refused body is said only when another served package's body really was refused. When the other package is uninstalled, the name goes back to its bare key, as before: before its slot is withdrawn, at the withdrawal; after it, when the uninstall's re-sync registers the served holder's flow again. Every bare entry (`execute`, `getFlow`, removal, version history, rollback, the bare inbound hook, credentials) then serves the name as one package's. diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 968f0889c4d..4d555f6be1c 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2941,7 +2941,8 @@ export class AutomationEngine implements IAutomationService { // a shared name back to one bare entry (`main`'s answer). [#33893; // amendment 7] `coHeldByDisabled`: so is the key of a holder whose // co-holders are disabled, which the boot pull files alone and a disabled - // co-holder's withdrawal leaves alone; it keeps its qualified key. + // co-holder's withdrawal leaves alone; it keeps its qualified key until the + // registry no longer holds the name twice ({@link placeFlowSlot} folds it). private readonly flowSlots = new FlowSlotTable( (name) => this.durableFlowHolder(name)?.status === 'refused', (name) => this.durableFlowHolder(name)?.status === 'refused' && this.flowHolder(name)?.status !== 'refused', @@ -5075,7 +5076,14 @@ export class AutomationEngine implements IAutomationService { return keys[0] ?? this.flowSlots.add({ packageId: null, name }).key; } const own = this.flowSlots.keyOf(name, packageId); - if (own !== undefined) return own; + if (own !== undefined) { + // [#33893] A lone slot kept under its qualified key beside a + // disabled co-holder folds back once that holder is gone (the + // uninstall's re-sync re-registers this one). + const folded = this.flowSlots.settle(name); + this.moveFlowRecords(folded); + return folded[0]?.to ?? own; + } const packageless = this.flowSlots.keyOf(name, null); if (packageless !== undefined) { this.flowSlots.adopt(packageless, packageId); diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index f5d3c36a296..05efaf6f86e 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1345,6 +1345,17 @@ describe('[#33893] the served holder of a name a disabled package co-holds keeps slots.add({ packageId: P2, name: 'f' }); coHeldByDisabled = false; expect(slots.remove(`${P2}/f`)).toEqual([{ from: `${P1}/f`, to: 'f' }]); + + // The disabled co-holder uninstalled: the lone qualified slot is no longer shared, and settles back to the bare name. + let many = true; + const kept = new FlowSlotTable(() => many, () => many); + kept.add({ packageId: P1, name: 'g' }); + expect(kept.settle('g')).toEqual([]); + many = false; + expect(kept.isShared('g')).toBe(false); + expect(kept.settle('g')).toEqual([{ from: `${P1}/g`, to: 'g' }]); + expect(kept.keyOf('g', P1)).toBe('g'); + expect(kept.settle('g')).toEqual([]); }); describe.each([[P1, P2], [P2, P1]].map((order) => [order.map(tagOf).join(' then '), order] as const))('registry holds %s', (_o, order) => { @@ -1396,18 +1407,40 @@ describe('[#33893] the served holder of a name a disabled package co-holds keeps }); }); - it('the disabled holder then uninstalled: the served holder keeps its key, and the bare name and its trigger still reach it', async () => { - ship(P1, triggered('t', 'alpha')); - ship(P2, triggered('t', 'beta')); - registry.disablePackage(P2); - engine.withdrawFlowSlot(P2, 't'); - registry.unregisterItemsByPackage(P2); + it.each([ + ['runtime disable, then the re-sync withdraws its slot', 'runtime'], + ['boot disable (the pull hands the engine the served holder only)', 'boot'], + ] as const)('%s, then the disabled holder is uninstalled: its re-sync folds the served holder back to the bare name, and every bare entry serves it (FROM: stuck under PACKAGE/NAME, the bare entries refused a name one package holds)', async (_label, path) => { + if (path === 'runtime') { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + registry.disablePackage(P2); + engine.withdrawFlowSlot(P2, 't'); + } else { + heldOnly(P1, triggered('t', 'alpha')); + heldOnly(P2, triggered('t', 'beta')); + registry.disablePackage(P2); + pull(P1, triggered('t', 'alpha')); + } expect(engine.flowSlotKey(P1, 't')).toBe(`${P1}/t`); + + // The uninstall: the registry and the loader set drop P2, and the + // uninstall's re-sync re-registers the name's one holder. + registry.unregisterItemsByPackage(P2); + loaderSets.t = [P1]; + engine.registerFlow('t', triggered('t', 'alpha'), { source: 'package', packageId: P1 }); + + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect([...armed.keys()]).toEqual(['t']); expect(await fireAll()).toEqual(['alpha']); + expect(engine.inboundHookSlot('t')).toBeUndefined(); + expect(engine.getFlowVersionHistory('t')).toHaveLength(2); ran = []; expect((await engine.execute('t')).success).toBe(true); - expect(await engine.getFlow('t')).toMatchObject({ name: 't' }); expect(ran).toEqual(['alpha']); + expect(() => engine.unregisterFlow('t')).not.toThrow(); + expect(await engine.getFlow('t')).toBeNull(); + expect([...armed.keys()]).toEqual([]); }); it('CONTROL — the other holder uninstalled before its slot is withdrawn: the name folds back to its bare key, as before', async () => { diff --git a/packages/services/service-automation/src/flow-slots.ts b/packages/services/service-automation/src/flow-slots.ts index f45ffa3f2de..309e8f8682e 100644 --- a/packages/services/service-automation/src/flow-slots.ts +++ b/packages/services/service-automation/src/flow-slots.ts @@ -20,8 +20,10 @@ * and the others are disabled (`coHeldByDisabled`), a package's lone slot of * the name is filed, and stays, under its qualified key: the first holder * the boot pull registers beside a disabled one, and the holder a disabled - * one's withdrawal leaves behind. Such a slot reads as shared - * ({@link FlowSlotTable.isShared}) for as long as it holds that key. + * one's withdrawal leaves behind. Once the registry no longer holds the name + * twice (the disabled holder uninstalled), the slot's next placement folds it + * back to the bare name ({@link FlowSlotTable.settle}): one keying rule, so a + * name one package holds is never read as shared. * * Invariant (D4): a package-less slot never sits beside a package slot. A * package arriving for a name a package-less slot holds takes it over @@ -106,15 +108,25 @@ export class FlowSlotTable { return this.byName.get(name)?.get(packageId ?? ''); } + /** [M1] Is `name` shared: two or more slots hold it, or one does while the registry holds it twice. Every reader asks this. */ + isShared(name: string): boolean { + const size = this.byName.get(name)?.size ?? 0; + return size > 1 || (size === 1 && this.heldByMany?.(name) === true); + } + /** - * [M1] Is `name` shared: two or more slots hold it, or one does while the registry holds it twice, or [#33893] - * under its qualified key. Every reader asks this. + * [#33893] The name's lone slot, filed under its qualified key beside a + * disabled co-holder, goes back to the bare name once the registry no + * longer holds the name twice: the move answered, or none. */ - isShared(name: string): boolean { + settle(name: string): FlowKeyMove[] { const packages = this.byName.get(name); - const size = packages?.size ?? 0; - if (size !== 1) return size > 1; - return this.heldByMany?.(name) === true || [...packages!.values()][0] !== name; + if (packages?.size !== 1 || this.heldByMany?.(name) === true) return []; + const [[onlyPackage, onlyKey]] = [...packages]; + if (onlyKey === name) return []; + this.rekey(onlyKey, name); + packages.set(onlyPackage, name); + return [{ from: onlyKey, to: name }]; } /** Every key, in arrival order. */ From b4d4a4a87fed1b4b7c7360f24fd1f61214eb63a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:10:34 +0000 Subject: [PATCH 09/15] docs(service-automation): name the write-door answers a disabled sole holder's flow moves The clone door's taken-name probe, the definition writes' rollback copy and carried-forward credentials, and the DELETE door's answer all ask getFlow, so they move with it; the changeset now says how. The runtime door pin gains the clone door's source row. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .changeset/33905-disabled-sole-holder-flow.md | 6 ++++++ .../src/domains/automation-addressed-route.test.ts | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/.changeset/33905-disabled-sole-holder-flow.md b/.changeset/33905-disabled-sole-holder-flow.md index 3f488c9f088..a5a1092a4a8 100644 --- a/.changeset/33905-disabled-sole-holder-flow.md +++ b/.changeset/33905-disabled-sole-holder-flow.md @@ -18,6 +18,12 @@ What moves, for such a flow, while its package is disabled: - `getFlow(name)` answered the flow. It now answers `null`, so the bare HTTP doors that ask it first (`GET /automation/NAME`, `POST /automation/NAME/trigger`, `POST /automation/trigger/NAME`, `POST /automation/NAME/toggle`, `POST /automation/NAME/clone`, `GET /automation/NAME/runs`) answer `404`, which is what the namespaced address `/automation/NAMESPACE/NAME…` already answered. - `toggleFlow(name, …)` switched the flow. It now rejects with `Flow 'NAME' not found`. +Three HTTP write doors ask `getFlow` whether the name is held, and move with it for such a flow. These answers were read from the runtime source; the engine's half of the clone answer was measured. Each holds only where the door's earlier checks, such as the packaged-base and authoring rules, let the request through. + +- `POST /automation/SOURCE/clone`, with the flow's name as the new name: the taken-name probe refused the copy with `409`. It now finds no flow and lets the copy through. The engine files the copy's body in the disabled package's slot of the name, and once the package is enabled again its trigger runs the copy's body until the next re-sync. This may widen what the door accepts. +- A definition write (`POST /automation`, `PUT /automation/NAME`) or a clone that the engine accepts and that is then refused (an unknown `notify` channel, a refused landing, a refused save) put back the definition the engine held. It now has nothing to put back, so it removes the name's registration. A `PUT` body that leaves out a stored credential no longer keeps the one the engine held. +- `DELETE /automation/NAME` answered a deletion. It still removes the engine's registration, but now answers `404` unless a stored row was removed. + Remedy: enable the package. Its flow runs on its trigger again with no re-arm, and the bare entries serve it again. An event that fires while the package is disabled is dropped, not replayed when the package is enabled again. diff --git a/packages/runtime/src/domains/automation-addressed-route.test.ts b/packages/runtime/src/domains/automation-addressed-route.test.ts index a0e79045ea2..747056ae0d8 100644 --- a/packages/runtime/src/domains/automation-addressed-route.test.ts +++ b/packages/runtime/src/domains/automation-addressed-route.test.ts @@ -698,6 +698,17 @@ describe('[#33905] a flow whose only holder\'s package is disabled: the bare doo expect(automation.listRunsPage).not.toHaveBeenCalled(); }); + it('the clone door with the flow as its source answers 404 as its namespaced address does; nothing is registered (FROM: the source was copied)', async () => { + const { call, automation } = dispatcherOver(registryHolding(true), false); + const registerFlow = vi.fn(); + (automation as Record).registerFlow = registerFlow; + const viaAddress = await call('/crm/solo/clone', 'POST', { name: 'solo_copy', label: 'Solo copy' }); + const viaBare = await call('/solo/clone', 'POST', { name: 'solo_copy', label: 'Solo copy' }); + expect([viaBare.status, codeOf(viaBare)]).toEqual([404, codeOf(viaAddress)]); + expect(viaAddress.status).toBe(404); + expect(registerFlow).not.toHaveBeenCalled(); + }); + it('CONTROL — the package enabled: the address is its bare path, and both serve the flow', async () => { const { call } = dispatcherOver(registryHolding(false), true); for (const [bare, addressed, method, body] of DOORS) { From ea75f64d0ab411ec065b7fda0673c2856de0a496 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:07:08 +0000 Subject: [PATCH 10/15] fix(service-automation): the served holder is re-armed beside a returning co-holder and reached before the uninstall's re-sync A lone slot filed under its qualified key beside a disabled co-holder is declined only once another package's body of the name is recorded as refused, so the enable's re-sync registering the served holder first arms it with no refused-body warning. A co-holder that returns while the incumbent is already qualified moves no key, so the incumbent's re-arm is done where the move's would have been. A refusal recorded later still declines it and says so. The fold back to the bare name after the co-holder leaves the registry now also happens the first time the engine fires the slot or reads its name (the bare key resolvers and the inbound hook), not only at its next placement, so a failed re-sync leaves no unreachable flow. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../services/service-automation/src/engine.ts | 45 +++++++++-- .../src/flow-slots-per-package.test.ts | 80 ++++++++++++++++++- .../service-automation/src/flow-slots.ts | 11 +-- 3 files changed, 125 insertions(+), 11 deletions(-) diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 4d555f6be1c..fa3b9b694dc 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -4209,7 +4209,11 @@ export class AutomationEngine implements IAutomationService { // [#33893] Both served ({@link loneSharedFlowKey}): beside a disabled // co-holder the slot is the name's one served holder, filed under its // qualified key, and is armed; the warning names no refused body. - if (this.loneSharedFlowKey(this.flowSlotName(flowName)) === flowName) { + // Filed under its qualified key, it is declined only once another + // package's body of the name was refused (recorded): a co-holder the + // re-sync has not registered yet is no refusal. + const slotName = this.flowSlotName(flowName); + if (this.loneSharedFlowKey(slotName) === flowName && (flowName === slotName || this.flowRefusals.has(slotName))) { if (!this.sharedSlotTriggerWarned.has(flowName)) { this.sharedSlotTriggerWarned.add(flowName); this.logger.warn( @@ -4444,12 +4448,16 @@ export class AutomationEngine implements IAutomationService { private triggerRun(armedKey: string): (ctx: AutomationContext) => Promise { const slot = this.flowSlots.slot(armedKey); return async (ctx) => { - const key = slot ? this.flowSlots.keyOf(slot.name, slot.packageId) : armedKey; + let key = slot ? this.flowSlots.keyOf(slot.name, slot.packageId) : armedKey; if (key === undefined && !isSlotKeySpelling(armedKey)) return this.execute(armedKey, ctx); if (key === undefined || (key !== armedKey && !this.boundFlowTriggers.has(armedKey))) { this.logger.debug(`Trigger fired flow '${armedKey}' after it moved or left and was released: not run.`); return undefined; } + // [#33893] A lone slot left under its qualified key (its disabled + // co-holder since uninstalled) folds back here, and this run goes + // to where it lands. + if (slot && this.settleFlowName(slot.name)) key = this.flowKeyNow(key); if (slot && slot.packageId !== null) { const said = qualifiedFlowKey(slot.packageId, slot.name); if (this.isDisabledHolderSlot(slot.name, slot.packageId)) { @@ -5080,9 +5088,7 @@ export class AutomationEngine implements IAutomationService { // [#33893] A lone slot kept under its qualified key beside a // disabled co-holder folds back once that holder is gone (the // uninstall's re-sync re-registers this one). - const folded = this.flowSlots.settle(name); - this.moveFlowRecords(folded); - return folded[0]?.to ?? own; + return this.settleFlowName(name) ? this.flowKeyNow(own) : own; } const packageless = this.flowSlots.keyOf(name, null); if (packageless !== undefined) { @@ -5092,8 +5098,17 @@ export class AutomationEngine implements IAutomationService { const incumbents = this.flowSlots.slotsOf(name); const incumbent = incumbents.length === 1 ? incumbents[0].packageId : null; if (incumbent !== null && this.flowHoldersSealed) this.bindPackagelessActivation(name, incumbent); + const incumbentKey = incumbents.length === 1 ? this.flowSlots.keyOf(name, incumbent) : undefined; const { key, moved } = this.flowSlots.add({ packageId, name }); this.moveFlowRecords(moved); + // [#33893] An incumbent already under its qualified key (filed so + // beside a disabled co-holder) moves no key as its co-holder returns, + // so the move's re-arm is done here: the M1 decline it may have taken + // while it was the name's one slot no longer applies. + if (incumbentKey !== undefined && incumbentKey !== name && moved.length === 0 && this.flows.has(incumbentKey)) { + this.sharedSlotTriggerWarned.delete(incumbentKey); + this.activateFlowTrigger(incumbentKey); + } if (incumbent !== null && !this.flowHoldersSealed) this.flowLedgerDisabled.refusePackagelessBind(name, incumbent); return key; } @@ -5291,6 +5306,7 @@ export class AutomationEngine implements IAutomationService { ): { key: string } | { refusal: PackageScopedRefusal } | { absent: true } { // [#31696] A slot key is no flow's name: it names no flow here. if (isSlotKeySpelling(name)) return { key: unfiledFlowKey(name) }; + this.settleFlowName(name); if (!this.flowSlots.isShared(name)) { const refusal = this.flowNameRefusal(name, callerPackageId); if (refusal) return { refusal }; @@ -5325,6 +5341,7 @@ export class AutomationEngine implements IAutomationService { */ private bareFlowKey(name: string): string | undefined { if (isSlotKeySpelling(name)) return undefined; + this.settleFlowName(name); if (!this.flowSlots.isShared(name)) return name; throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(name, null)); } @@ -5343,6 +5360,7 @@ export class AutomationEngine implements IAutomationService { */ private servedBareFlowKey(name: string): string | undefined { if (isSlotKeySpelling(name)) return undefined; + this.settleFlowName(name); if (!this.flowSlots.isShared(name)) return this.isDisabledSoleHolder(name) ? undefined : name; const resolved = this.resolveFlowKey(name, null); if ('refusal' in resolved) throw new PackageScopedNameRefusedError(resolved.refusal); @@ -5410,6 +5428,18 @@ export class AutomationEngine implements IAutomationService { return keys.length === 1 && this.flowSlots.isShared(name) && this.flowHolder(name)?.status === 'refused' ? keys[0] : undefined; } + /** + * [#33893] Fold `name`'s lone slot back to the bare name if it is still + * under its qualified key while the registry no longer holds the name + * twice ({@link FlowSlotTable.settle}), moving its records and trigger. + * True when it moved. + */ + private settleFlowName(name: string): boolean { + const moved = this.flowSlots.settle(name); + this.moveFlowRecords(moved); + return moved.length > 0; + } + /** [#31696] Is `key` the key of a slot whose name another slot holds too? */ private isSharedFlowKey(key: string): boolean { const slot = this.flowSlots.slot(key); @@ -5697,6 +5727,10 @@ export class AutomationEngine implements IAutomationService { }; recordFlowRefusal.call(host, name, error); if (lone !== undefined) this.deactivateFlowTrigger(lone); + // [#33893] A lone slot under its qualified key was armed while the + // co-holder was not yet registered; asked again, it takes the decline + // and says it. + if (lone !== undefined && lone !== name) this.activateFlowTrigger(lone); } /** @@ -6012,6 +6046,7 @@ export class AutomationEngine implements IAutomationService { | { readonly status: 'unadmitted' } | { readonly status: 'refused'; readonly candidates: PackageScopedRefusal['candidates'] } { if (isSlotKeySpelling(flowName) || flowName.startsWith('\u0000')) return { status: 'unadmitted' }; + this.settleFlowName(flowName); if (!this.flowSlots.isShared(flowName)) return undefined; if (address === undefined) return { status: 'refused', candidates: this.sharedFlowNameRefusal(flowName, null).candidates }; const environment = address.qualifier === ENVIRONMENT_ADDRESS_SEGMENT; diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 05efaf6f86e..d6691c41185 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1316,7 +1316,7 @@ describe('[#33893] the served holder of a name a disabled package co-holds keeps async function fireAll(): Promise { ran = []; - for (const [key, callback] of armed) await callback({ params: { flowName: key } }); + for (const [key, callback] of [...armed]) await callback({ params: { flowName: key } }); return [...ran].sort(); } @@ -1443,6 +1443,84 @@ describe('[#33893] the served holder of a name a disabled package co-holds keeps expect([...armed.keys()]).toEqual([]); }); + /** The disable both ways: the boot pull hands the engine the served holder only, or both are shipped and the re-sync withdraws the disabled one's slot. */ + function disableBeside(path: 'boot' | 'runtime', off: string, on: string): void { + if (path === 'boot') { + for (const holder of [P1, P2]) heldOnly(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + pull(on, triggered('t', tagOf(on))); + } else { + for (const holder of [P1, P2]) ship(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + engine.withdrawFlowSlot(off, 't'); + } + } + + describe.each(['boot', 'runtime'] as const)('%s disable, then the enable\'s re-sync registers every contender', (path) => { + it.each([ + [P1, P2, 'served holder first'], + [P2, P1, 'served holder first'], + [P1, P2, 'returning holder first'], + [P2, P1, 'returning holder first'], + ])('%s disabled, %s served, %s: both slots armed and dispatched, no refused-body warning (FROM: the served holder declined behind it and never re-armed)', async (off, on, order) => { + disableBeside(path, off, on); + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + + registry.enablePackage(off); + const contenders = order === 'served holder first' ? [on, off] : [off, on]; + for (const holder of contenders) pull(holder, triggered('t', tagOf(holder))); + + expect([...armed.keys()].sort()).toEqual([`${P1}/t`, `${P2}/t`]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + expect(refusedBodyWarned()).toEqual([]); + }); + }); + + it('CONTROL — the returning holder\'s body really is refused: the served one is declined behind the warning, once; registered after all, both are armed', async () => { + disableBeside('runtime', P2, P1); + registry.enablePackage(P2); + pull(P1, triggered('t', 'alpha')); + expect([...armed.keys()]).toEqual([`${P1}/t`]); + + engine.recordFlowRefusal('t', new Error('refused body')); + expect([...armed.keys()]).toEqual([]); + expect(refusedBodyWarned()).toHaveLength(1); + + pull(P2, triggered('t', 'beta')); + expect([...armed.keys()].sort()).toEqual([`${P1}/t`, `${P2}/t`]); + expect(await fireAll()).toEqual(['alpha', 'beta']); + expect(refusedBodyWarned()).toHaveLength(1); + }); + + describe('the stretch between the uninstall and the re-sync\'s registration (no re-registration at all: a failed re-sync read)', () => { + function uninstalled(): void { + disableBeside('runtime', P2, P1); + registry.unregisterItemsByPackage(P2); + loaderSets.t = [P1]; + expect(engine.flowSlotKey(P1, 't')).toBe(`${P1}/t`); + } + + it('first touched by its trigger: the event runs the flow, and the slot folds back to the bare name with its binding (FROM: execute was asked a slot key and ran nothing)', async () => { + uninstalled(); + expect(await fireAll()).toEqual(['alpha']); + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect([...armed.keys()]).toEqual(['t']); + expect(await fireAll()).toEqual(['alpha']); + }); + + it('first touched by a bare entry: each one serves the name (FROM: no flow under the bare name)', async () => { + uninstalled(); + expect(engine.inboundHookSlot('t')).toBeUndefined(); + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect(await engine.getFlow('t')).toMatchObject({ name: 't' }); + expect(engine.getFlowVersionHistory('t')).toHaveLength(1); + ran = []; + expect((await engine.execute('t')).success).toBe(true); + expect(ran).toEqual(['alpha']); + expect([...armed.keys()]).toEqual(['t']); + }); + }); + it('CONTROL — the other holder uninstalled before its slot is withdrawn: the name folds back to its bare key, as before', async () => { ship(P1, triggered('t', 'alpha')); ship(P2, triggered('t', 'beta')); diff --git a/packages/services/service-automation/src/flow-slots.ts b/packages/services/service-automation/src/flow-slots.ts index 309e8f8682e..25dc8534882 100644 --- a/packages/services/service-automation/src/flow-slots.ts +++ b/packages/services/service-automation/src/flow-slots.ts @@ -21,9 +21,10 @@ * the name is filed, and stays, under its qualified key: the first holder * the boot pull registers beside a disabled one, and the holder a disabled * one's withdrawal leaves behind. Once the registry no longer holds the name - * twice (the disabled holder uninstalled), the slot's next placement folds it - * back to the bare name ({@link FlowSlotTable.settle}): one keying rule, so a - * name one package holds is never read as shared. + * twice (the disabled holder uninstalled), it folds back to the bare name + * ({@link FlowSlotTable.settle}) the first time the engine places it, fires it + * or reads its name: one keying rule, so a name one package holds is never + * read as shared. * * Invariant (D4): a package-less slot never sits beside a package slot. A * package arriving for a name a package-less slot holds takes it over @@ -121,9 +122,9 @@ export class FlowSlotTable { */ settle(name: string): FlowKeyMove[] { const packages = this.byName.get(name); - if (packages?.size !== 1 || this.heldByMany?.(name) === true) return []; + if (packages?.size !== 1) return []; const [[onlyPackage, onlyKey]] = [...packages]; - if (onlyKey === name) return []; + if (onlyKey === name || this.heldByMany?.(name) === true) return []; this.rekey(onlyKey, name); packages.set(onlyPackage, name); return [{ from: onlyKey, to: name }]; From d6a464ce03f8f9a767155addc2ac5ce9bbd74aac Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:09:17 +0000 Subject: [PATCH 11/15] docs(service-automation): the enable and uninstall paths of a disabled co-holder, and the clone answer as ruled Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .changeset/33893-served-holder-keeps-slot-key.md | 2 +- .changeset/33905-disabled-sole-holder-flow.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/33893-served-holder-keeps-slot-key.md b/.changeset/33893-served-holder-keeps-slot-key.md index faa51fbbdca..9f0ee5aa668 100644 --- a/.changeset/33893-served-holder-keeps-slot-key.md +++ b/.changeset/33893-served-holder-keeps-slot-key.md @@ -12,4 +12,4 @@ When two packages ship a flow of the same name and one of them is disabled, the - At boot, with one holder disabled, only the served holder's flow is pulled. Its slot was filed under the bare name and declined as if the other package's body had been refused, so its trigger never ran, behind a warning that named a refused body. - At runtime, the re-sync that follows a disable withdraws the disabled holder's slot. The served slot was moved to the bare name and its trigger binding was stopped, and not armed again. -Now a disable moves no key: in both cases the served holder's slot stays under `PACKAGE/NAME`, armed, and runs on its trigger; the bare name reaches it as the name's one served holder. Enabling the other package again arms its slot beside it, with no re-arm of the served one. The warning about a refused body is said only when another served package's body really was refused. When the other package is uninstalled, the name goes back to its bare key, as before: before its slot is withdrawn, at the withdrawal; after it, when the uninstall's re-sync registers the served holder's flow again. Every bare entry (`execute`, `getFlow`, removal, version history, rollback, the bare inbound hook, credentials) then serves the name as one package's. +Now a disable moves no key: in both cases the served holder's slot stays under `PACKAGE/NAME`, armed, and runs on its trigger; the bare name reaches it as the name's one served holder. When the other package is enabled again, its re-sync registers both packages' flows, in either order, and both slots end armed on their triggers. The warning about a refused body is said only once another package's body of the name is recorded as refused. When the other package is uninstalled, the name goes back to its bare key, as before. Before its slot is withdrawn, that happens at the withdrawal. After the withdrawal, it happens the first time the engine registers the served holder's flow again, fires its trigger or is asked for the name. Every bare entry (`execute`, `getFlow`, removal, version history, rollback, the bare inbound hook, credentials) then serves the name as one package's, and a re-sync that fails leaves no flow unreachable. diff --git a/.changeset/33905-disabled-sole-holder-flow.md b/.changeset/33905-disabled-sole-holder-flow.md index a5a1092a4a8..6c1f5dde3ef 100644 --- a/.changeset/33905-disabled-sole-holder-flow.md +++ b/.changeset/33905-disabled-sole-holder-flow.md @@ -20,7 +20,7 @@ What moves, for such a flow, while its package is disabled: Three HTTP write doors ask `getFlow` whether the name is held, and move with it for such a flow. These answers were read from the runtime source; the engine's half of the clone answer was measured. Each holds only where the door's earlier checks, such as the packaged-base and authoring rules, let the request through. -- `POST /automation/SOURCE/clone`, with the flow's name as the new name: the taken-name probe refused the copy with `409`. It now finds no flow and lets the copy through. The engine files the copy's body in the disabled package's slot of the name, and once the package is enabled again its trigger runs the copy's body until the next re-sync. This may widen what the door accepts. +- `POST /automation/SOURCE/clone`, with the flow's name as the new name: the taken-name probe refused the copy with `409`. It now finds no flow and lets the copy through. The engine files the copy's body in the disabled package's slot of the name, and once the package is enabled again its trigger runs the copy's body until the next re-sync. That is the answer the door already gives once the disable's re-sync has withdrawn the flow, so the door accepts nothing the normal path refuses. - A definition write (`POST /automation`, `PUT /automation/NAME`) or a clone that the engine accepts and that is then refused (an unknown `notify` channel, a refused landing, a refused save) put back the definition the engine held. It now has nothing to put back, so it removes the name's registration. A `PUT` body that leaves out a stored credential no longer keeps the one the engine held. - `DELETE /automation/NAME` answered a deletion. It still removes the engine's registration, but now answers `404` unless a stored row was removed. From 21e9ee5a85770e233bb0a5f9ef64b0d8816f52d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:59:46 +0000 Subject: [PATCH 12/15] fix(service-automation)!: the inbound hook door refuses a disabled holder's slot before anything is enqueued AutomationEngine.inboundHookSlot answers `unadmitted` for a slot whose registry-held package is disabled (isDisabledHolderSlot): the qualified address of a disabled co-holder's slot, and every address of a disabled sole holder's flow. Both faces then answer the door's one 401 once the body is read, the bytes the address gets after the disable's re-sync, and nothing is enqueued whose run would be skipped. The cause is logged at info, never sent. Asked at post time, so a re-enable serves the address again with no re-arm. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../services/service-automation/src/engine.ts | 44 ++++++++++++++++++- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index fa3b9b694dc..5ab649bae05 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -6036,6 +6036,19 @@ export class AutomationEngine implements IAutomationService { * - `refused`: the bare hook of a name two packages hold: every holder, * nothing picked. The door logs the holders and answers its one * refusal: D5's `409` does not apply to this anonymous door. + * + * [#33906; seat ruling 6884403301, amendments 2, 3 and 8] A slot whose + * package is disabled now ({@link isDisabledHolderSlot}) answers no + * address: the qualified address of a disabled co-holder's slot, and + * every address of a disabled sole holder's flow, the bare one included, + * are `unadmitted` — the door's one refusal, answered once the body is + * read in full, the same bytes the address gets once the disable's + * re-sync has withdrawn the slot. Nothing is enqueued, so no post is + * accepted whose run {@link triggerRun} would then skip. The slot is + * judged after the address has picked it, and no other holder is served + * in its place. The cause goes to the server log only, here, once per + * refused post. The question is asked at post time, so the address + * answers again the moment its package is enabled, with no re-arm. */ inboundHookSlot( flowName: string, @@ -6047,7 +6060,12 @@ export class AutomationEngine implements IAutomationService { | { readonly status: 'refused'; readonly candidates: PackageScopedRefusal['candidates'] } { if (isSlotKeySpelling(flowName) || flowName.startsWith('\u0000')) return { status: 'unadmitted' }; this.settleFlowName(flowName); - if (!this.flowSlots.isShared(flowName)) return undefined; + if (!this.flowSlots.isShared(flowName)) { + const packageId = this.flowSlotPackage(flowName); + return packageId !== undefined && this.isDisabledHolderSlot(flowName, packageId) + ? this.disabledHolderHookRefused(flowName, packageId, flowName) + : undefined; + } if (address === undefined) return { status: 'refused', candidates: this.sharedFlowNameRefusal(flowName, null).candidates }; const environment = address.qualifier === ENVIRONMENT_ADDRESS_SEGMENT; const keys = this.flowSlots.keysOf(flowName).filter((key) => { @@ -6056,7 +6074,29 @@ export class AutomationEngine implements IAutomationService { return slot.packageId !== null && address.namespaceOwners.includes(slot.packageId) && this.packagedFlowOwner(key) === slot.packageId; }); - return keys.length === 1 ? { status: 'served', key: keys[0] } : { status: 'unadmitted' }; + if (keys.length !== 1) return { status: 'unadmitted' }; + const packageId = this.flowSlotPackage(keys[0]); + if (packageId !== undefined && this.isDisabledHolderSlot(flowName, packageId)) { + return this.disabledHolderHookRefused(flowName, packageId, keys[0]); + } + return { status: 'served', key: keys[0] }; + } + + /** + * [#33906] {@link inboundHookSlot}'s answer for the slot `key` of package + * `packageId`'s flow `name` while that package is disabled: `unadmitted`, + * its cause logged here at `info` (the sender is told, with the door's one + * refusal, so nothing that claims to be persisted is lost). + */ + private disabledHolderHookRefused(name: string, packageId: string, key: string): { readonly status: 'unadmitted' } { + this.logger.info( + `Inbound hook post for flow '${name}' of package '${packageId}', which is disabled — refused with the ` + + 'one answer every unverified post gets: nothing was enqueued, and no other package\'s flow of the ' + + 'name was reached in its place. A sender that retries on a non-2xx keeps the event and can ' + + 'redeliver it once the package is enabled.', + { cause: 'disabled-holder', flow: name, package: packageId, slot: key }, + ); + return { status: 'unadmitted' }; } /** From 681d36b1472c44621e60d7038752a140c5dada46 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:12:59 +0000 Subject: [PATCH 13/15] test(dogfood): the inbound hook of a disabled holder's armed slot, both faces Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- ...inbound-hook-disabled-holder-33906.test.ts | 354 ++++++++++++++++++ 1 file changed, 354 insertions(+) create mode 100644 packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts diff --git a/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts b/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts new file mode 100644 index 00000000000..022bad043b9 --- /dev/null +++ b/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts @@ -0,0 +1,354 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D5, #33906; seat ruling 6884403301, amendments 2, 3 and 8] END + * TO END: the inbound hook of a flow slot whose package is disabled while the + * slot is still armed (the disable's re-sync has not withdrawn it: its + * announce or protocol read failed, or the disable came with no announce). + * + * The real `AutomationEngine`, built by the real `AutomationServicePlugin` + * `init()` (so its flow-name resolver is the plugin's own, over the real + * `SchemaRegistry`), the real `ApiTriggerPlugin` mounting the self-hosted + * door and registering the `trigger-api` member, the real `ApiTrigger` + * verifying and enqueueing, and the real runtime `HttpDispatcher` forwarding + * the hosted face to that member. A queue delivers each message to the + * trigger's consumer at once, so a run is observed. + * + * - The qualified address of a disabled co-holder's slot answers the door's + * one refusal on both faces, once the body is read: the bytes the address + * gets after the disable's re-sync. Nothing is enqueued and nothing runs; + * the cause is in the server log only. + * - A disabled sole holder's flow: the same, on its qualified and its bare + * address. + * - The enable serves the address again (202), with no re-arm. + * - CONTROL: the served co-holder answers 202 and runs; with nothing + * disabled every address answers as before. + * + * Every value is a probe sentinel, not a credential. + */ + +import { createHmac } from 'node:crypto'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { inboundHookJsonResponse, inboundHookRefusalResponse } from '@objectstack/core'; +import { SchemaRegistry, assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +import { HttpDispatcher } from '@objectstack/runtime'; +import { AutomationEngine, AutomationServicePlugin, FlowCredentialChannel } from '@objectstack/service-automation'; +import { ApiTriggerPlugin, HOOKS_ADDRESSED_PATH, HOOKS_PATH } from '@objectstack/trigger-api'; + +const P1 = 'com.acme.alpha'; +const P2 = 'com.acme.beta'; +const SHARED = 'zz_disabled_hook'; +const ALONE = 'zz_disabled_alone'; +const S1 = 'pin-disabled-hook-alpha-71c4'; +const S2 = 'pin-disabled-hook-beta-e09a'; +const S_ALONE = 'pin-disabled-hook-alone-3f58'; + +type Line = { level: string; message: string; fields?: any }; +const lines: Line[] = []; +const logger: any = {}; +for (const level of ['debug', 'info', 'warn', 'error']) { + logger[level] = (message: string, fields?: unknown) => { lines.push({ level, message, fields }); }; +} +logger.child = () => logger; + +const sign = (secret: string, body: string) => { + const t = Math.floor(Date.now() / 1000); + return `t=${t},v1=` + createHmac('sha256', secret).update(`${t}.${body}`, 'utf8').digest('hex'); +}; + +/** start (api hook `h1`, its secret in the channel) → mark(tag) → end. */ +function hooked(name: string, tag: string) { + return { + name, + label: name, + type: 'api', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { hookId: 'h1' } }, + { id: 'mark', type: 'mark', label: 'Mark', config: { tag } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'mark' }, + { id: 'e2', source: 'mark', target: 'end' }, + ], + }; +} + +/** One active hook-secret row per (flow, package), as the channel stores them. */ +function credentialStore(rows: Array<{ flow: string; packageId: string; value: string }>) { + const stored = rows.map((r, i) => ({ + id: `cred_${i}`, flow_name: r.flow, flow_package: r.packageId, node_id: 'start', credential_key: 'secret', state: 'active', value: r.value, + })); + return { + async find(_object: string, query?: { where?: Record; limit?: number }) { + const where = query?.where ?? {}; + const rows = stored.filter((row) => Object.entries(where).every(([k, v]) => (row as Record)[k] === v)); + const page = typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows; + return page.map(({ value: _value, ...row }) => row); + }, + async insert() { throw new Error('read-only probe store'); }, + async update(_object: string, data: unknown, options?: unknown) { + assertEngineUpdateDispatch(data as never, options as never); + throw new Error('read-only probe store'); + }, + async delete(_object: string, options?: unknown) { + assertEngineDeleteDispatch(options as never); + throw new Error('read-only probe store'); + }, + async resolveSecretField(_object: string, id: string) { + return stored.find((row) => row.id === id)?.value ?? null; + }, + }; +} + +/** An answer as its bytes: status, headers and body. */ +type Snapshot = { status: number; headers: Array<[string, string]>; body: string }; +async function snapshot(res: Response): Promise { + return { status: res.status, headers: [...res.headers.entries()], body: await res.text() }; +} + +let registry: SchemaRegistry; +let engine: AutomationEngine; +let routes: Map Promise) => Promise>; +let dispatcher: HttpDispatcher; +let enqueued: string[]; +let ran: string[]; +let subscribed: string[]; + +/** The hook's address: `ns` absent is the bare hook. */ +type Address = { ns?: string; flowName: string }; + +/** POST through the self-hosted mount, as Hono hands a handler its decoded parameters and renders `c.json`. */ +async function postSelfHosted(address: Address, secret: string): Promise { + const body = JSON.stringify({ probe: address }); + const headers: Record = { 'x-objectstack-signature': sign(secret, body) }; + const params: Record = { flowName: address.flowName, hookId: 'h1', ...(address.ns ? { ns: address.ns } : {}) }; + const c = { + req: { param: (n: string) => params[n], text: async () => body, header: (n: string) => headers[n.toLowerCase()] }, + json: (b: unknown, status: number) => inboundHookJsonResponse(b, status), + }; + const route = routes.get(address.ns ? HOOKS_ADDRESSED_PATH : HOOKS_PATH)!; + return snapshot((await route(c, async () => {})) as Response); +} + +/** POST through the runtime dispatcher (the hosted face: a kernel with no http.server). */ +async function postHosted(address: Address, secret: string): Promise { + const body = JSON.stringify({ probe: address }); + const path = address.ns + ? `/automation/hooks/${address.ns}/${address.flowName}/h1` + : `/automation/hooks/${address.flowName}/h1`; + const request = new Request(`http://tenant.example/api/v1${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-objectstack-signature': sign(secret, body) }, + body, + }); + const result = await dispatcher.dispatch('POST', path, {}, {}, { request } as never); + expect(result.response, path).toBeUndefined(); + return snapshot(result.result as Response); +} + +const FACES = [['self-hosted', postSelfHosted], ['hosted', postHosted]] as const; + +/** The engine's own line for a post it refused because its slot's package is disabled. */ +const disabledCauses = () => lines.filter((l) => l.fields?.cause === 'disabled-holder'); + +beforeEach(async () => { + routes = new Map(); + lines.length = 0; + enqueued = []; + ran = []; + subscribed = []; + registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const [id, namespace] of [[P1, 'alpha'], [P2, 'beta']]) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace } as never, 'code'); + } + const loaderSets: Record = {}; + + // The queue delivers each message to the trigger's consumer at once. + const consumers = new Map Promise | void>(); + const queue = { + async publish(name: string, data: unknown) { + enqueued.push(name); + await consumers.get(name)?.({ data }); + return `msg_${enqueued.length}`; + }, + async subscribe(name: string, handler: (message: { data: unknown }) => Promise | void) { + subscribed.push(name); + consumers.set(name, handler); + }, + async unsubscribe(name: string) { consumers.delete(name); }, + }; + const app = { post: (path: string, handler: any) => { routes.set(path, handler); } }; + const services: Record = { + queue, + 'http.server': { getRawApp: () => app }, + objectql: { registry }, + }; + const ctx = { + logger, + hook: (event: string, fn: () => Promise) => { if (event === 'kernel:ready') ready.push(fn); }, + getService: (name: string) => { + if (name in services) return services[name]; + throw new Error(`no ${name}`); + }, + registerService: (name: string, service: unknown) => { services[name] = service; }, + }; + const ready: Array<() => Promise> = []; + + // The engine the automation plugin builds, its flow-name resolver the plugin's own. + await new AutomationServicePlugin({ suspendedRunStore: 'memory' }).init(ctx as never); + engine = services.automation as AutomationEngine; + engine.registerNodeExecutor({ + type: 'mark', + async execute(node: { config?: { tag?: string } }) { + ran.push(String(node.config?.tag)); + return { success: true }; + }, + } as never); + engine.setPackagedFlowSource((name, packageId) => { + const holders = loaderSets[name] ?? []; + if (packageId !== undefined) return holders.includes(packageId) ? packageId : undefined; + return holders.length === 1 ? holders[0] : undefined; + }); + const channel = new FlowCredentialChannel(() => credentialStore([ + { flow: SHARED, packageId: P1, value: S1 }, + { flow: SHARED, packageId: P2, value: S2 }, + { flow: ALONE, packageId: P1, value: S_ALONE }, + ])); + await channel.loadIndex(); + engine.setFlowCredentialSource(channel); + + await new ApiTriggerPlugin().start(ctx as never); + for (const fn of ready) await fn(); + expect(services['trigger-api']).toBeDefined(); + + // The hosted face: the runtime dispatcher over a kernel with no http.server. + const { 'http.server': _socket, ...hosted } = services; + const kernel: any = { + getState: () => 'running', + getService: (n: string) => hosted[n] ?? null, + getServiceAsync: async (n: string) => hosted[n] ?? null, + context: { getService: (n: string) => hosted[n] ?? null }, + }; + dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + (dispatcher as any).domainDeps.logger = logger; + + const ship = (packageId: string, body: { name: string }) => { + registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId); + loaderSets[body.name] = [...new Set([...(loaderSets[body.name] ?? []), packageId])]; + engine.registerFlow(body.name, body, { source: 'package', packageId, holder: packageId }); + }; + ship(P1, hooked(SHARED, 'p1')); + ship(P2, hooked(SHARED, 'p2')); + ship(P1, hooked(ALONE, 'alone')); + // The consumer runs the flow after the publish resolves its subscription. + await new Promise((r) => setTimeout(r, 0)); +}); + +describe('#33906 the inbound hook of a disabled holder\'s armed slot, both faces', () => { + it('CONTROL: with nothing disabled, each qualified hook and the sole holder\'s bare hook answer 202 and run', async () => { + for (const [face, post] of FACES) { + ran = []; + expect((await post({ ns: 'alpha', flowName: SHARED }, S1)).status, face).toBe(202); + expect((await post({ ns: 'beta', flowName: SHARED }, S2)).status, face).toBe(202); + expect((await post({ ns: 'alpha', flowName: ALONE }, S_ALONE)).status, face).toBe(202); + expect((await post({ flowName: ALONE }, S_ALONE)).status, face).toBe(202); + expect(ran, face).toEqual(['p1', 'p2', 'alone', 'alone']); + } + expect(disabledCauses()).toEqual([]); + }); + + it('red line: the disabled co-holder\'s qualified address answers the one refusal, the bytes it gets after the re-sync; nothing is enqueued; the cause is logged only', async () => { + registry.disablePackage(P1); + const reference = await snapshot(inboundHookRefusalResponse()); + const armed: Record = {}; + for (const [face, post] of FACES) { + armed[face] = await post({ ns: 'alpha', flowName: SHARED }, S1); + expect(armed[face], face).toEqual(reference); + for (const leak of [P1, 'alpha', 'disabled']) expect(armed[face].body, face).not.toContain(leak); + } + expect(enqueued).toEqual([]); + expect(ran).toEqual([]); + const causes = disabledCauses(); + expect(causes).toHaveLength(2); + expect(causes[0].fields).toEqual({ cause: 'disabled-holder', flow: SHARED, package: P1, slot: `${P1}/${SHARED}` }); + + // The disable's re-sync withdraws the slot: the same address, the same bytes. + engine.withdrawFlowSlot(P1, SHARED); + for (const [face, post] of FACES) expect(await post({ ns: 'alpha', flowName: SHARED }, S1), face).toEqual(armed[face]); + expect(enqueued).toEqual([]); + expect(ran).toEqual([]); + }); + + it('CONTROL: the served co-holder beside the disabled one answers 202 on both faces and runs its own flow', async () => { + registry.disablePackage(P1); + for (const [face, post] of FACES) expect((await post({ ns: 'beta', flowName: SHARED }, S2)).status, face).toBe(202); + expect(enqueued).toEqual([`flow-api:${P2}/${SHARED}`, `flow-api:${P2}/${SHARED}`]); + expect(ran).toEqual(['p2', 'p2']); + expect(disabledCauses()).toEqual([]); + }); + + it('red line: both holders disabled, neither qualified address is served', async () => { + registry.disablePackage(P1); + registry.disablePackage(P2); + const reference = await snapshot(inboundHookRefusalResponse()); + for (const [face, post] of FACES) { + expect(await post({ ns: 'alpha', flowName: SHARED }, S1), face).toEqual(reference); + expect(await post({ ns: 'beta', flowName: SHARED }, S2), face).toEqual(reference); + } + expect(enqueued).toEqual([]); + expect(ran).toEqual([]); + expect(disabledCauses().map((l) => l.fields.package)).toEqual([P1, P2, P1, P2]); + }); + + it('red line: a disabled sole holder\'s flow answers the one refusal on its qualified and its bare address, the bytes they get after the re-sync; nothing is enqueued', async () => { + registry.disablePackage(P1); + const reference = await snapshot(inboundHookRefusalResponse()); + const addresses: Address[] = [{ ns: 'alpha', flowName: ALONE }, { flowName: ALONE }]; + const armed = new Map(); + for (const [face, post] of FACES) { + for (const address of addresses) { + const answer = await post(address, S_ALONE); + expect(answer, `${face} ${JSON.stringify(address)}`).toEqual(reference); + for (const leak of [P1, 'alpha', 'disabled']) expect(answer.body).not.toContain(leak); + armed.set(`${face} ${JSON.stringify(address)}`, answer); + } + } + expect(enqueued).toEqual([]); + expect(ran).toEqual([]); + expect(disabledCauses()).toHaveLength(4); + expect(disabledCauses()[0].fields).toEqual({ cause: 'disabled-holder', flow: ALONE, package: P1, slot: ALONE }); + + engine.withdrawFlowSlot(P1, ALONE); + for (const [face, post] of FACES) { + for (const address of addresses) { + const key = `${face} ${JSON.stringify(address)}`; + expect(await post(address, S_ALONE), key).toEqual(armed.get(key)); + } + } + expect(enqueued).toEqual([]); + expect(ran).toEqual([]); + }); + + it('the enable serves each address again, 202 and a run, with no re-arm', async () => { + const bindings = engine.getActiveTriggerBindings().map((b) => b.flowName).sort(); + const subscriptions = [...subscribed]; + registry.disablePackage(P1); + for (const [face, post] of FACES) { + expect((await post({ ns: 'alpha', flowName: SHARED }, S1)).status, face).toBe(401); + expect((await post({ flowName: ALONE }, S_ALONE)).status, face).toBe(401); + } + expect(ran).toEqual([]); + + registry.enablePackage(P1); + for (const [face, post] of FACES) { + expect((await post({ ns: 'alpha', flowName: SHARED }, S1)).status, face).toBe(202); + expect((await post({ ns: 'alpha', flowName: ALONE }, S_ALONE)).status, face).toBe(202); + expect((await post({ flowName: ALONE }, S_ALONE)).status, face).toBe(202); + } + expect(ran).toEqual(['p1', 'alone', 'alone', 'p1', 'alone', 'alone']); + expect(engine.getActiveTriggerBindings().map((b) => b.flowName).sort()).toEqual(bindings); + expect(subscribed).toEqual(subscriptions); + }); +}); From aa16cc6e9e9b2358bbbaa371308181af51176e5e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 00:22:43 +0000 Subject: [PATCH 14/15] chore: changeset for the inbound hook door's disabled-holder refusal Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../33906-inbound-hook-disabled-holder.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .changeset/33906-inbound-hook-disabled-holder.md diff --git a/.changeset/33906-inbound-hook-disabled-holder.md b/.changeset/33906-inbound-hook-disabled-holder.md new file mode 100644 index 00000000000..02f9f094cee --- /dev/null +++ b/.changeset/33906-inbound-hook-disabled-holder.md @@ -0,0 +1,23 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation)!: the inbound hook door refuses the address of a flow slot whose package is disabled, before anything is enqueued (ADR-0150 D5) + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a sender that posts to the inbound hook of a flow whose package is disabled while the automation engine still holds that flow's slot (the re-sync that follows a disable failed or did not run, or the disable came with no announce). The door answered `202 Accepted` and queued the post, and the queued run was then skipped, so the event was lost while the sender was told it was accepted. It now answers the door's one refusal, `401 INVALID_SIGNATURE`. + +What moves, while the package is disabled: + +- `POST /api/v1/automation/hooks/NAMESPACE/NAME/HOOK` for a name two packages each ship, where NAMESPACE names the disabled package: the self-hosted mount and the hosted face both answer the one refusal, once the body has been read in full. Nothing is enqueued, and the other package's flow of the name is not reached in its place. +- For a name only the disabled package ships, both its qualified address and the bare `POST /api/v1/automation/hooks/NAME/HOOK` answer the same refusal. + +The answer is byte for byte the one the same address gets once the disable's re-sync has withdrawn the slot, and the one every unverified post gets, so it says nothing about which packages are installed or disabled. The cause is written to the server log only, at `info`, once per refused post (`cause: 'disabled-holder'`, with the flow, the package and the slot). + +Senders that retry on a non-2xx keep the event and can redeliver after a re-enable. When the package is enabled again the address answers `202` and runs the flow again, with no re-arm. + +The served package's qualified hook beside a disabled one, a flow no package ships, and a flow switched off with its slot toggle answer as before. The bare hook of a name two packages ship answers the one refusal as before. From 3fecb9b67ec309eba9f6d83c6e0e599b16f97650 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:48:16 +0000 Subject: [PATCH 15/15] test(dogfood): the disabled-holder hook rig's credential store is read-only The hook door writes no credential, so the store double carries no write verb and owes no engine-double ledger row. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../inbound-hook-disabled-holder-33906.test.ts | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts b/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts index 022bad043b9..1f95f4ec586 100644 --- a/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts +++ b/packages/qa/dogfood/test/inbound-hook-disabled-holder-33906.test.ts @@ -30,7 +30,7 @@ import { createHmac } from 'node:crypto'; import { beforeEach, describe, expect, it } from 'vitest'; import { inboundHookJsonResponse, inboundHookRefusalResponse } from '@objectstack/core'; -import { SchemaRegistry, assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; +import { SchemaRegistry } from '@objectstack/objectql'; import { HttpDispatcher } from '@objectstack/runtime'; import { AutomationEngine, AutomationServicePlugin, FlowCredentialChannel } from '@objectstack/service-automation'; import { ApiTriggerPlugin, HOOKS_ADDRESSED_PATH, HOOKS_PATH } from '@objectstack/trigger-api'; @@ -74,7 +74,7 @@ function hooked(name: string, tag: string) { }; } -/** One active hook-secret row per (flow, package), as the channel stores them. */ +/** One active hook-secret row per (flow, package), as the channel stores them: read-only, the hook door writes nothing. */ function credentialStore(rows: Array<{ flow: string; packageId: string; value: string }>) { const stored = rows.map((r, i) => ({ id: `cred_${i}`, flow_name: r.flow, flow_package: r.packageId, node_id: 'start', credential_key: 'secret', state: 'active', value: r.value, @@ -86,15 +86,6 @@ function credentialStore(rows: Array<{ flow: string; packageId: string; value: s const page = typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows; return page.map(({ value: _value, ...row }) => row); }, - async insert() { throw new Error('read-only probe store'); }, - async update(_object: string, data: unknown, options?: unknown) { - assertEngineUpdateDispatch(data as never, options as never); - throw new Error('read-only probe store'); - }, - async delete(_object: string, options?: unknown) { - assertEngineDeleteDispatch(options as never); - throw new Error('read-only probe store'); - }, async resolveSecretField(_object: string, id: string) { return stored.find((row) => row.id === id)?.value ?? null; }, @@ -215,7 +206,7 @@ beforeEach(async () => { { flow: SHARED, packageId: P1, value: S1 }, { flow: SHARED, packageId: P2, value: S2 }, { flow: ALONE, packageId: P1, value: S_ALONE }, - ])); + ]) as never); await channel.loadIndex(); engine.setFlowCredentialSource(channel);