Skip to content

Commit 583bbf3

Browse files
fix(automation)!: switching on a packaged flow that its own status disarms is refused, and the toggle door answers the engine state (#34810)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBFyg5B2muWbKZjA9phXVWse)_ Refs #34655 (half B; half A follows in its own PR) Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — skills/objectstack-automation/SKILL.md teaches the toggle only as the off switch for an installed package's flow; nothing it says changes ## 维护者速读 - 改了什么:管理员对一个"作者已把 status 设为 obsolete/invalid"的打包 flow 点"开启"时,开关不再写入激活账本并谎报"已开启",而是直接拒绝(409)并说明原因;开关接口的成功应答改为回报引擎读回的真实状态(同名 flow 被两个包持有时,回报被切换那个包自己的状态)。 - 为什么改:此前开关写了 `active:true` 却让 flow 继续关着,接口仍回 `{enabled:true}`,管理员以为已开、实际从不运行(卡 34655 的 B 半,分诊要求先落)。 - 风险与回滚:这是一次收窄(BREAKING):对 status 为 obsolete/invalid 的打包 flow 点"开启"由 200 改为 409,并且不再覆盖已有的 active:false 行——此前"先开、再以 active 重发"会直接运行,现在重发后还要再开一次;关闭方向与正常 flow 不变。回滚即还原本 PR。 - 先看:`service-automation/src/flow-definitions.ts` 第 554 行起的新拒绝;`engine.ts` 第 7571 行 host 字面量与第 7528 行起的 `@throws`;`runtime/src/domains/automation.ts` 第 4453 行起的应答读回(只在该名字恰有一行时读回)。 - 两分钟验证:`pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2 src/toggle-door-packaged-only.test.ts`,预期全绿且含 "switching ON a packaged flow its own status disarms is refused" 一组;本轮的双持有者应答:`pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/automation-addressed-route.test.ts`,预期 "the toggle door answers the switched slot" 一组 5 条全绿。 - 需要你做的:作为收窄 PR(Tier H),在审核记录到位后批准落地;#34654 已合入,本分支已合并 main。 ## What changes - **Refusal (engine).** `toggleFlow` with `enabled: true` on a packaged flow whose definition's `status` disables it (`obsolete` / `invalid`, the verdict `registerFlow` records in `flowStatusDisabled`) is refused with `RESOURCE_CONFLICT` / 409. It sits right after the provenance refusal (`refuseCustomerAuthoredToggle`), before the ledger write and before any in-process change, so nothing half-flips. No new error code or public name. The verdict is read from `flowStatusDisabled`, now passed in `AutomationEngine.toggleFlowKey`'s host literal, so the status rule keeps one source. The `toggleFlow` docblock `@throws` names the new refusal. - The sentence (the flow's name and status filled in): `Flow 'NAME' cannot be enabled through this switch: its definition's status is 'STATUS', which keeps it off. This switch never changes a definition's status; publish the flow with status 'active' (for a package that is read-only here, that takes a package version that ships it active). Nothing was changed.` - **Toggle off is unchanged, on purpose.** Switching a status-disarmed flow OFF still writes `active: false`. Turning off a flow that is already off is not an error, and the row records the installation's choice: when a later definition ships the flow `active`, it stays off until an administrator turns it on. A pin holds this. - **A second moved path.** Switching on a status-disarmed flow used to write `active: true` over an administrator's earlier `active: false` row, so a later republish as `active` made it run at once. The row now stays, so after that republish the flow is still off until it is switched on again. One-line fix: publish the flow with status `active` first, then switch it on. - **The door's answer (runtime).** `POST /automation/:name/toggle` answers `200 { name, enabled }` with `enabled` read back from `getFlowRuntimeStates` (the reading `GET /automation/_status` serves). It no longer echoes the request. That reading names the switched flow only while the name has one row there: a flow name two packages hold has one row per holder under the same name (ADR-0150 D4), and the door reaches such a name through `flowSlotView` (its address `/automation/:ns/:name/toggle`, or the bare name while one holder's package is enabled), which switches one slot. Two or more rows therefore read back nothing. In that case, and for a service that does not implement the read or holds no row of the name, the door keeps the legacy echo. For the engine's own service (the only one with slots) that echo is true by construction, because the refusal above stops the one request whose echo was false, on every toggle entry. The handler comment, the route docblock and the changeset say so. ## Tests New pins: - `service-automation/src/toggle-door-packaged-only.test.ts`, new top-level describe `[ADR-0126 §7.2] switching ON a packaged flow its own status disarms is refused, and nothing half-flips`: - status `obsolete` and status `invalid`: code `RESOURCE_CONFLICT` and status 409, the status named. `setActive` is never called, the ledger stays empty, the `/_status` row is unchanged, the trigger stays unbound and `execute` answers `FLOW_DISABLED`. - Off both ways (ledger row and status): refused, and the row is unchanged. - Toggle off: accepted, the row is written, and the flow stays off after a republish as `active`. - The named step completes: republished `active`, the switch arms it. - CONTROL, status `active` and status `draft`: off and on work as before. - `runtime/src/domains/automation-toggle-caller.test.ts`, new top-level describe `[ADR-0126 §7.2] the toggle door answers the engine state, not the request`: - Enable request over a service whose state reads off: `{enabled:false}`, which equals `/_status`. - Disable request over a service whose state reads on: `{enabled:true}`. - CONTROL: state and request agree. - A service without `getFlowRuntimeStates`: the legacy echo. - `runtime/src/domains/automation-addressed-route.test.ts`, new top-level describe `[ADR-0126 §7.2] the toggle door answers the switched slot, on a name two packages hold` (real dispatcher, real `SchemaRegistry`, an engine double that keeps each slot's state and reads one row per slot under the bare name, in registration order). Each case switches the holder registered SECOND, with the first holder's row reading the opposite state: - ON at the second holder's address, the first holder off: `200 {enabled: true}`, equal to that slot's state. - OFF at the second holder's address, the first holder on: `200 {enabled: false}`. - The bare name whose one served holder is the second registered (the first package disabled, its slot off): `200 {enabled: true}`, through `toggleFlowSlot`, the bare `toggleFlow` never called. - CONTROL: the first holder's address, the second reading the opposite: the answer is the first holder's own state. - CONTROL: a name one package holds still answers its one row read back, not the request. Existing tests whose behaviour changed, each named: - `service-automation/src/flow-activation-ledger.test.ts`, case "a STATUS-disabled subflow gets a remedy through its definition — this switch never moves a status". It asserted that `toggleFlow('shared_step', true)` resolves and the child still answers `FLOW_DISABLED`. It now asserts the toggle rejects with `RESOURCE_CONFLICT` / 409, and the child still answers `FLOW_DISABLED`. - `service-automation/src/flow-activation-late-trigger.test.ts`, case "re-enabling the LEDGER bit of a flow whose STATUS is obsolete does not arm it". It is renamed "switching ON a flow whose STATUS is obsolete is refused before the ledger write, and it stays unarmed". The toggle now rejects with `RESOURCE_CONFLICT` / 409, and the unbound, `enabled:false`, `FLOW_DISABLED` assertions are unchanged. The runtime toggle test file gains a module-top `import '@objectstack/metadata'`, which `check:test-source-alias` asks for (the same line its sibling tests carry). ## Acceptance notes - **Landing tier: narrowing (`Clause-②: no (narrowing)`, BREAKING), handed to the seat as Tier H.** The changeset carries the ADR-0087 disposition `not-required (no-migration-prescription)`: no schema key, value, metadata type or stored row moves, only one REST door's answer. - **#34654 has landed; this branch has taken it.** That PR also edited `engine.ts`. This PR touches only two spots there, the `toggleFlowKey` host literal and the `toggleFlow` docblock (now near lines 7528 and 7571). `origin/main` e9f65a3, which carries #34654, merged into this branch cleanly in fix round 1 (merge 8eee7dd). - Half A (a packaged flow that declares it ships switched off) is not in this PR. It is a new authorable key and gets its own PR and contract review. - The engine's arming gate in `activateFlowTrigger` still declines any flow that may not run. The toggle no longer reaches it with a status-disarmed flow switched on. - **Fix round 1 (L1 REWORK 6948915409), by seat 3:** - **M1 fixed.** The read-back picked the first row of the name, which on a name two packages hold is the first-registered holder's, so switching the other holder (at its address, or bare with one served holder left) answered the wrong package's state. The door now reads back only a name's one row; with two or more rows it echoes, which every engine toggle entry makes true. A fix inside `flowSlotView` was not taken: the engine's rows carry no slot key, so a view cannot tell its own row apart without a new engine member, outside this PR's claimed surface. - **Pins:** the five cases above. **Ablation** (fix reverted to `rows[0]`): 3 of 65 red, exactly the three second-holder cases; both CONTROLs green. - **Real stack, measured once and not committed:** a throwaway step appended to the Q4 case of `packages/qa/dogfood/test/flow-name-per-namespace.dogfood.test.ts` (alpha's `qa_ns_q4` off, theta's installed second). With the fix, `POST /automation/theta/qa_ns_q4/toggle {enabled:true}` answered `{enabled:true}` and `getFlowRuntimeStates` read two `qa_ns_q4` rows `[false, true]`. With the fix reverted and `@objectstack/runtime` rebuilt (marker proven in `dist/`), the same call answered `{"name":"qa_ns_q4","enabled":false}`, alpha's row, the scenario L1 described. Restored, rebuilt, marker proven absent. - **S1:** the withdrawn contract-review routing line (review#1, stamped 12:31Z) is removed. - `origin/main` merged (it carries #34654), clean; overlap-check VERDICT clean. - Full dogfood battery on head 8eee7dd: `VERDICT command-exit 0`, Test Files 479 passed / 3 skipped (482), Tests 4067 passed / 68 skipped (4135). Readings in Verification. ## Verification <details><summary>Fix round 1 (head 8eee7dd): tests, ablation, real-stack probe, battery, gates</summary> Every run went through `scripts/pm/os-verify-lock.sh`; each verdict line is quoted from that run. - Door pins on 5b5f2e6: `automation-addressed-route.test.ts` + `automation-toggle-caller.test.ts`: Test Files 2 passed (2), Tests 65 passed (65), `VERDICT command-exit 0`. - Ablation (`scripts/ablation-replace.mjs`): anchor `const state = rows.length === 1 ? rows[0] : undefined;` replaced by `const state = rows[0];`, anchor 1 to 0, blob a1367e7 to b7aa5bd21d9a. Same two files: Tests 3 failed / 62 passed, `VERDICT command-exit 1`. Red: ON at the second holder's address, OFF at the second holder's address, the bare name with the second holder served. Green: both CONTROLs. Restored: blob == HEAD a1367e7, `git diff HEAD` empty. The suites import the door by relative path, so no `dist/` sits between mutation and run. - Real-stack probe (throwaway, not committed), Q4 case of `flow-name-per-namespace.dogfood.test.ts` on 8eee7dd: with the fix, Tests 10 passed (10). Fix reverted (blob 65e6a60 to 08a723a102aa), `@objectstack/runtime` rebuilt, `ablation-dist-preflight` found the marker in `dist/`: Tests 1 failed / 9 passed, `{"success":true,"data":{"name":"qa_ns_q4","enabled":false}}` against expected `enabled: true`. Restored to HEAD blob, rebuilt, preflight `--absent` exit 0; probe removed, `git status` clean. - On 8eee7dd: `pnpm --filter @objectstack/runtime test`: Test Files 613 passed (613), Tests 11417 passed / 23 skipped. `pnpm --filter @objectstack/runtime typecheck`: exit 0. `pnpm --filter @objectstack/service-automation test`: Test Files 287 passed (287), Tests 4139 passed (4139). `pnpm --filter @objectstack/service-automation typecheck`: exit 0. - Full dogfood (`pnpm --filter @objectstack/dogfood test`, no shard, no path) on 8eee7dd: `VERDICT command-exit 0`, Test Files 479 passed / 3 skipped (482), Tests 4067 passed / 68 skipped (4135). - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on 8eee7dd: 75 families, each run with stdin from /dev/null. 73 exit 0 on the first sweep. `check:type-check-debt` answered queue-timeout (exit 99 inside, PREREQUISITE NOT MET 3) while the battery held the lock; rerun under the lock: exit 0. `check:dual-build-cjs-loads` answered PREREQUISITE NOT MET (3, no dist for some packages); after the full package build, exit 0. `--ran` with exit codes: 75 derived, 75 run, 0 NOT-MEASURED, 0 UNRUN. - `node scripts/pm/overlap-check.mjs`: origin/main e9f65a3 and #34793 merge cleanly, `VERDICT clean exit 0`. - CI on 8eee7dd: 53 check-runs, all completed, 37 `success` and 16 `skipped`, none failed (including `Lint & Repo Gates`, `TypeScript Type Check`, `Test Core`, `Build Core`, `Dogfood Regression Gate`, `Live E2E UI`, `Test UI`, `Check Changeset`, `Governed Surface Queue Guard`). </details> Premise re-measured on `origin/main` f6f5b50 before the change, with throwaway tests, since deleted: - Engine, packaged flow with a record-change trigger and a ledger, `toggleFlow(f, true)`: for `obsolete` and `invalid` the call resolved, a row `active:true` was written, the flow read enabled false, the trigger stayed unbound and `execute` answered `FLOW_DISABLED`. For `active` and `draft` (CONTROL) the flow read enabled true and the trigger was bound. - Door: 200 `{"success":true,"data":{"name":"f","enabled":true}}`, while `GET /automation/_status` read `enabled:false`. `git merge-tree --write-tree` of head a65f6b4 against #34654's head `8598c1dcb77d7865c91fac5e967d1df84ed44d7d`: exit 0, clean, tree 85297242129540c331add7b00258ba97dda41841. <details><summary>Ablation readings (one per changed behaviour, through scripts/ablation-replace.mjs; mutation landed and restored to the HEAD blob, git diff HEAD empty)</summary> - Refusal removed (`if (enabled && this.flowStatusDisabled.get(name) === true) {` changed to `if (false && …`), anchor 1 to 0, blob d82d747 to 2e5b155587b8. Result: `toggle-door-packaged-only` + `flow-activation-ledger` 5 failed / 63 passed. Red: both status pins, the both-ways pin, the step-completes pin and the existing ledger subflow case. The toggle-off pin and both CONTROLs stayed green, as expected. Restored to d82d747. - Door read-back removed (the answer back to `deps.success({ name, enabled })`), anchor 1 to 0, blob 66105af to 3fe21d164cbd. Result: `automation-toggle-caller` 2 failed / 4 passed. Red: both disagreeing-state pins. The CONTROL and the no-read-method echo pin stayed green. Restored to 66105af. Both suites import the source under test by relative path, so no `dist/` sits between the mutation and the run. </details> <details><summary>Local tests (heads 0c7fc78 and a65f6b4)</summary> All runs went through `scripts/pm/os-verify-lock.sh`, which ended with `VERDICT command-exit 0`. - `pnpm --filter @objectstack/service-automation test` on 8c918c4, before the merge of `origin/main` f02f4f6: the first run showed 1 failed, the existing `flow-activation-late-trigger` case named above, which was updated in 8c918c4. That file was rerun: 11/11. The package total is 287 files and 4113 tests, all green except that one case before its update. `pnpm --filter @objectstack/service-automation typecheck` (tsc plus check:test-typecheck): exit 0. - `pnpm --filter @objectstack/runtime test && pnpm --filter @objectstack/runtime typecheck`, then the three touched service-automation files, on merge head 03f7f18: runtime Test Files 611 passed (611), Tests 11342 passed, 19 skipped; service-automation Test Files 3 passed (3), Tests 79 passed (79). - The last commit, 0c7fc78, adds only the module-top import to `automation-toggle-caller.test.ts`. That file was rerun: 6/6. - `@objectstack/spec` check:generated after the merge: all 14 generated artifacts are up to date. - Full dogfood on a65f6b4 under os-verify-lock: VERDICT command-exit 0; Test Files 479 passed | 3 skipped (482); Tests 4059 passed | 68 skipped (4127). After the merge of `origin/main` at a65f6b4: runtime test + typecheck 611/611 files, 11346 passed / 19 skipped; the three touched service-automation files 79/79; typecheck exit 0; the three changeset gates exit 0. </details> <details><summary>Derived gates (dispatch-gates --commands, reconciled with --ran)</summary> Derived on head a65f6b4 (and first on 0c7fc78): `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` listed 75 families. Each one was run with stdin from /dev/null, and its exit code was taken before any pipe. - Result: 75 of 75 exit 0. `dispatch-gates --ran`: 75 derived, 75 run, 0 NOT-MEASURED, 0 UNRUN. - On the first sweep (head 03f7f18), two families were not green: - `check:dual-build-cjs-loads` answered exit 3 (PREREQUISITE NOT MET, no dist). It went green after a full `pnpm build`. - `check:test-source-alias` answered exit 1: the new runtime pins reach `@objectstack/metadata` through a dynamic import. 0c7fc78 adds the module-top import the gate asks for. - Both families are exit 0 on the final sweep. The repo-wide families are left to CI. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfr1xZSFZzCR8HnqXX --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0584eb5 commit 583bbf3

9 files changed

Lines changed: 366 additions & 14 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
fix(automation)!: switching on a packaged flow that its own status disarms is refused, and the toggle door answers the engine's state
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
Skills-docs: none — skills/objectstack-automation/SKILL.md teaches the toggle only as the off switch for an installed package's flow; nothing it says changes
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value, metadata type or stored row shape is added, removed, renamed or rewritten: what moves is the answer of one REST door (POST /automation/:name/toggle, and the IAutomationService.toggleFlow it calls) to one request, switching on a packaged flow whose own status already keeps it off. A flow definition that was valid stays valid and is armed exactly as before; nothing exists for objectstack migrate meta to rewrite. The one-line fix for a caller is in the body: publish the flow with status active, then switch it on. -->
13+
14+
**BREAKING** for a caller that switches on a packaged flow whose definition's `status` is `obsolete` or `invalid`. The switch moves only the activation-ledger bit, and a status is the author's, so that request never made the flow run. It now says so instead of reporting success.
15+
16+
**What changes.**
17+
18+
- `POST /api/v1/automation/:name/toggle` with `{ enabled: true }` (and `IAutomationService.toggleFlow(name, true)` on the engine's service) on such a flow used to answer `200 { name, enabled: true }`. It wrote `active: true` to `sys_metadata_activation`, replacing any `active: false` row an administrator had left there, while `GET /automation/_status` read `enabled: false`. It now answers `409 RESOURCE_CONFLICT`, names the status, and writes nothing.
19+
- An `active: false` row already standing for the flow stays as it is.
20+
- The refusal names the step that arms the flow: publish it with status `active`, or for a read-only package, install a package version that ships it active.
21+
- A second case changes. An administrator switches such a flow on while it is still `obsolete`, and the flow is later published or shipped `active`. If the ledger held an `active: false` row for it, the flow used to run as soon as it arrived `active`, because the earlier switch-on had replaced that row. Now the row is still there, so the flow stays off after it arrives `active` until it is switched on again.
22+
- The door's `200` answer reads `enabled` back from `getFlowRuntimeStates`, the same reading `GET /automation/_status` serves, and no longer echoes the request. A service that does not implement `getFlowRuntimeStates` keeps the old answer, the request echoed. So does a flow name two packages hold, switched at one package's address (`/automation/:ns/:name/toggle`) or at the bare name while only one holder's package is enabled: that reading has one row per holder under the same name, so it cannot tell which row was switched, and the engine's echo is true because it refuses the one switch-on that would leave the flow off.
23+
24+
**Who moves, in one line.** Publish the flow with status `active` first, then switch it on. A flow already published `active` that still reads `enabled: false` needs one more switch-on.
25+
26+
**Unchanged.** Switching such a flow off is still accepted: it writes `active: false`, which keeps the flow off after a later definition ships it active. Every flow whose status is `active` or `draft` switches on and off as before. A customer-authored flow is still refused by the earlier provenance check.

‎packages/runtime/src/domains/automation-addressed-route.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,3 +719,103 @@ describe('[#33905] a flow whose only holder\'s package is disabled: the bare doo
719719
}
720720
});
721721
});
722+
723+
/**
724+
* [ADR-0126 §7.2, ADR-0150 D4] The toggle door's `200` answers the switched
725+
* flow's own state, on a name two packages hold too. The door reaches such a
726+
* name through `flowSlotView` (an address, or the bare name with one served
727+
* holder left), whose `toggleFlow` switches one slot, while the engine reads
728+
* one row per slot under the bare name, in registration order. A row picked by
729+
* name there is the FIRST holder's, so each case switches the holder
730+
* registered SECOND, with the first one's row reading the opposite state.
731+
*
732+
* Driven through the real dispatcher over a real `SchemaRegistry`, and an
733+
* engine double that keeps each slot's state, switches it in `toggleFlowSlot`
734+
* and reads it back the engine's way (`getFlowRuntimeStates`: one row per
735+
* slot, under the bare name).
736+
*/
737+
describe('[ADR-0126 §7.2] the toggle door answers the switched slot, on a name two packages hold', () => {
738+
const NAME = 'convert';
739+
740+
function registryOf(order: readonly string[], disabled: readonly string[] = []) {
741+
const registry = new SchemaRegistry();
742+
registry.logLevel = 'silent';
743+
for (const [id, namespace] of [[CRM, 'crm'], [HR, 'hr']]) {
744+
registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace } as never, 'code');
745+
}
746+
for (const holder of order) registry.registerItem('flow', { name: NAME, _packageId: holder }, 'name' as never, holder);
747+
for (const id of disabled) registry.disablePackage(id);
748+
return registry;
749+
}
750+
751+
/** `slots`: each holder's slot of `NAME` and its state, in registration order. */
752+
function dispatcherOver(registry: SchemaRegistry, slots: Array<[string, boolean]>) {
753+
const state = new Map(slots);
754+
const keyed = (pkg: string | null) => (pkg !== null && state.has(pkg) ? (state.size > 1 ? `${pkg}/${NAME}` : NAME) : undefined);
755+
const shared = () => Object.assign(new Error(`Flow '${NAME}' is held by several packages`), { code: 'RESOURCE_CONFLICT', status: 409 });
756+
const automation = {
757+
handlerReady: true,
758+
getFlow: vi.fn(async (name: string) => { if (name === NAME) throw shared(); return null; }),
759+
toggleFlow: vi.fn(async (name: string) => { if (name === NAME) throw shared(); }),
760+
getFlowRuntimeStates: vi.fn(() => [...state].map(([, enabled]) => ({ name: NAME, enabled, bound: enabled }))),
761+
flowSlotKey: vi.fn((pkg: string | null, name: string) => (name === NAME ? keyed(pkg) : undefined)),
762+
getFlowSlot: vi.fn((pkg: string | null, name: string) => (name === NAME && keyed(pkg) ? { name, label: `${pkg} flow` } : null)),
763+
executeSlot: vi.fn(async () => ({ success: true, output: {} })),
764+
toggleFlowSlot: vi.fn(async (pkg: string, _name: string, enabled: boolean) => { state.set(pkg, enabled); }),
765+
};
766+
const services: Record<string, unknown> = { automation, objectql: { registry } };
767+
const resolve = (name: string) => services[name];
768+
const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } };
769+
const dispatcher = new HttpDispatcher(kernel);
770+
const toggle = async (path: string, enabled: boolean) => {
771+
const answered = await dispatcher.handleAutomation(path, 'POST', { enabled }, { request: {}, executionContext: ADMIN } as any, {});
772+
return { status: answered.response?.status ?? 200, body: answered.response?.body as any };
773+
};
774+
return { toggle, automation, stateOf: (pkg: string) => state.get(pkg) };
775+
}
776+
777+
it('switched ON at the second holder\'s address, the first holder off: 200 { enabled: true }, that slot\'s state (FROM: the first holder\'s false)', async () => {
778+
const { toggle, automation, stateOf } = dispatcherOver(registryOf([CRM, HR]), [[CRM, false], [HR, false]]);
779+
const on = await toggle(`/hr/${NAME}/toggle`, true);
780+
expect(automation.toggleFlowSlot.mock.calls.map((c) => [c[0], c[2]])).toEqual([[HR, true]]);
781+
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: true }]);
782+
expect(on.body?.data?.enabled).toBe(stateOf(HR));
783+
expect(stateOf(CRM)).toBe(false);
784+
});
785+
786+
it('switched OFF at the second holder\'s address, the first holder on: 200 { enabled: false } (FROM: the first holder\'s true)', async () => {
787+
const { toggle, stateOf } = dispatcherOver(registryOf([CRM, HR]), [[CRM, true], [HR, true]]);
788+
const off = await toggle(`/hr/${NAME}/toggle`, false);
789+
expect([off.status, off.body?.data], JSON.stringify(off.body)).toEqual([200, { name: NAME, enabled: false }]);
790+
expect(off.body?.data?.enabled).toBe(stateOf(HR));
791+
expect(stateOf(CRM)).toBe(true);
792+
});
793+
794+
it('the bare name whose one served holder is the second registered (the first disabled, its slot off): 200 { enabled: true } (FROM: the disabled holder\'s false)', async () => {
795+
const { toggle, automation, stateOf } = dispatcherOver(registryOf([CRM, HR], [CRM]), [[CRM, false], [HR, false]]);
796+
const on = await toggle(`/${NAME}/toggle`, true);
797+
expect(automation.toggleFlowSlot.mock.calls.map((c) => [c[0], c[2]])).toEqual([[HR, true]]);
798+
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: true }]);
799+
expect(on.body?.data?.enabled).toBe(stateOf(HR));
800+
expect(automation.toggleFlow).not.toHaveBeenCalled();
801+
});
802+
803+
it('CONTROL — the first holder\'s address, the second holder reading the opposite: the answer is the first holder\'s own state', async () => {
804+
const { toggle, automation, stateOf } = dispatcherOver(registryOf([CRM, HR]), [[CRM, false], [HR, true]]);
805+
const on = await toggle(`/crm/${NAME}/toggle`, true);
806+
expect(automation.toggleFlowSlot.mock.calls.map((c) => [c[0], c[2]])).toEqual([[CRM, true]]);
807+
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: true }]);
808+
expect(on.body?.data?.enabled).toBe(stateOf(CRM));
809+
});
810+
811+
it('CONTROL — a name one package holds still answers its one row read back, not the request', async () => {
812+
const { toggle, automation } = dispatcherOver(registryOf([HR]), [[HR, false]]);
813+
// The row reads off whatever was asked: the door answers the row.
814+
automation.toggleFlowSlot.mockImplementation(async () => {});
815+
automation.toggleFlow.mockImplementation(async () => {});
816+
automation.getFlow.mockImplementation(async (name: string) => (name === NAME ? { name } : null) as never);
817+
const on = await toggle(`/${NAME}/toggle`, true);
818+
expect([on.status, on.body?.data], JSON.stringify(on.body)).toEqual([200, { name: NAME, enabled: false }]);
819+
expect(automation.getFlowRuntimeStates).toHaveBeenCalled();
820+
});
821+
});

‎packages/runtime/src/domains/automation-toggle-caller.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
import { describe, it, expect, vi } from 'vitest';
1515

1616
import { HttpDispatcher } from '../http-dispatcher.js';
17+
// Paid at collection, not inside a clocked case: the dispatcher's package domain
18+
// reaches it through a dynamic import (check:test-source-alias).
19+
import '@objectstack/metadata';
1720

1821
function makeDispatcher() {
1922
const toggleFlow = vi.fn(async (_name: string, _on: boolean, _caller?: { userId?: string }) => undefined);
@@ -62,3 +65,74 @@ describe('#26474 — the flow toggle door passes its caller to toggleFlow', () =
6265
expect(caller).toEqual({ userId: 'u_admin' });
6366
});
6467
});
68+
69+
/**
70+
* [ADR-0126 §7.2] The 200 answer is the engine's state read back through
71+
* `getFlowRuntimeStates` (the reading `GET /_status` serves), never the
72+
* request echoed: the switch moves only the ledger bit, so a flow its own
73+
* status keeps off read `{enabled: true}` here and `enabled: false` there.
74+
* The stand-in's state is set apart from what toggleFlow was asked, so an echo
75+
* and a read-back answer differently.
76+
*/
77+
describe('[ADR-0126 §7.2] the toggle door answers the engine state, not the request', () => {
78+
function dispatcherWithState(stateEnabled: boolean | undefined, readsState = true) {
79+
const toggleFlow = vi.fn(async () => undefined);
80+
const getFlowRuntimeStates = vi.fn(() =>
81+
stateEnabled === undefined ? [] : [{ name: 'welcome_flow', enabled: stateEnabled, bound: stateEnabled }],
82+
);
83+
const services: Record<string, unknown> = {
84+
automation: {
85+
getFlow: async (name: string) => (name === 'welcome_flow' ? { name, trigger: { type: 'manual' } } : null),
86+
toggleFlow,
87+
...(readsState ? { getFlowRuntimeStates } : {}),
88+
},
89+
};
90+
const resolve = (name: string) => services[name];
91+
const kernel: any = {
92+
getService: resolve,
93+
getServiceAsync: async (name: string) => resolve(name),
94+
context: { getService: resolve },
95+
};
96+
return { dispatcher: new HttpDispatcher(kernel), toggleFlow, getFlowRuntimeStates };
97+
}
98+
99+
it('enable requested, the engine reads the flow off: 200 { enabled: false }, as GET /_status reads it', async () => {
100+
const { dispatcher, toggleFlow } = dispatcherWithState(false);
101+
const ctx = ctxOf({ userId: 'u_admin' });
102+
103+
const on = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: true }, ctx);
104+
const status = await dispatcher.handleAutomation('/_status', 'GET', undefined, ctx);
105+
106+
expect(toggleFlow).toHaveBeenLastCalledWith('welcome_flow', true, { userId: 'u_admin' });
107+
expect(on.response?.status).toBe(200);
108+
expect(on.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: false });
109+
expect(status.response?.body?.data?.flows?.[0]?.enabled).toBe(on.response?.body?.data?.enabled);
110+
});
111+
112+
it('disable requested, the engine reads the flow on: 200 { enabled: true }', async () => {
113+
const { dispatcher } = dispatcherWithState(true);
114+
115+
const off = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: false }, ctxOf({ userId: 'u_admin' }));
116+
117+
expect(off.response?.status).toBe(200);
118+
expect(off.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: true });
119+
});
120+
121+
it('CONTROL — engine state agrees with the request: the answer is that state', async () => {
122+
const { dispatcher, getFlowRuntimeStates } = dispatcherWithState(true);
123+
124+
const on = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: true }, ctxOf({ userId: 'u_admin' }));
125+
126+
expect(on.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: true });
127+
expect(getFlowRuntimeStates).toHaveBeenCalled();
128+
});
129+
130+
it('a service that does not implement the read keeps the legacy answer, the request echoed', async () => {
131+
const { dispatcher } = dispatcherWithState(undefined, false);
132+
133+
const off = await dispatcher.handleAutomation('/welcome_flow/toggle', 'POST', { enabled: false }, ctxOf({ userId: 'u_admin' }));
134+
135+
expect(off.response?.status).toBe(200);
136+
expect(off.response?.body?.data).toEqual({ name: 'welcome_flow', enabled: false });
137+
});
138+
});

‎packages/runtime/src/domains/automation.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3781,7 +3781,15 @@ export async function classifyResumeResult(
37813781
* activation ledger. A flow no package ships → 409
37823782
* `RESOURCE_CONFLICT` naming that flow's own switch,
37833783
* its `status` ('obsolete' / 'active') published
3784-
* through `PUT /:name`; nothing changes (#20726)
3784+
* through `PUT /:name`; nothing changes (#20726).
3785+
* Switching ON a packaged flow whose own `status`
3786+
* disables it → 409 `RESOURCE_CONFLICT` naming the
3787+
* status; nothing changes. 200 answers
3788+
* `{ name, enabled }` with `enabled` read back from
3789+
* `getFlowRuntimeStates` while the name has one
3790+
* row there (echoed by a service that does not
3791+
* implement that read, and for a name two packages
3792+
* hold, which reads one row per holder)
37853793
* ⚑ authoring write — `manage_metadata` (commit 266436a7f):
37863794
* enablement is environment-wide, so an
37873795
* unentitled toggle reached every organization
@@ -4422,7 +4430,31 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str
44224430
// [#26474] Who asked, so the ledger row and its audit row name
44234431
// them. The id only: this door has already judged the caller.
44244432
await automationService.toggleFlow(name, enabled, activationCaller(context));
4425-
return { handled: true, response: deps.success({ name, enabled }) };
4433+
// [ADR-0126 §7.2] The answer is the engine's state read back,
4434+
// never the request echoed: the switch moves only the ledger
4435+
// bit, and the flow's `status` is a second dimension it does
4436+
// not move, so "the write landed" and "the flow is on" are two
4437+
// facts. Read through `getFlowRuntimeStates`, the one reading
4438+
// `GET /_status` serves, so the two doors cannot disagree.
4439+
// That reading names the switched flow only while the name
4440+
// has ONE row. A name two packages hold reaches here too: by
4441+
// its address, or bare with one served holder left, through
4442+
// `flowSlotView`, whose `toggleFlow` switches one slot while
4443+
// the engine still reads one row per slot under the bare
4444+
// name ([ADR-0150 D4], `getFlowRuntimeStates`). A row picked
4445+
// by name there may be the other holder's, so two or more
4446+
// rows read back nothing. Then, as for a service that does
4447+
// not implement the read or holds no row of the name, the
4448+
// request is echoed, the legacy answer; for the engine's own
4449+
// service (the only one with slots) that echo is true by
4450+
// construction, since every toggle entry refuses switching
4451+
// on a flow its status keeps off.
4452+
const svc = automationService as Pick<IAutomationService, 'getFlowRuntimeStates'>;
4453+
const rows = typeof svc.getFlowRuntimeStates === 'function'
4454+
? svc.getFlowRuntimeStates().filter((s) => s.name === name)
4455+
: [];
4456+
const state = rows.length === 1 ? rows[0] : undefined;
4457+
return { handled: true, response: deps.success({ name, enabled: state ? state.enabled : enabled }) };
44264458
}
44274459
}
44284460

0 commit comments

Comments
 (0)