Skip to content

Commit d9bf777

Browse files
feat(spec): optional caller on IAutomationService.toggleFlow (#26545)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBXVayMXFjUu7EtXTKCGj4pc)_ Fixes #26506 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:`IAutomationService.toggleFlow` 增加可选的第三个参数 `caller`,只携带 `userId`,用来告诉服务是谁开关了这个打包流程。 - 为什么改:管理员关掉打包流程时,激活台账行与审计行的操作人都是空,审计无法说明是哪位管理员做的;服务端修复 (#26474) 需要契约先有这个通道。 - 风险与回滚:参数可选,现有实现与调用方原样编译,运行时行为零变化;回滚即还原这一行签名。 - 先看:`packages/spec/src/contracts/automation-service.ts`(`toggleFlow` 签名与 TSDoc),`packages/spec/src/contracts/automation-toggle-flow-caller.pin.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/spec exec vitest run src/contracts/automation-toggle-flow-caller.pin.test.ts`,预期 2 个用例通过。 - 需要你做的:无,席位落地。 ## What changes `IAutomationService.toggleFlow?(name, enabled)` gains an optional third parameter, `caller`, typed as `Pick` over `AutomationContext` narrowed to the single key `'userId'`. A door that serves a person passes that person's id, so the `sys_metadata_activation` row the switch writes, and its `sys_audit_log` row, can name the admin instead of a null actor. The method's TSDoc now says what the channel carries, that it is attribution only (it grants nothing, and an implementation neither refuses nor widens the switch on it), and that an absent caller, or one with no `userId`, means an unattributed write. The parameter is optional, so every current implementer (`AutomationEngine.toggleFlow` in `@objectstack/service-automation`) and every caller (the runtime's `POST /api/v1/automation/:name/toggle` door and its test doubles) compiles unchanged. This is the contract half only: the door passing the caller and the engine writing with it are the server half, #26474. ## Why this shape The order was to follow `execute(flowName, context?: AutomationContext)` in the same contract, reusing `AutomationContext` or a narrow subset of it. I took the subset, one key: - **`userId` is the key the write records.** The engine stamps `created_by` / `updated_by` from the context's user, and the audit writer reads `user_id` from it. `AutomationContext.userId` is already the contract's spelling for "the acting user", so `execute` and `toggleFlow` name the person the same way. - **No positions, permissions or posture.** `toggleFlow` is no authority gate: ADR-0126 §5 gates the switch at the door that receives the request, and the ledger write runs elevated. A channel carrying grants would invite a second gate inside the service whose rules could drift from the door's. - **No tenant.** The activation ledger is deployment state with no organization column (ADR-0126 as amended by ADR-0131 D6), so a tenant id would carry nothing the write reads. - **Not the whole `AutomationContext`.** Most of its keys (`record`, `params`, `runAs`, `flowName`, `flowRunId`, `callerParamKeys`) describe a run and mean nothing for a switch. Taking the whole type would leave each implementer to decide which to ignore. With the narrow type, a caller literal carrying `positions` or `record` does not compile (pinned). - **Not `ExecutionContext`.** Several store contracts take the caller as `ExecutionContext | undefined` (`IAIConversationService`, `ISharingService`). That would hand the service the caller's whole principal, grants included, which is the second-gate risk above. The order also pointed at the `AutomationContext` precedent in this contract. Widening later is additive: another key can join the `Pick` if a reader ever needs it. ## Tests `packages/spec/src/contracts/automation-toggle-flow-caller.pin.test.ts`, compiled by `check:test-typecheck` under `tsconfig.test.json` and run by vitest: - type level: the third parameter is exactly the narrowed `Pick` or `undefined`; the arity is 2 or 3; `name` and `enabled` keep their types and places; - additive: a two-parameter implementation (a function and a class) still satisfies the contract, and a two-argument call still compiles; - narrow: a caller literal with `positions`, or with `record`, is a compile error (`@ts-expect-error`, which itself fails if the line ever compiles); - runtime: an implementation reads `caller?.userId` without a cast, and reads it as absent when not passed; a two-parameter implementation runs when a caller is passed. Reverse verification (one-off, not kept): the signature reverted to the two-parameter form via `scripts/ablation-replace.mjs` (anchor 1 to 0, blob `8fc1e1cc` to `201b1e11`), then `tsc --noEmit -p tsconfig.test.json`. The pin file turned red with 9 errors (TS2344 on both identity asserts, TS2554 on each three-argument call, TS2493 and TS7006 where the third parameter vanished). Restored: blob equals HEAD and `git diff HEAD` is empty. ## Acceptance notes - Until #26474's server half lands, the flow switch still writes a null actor; this PR changes no runtime behaviour. - The runtime tests that pin the door's call as `toHaveBeenCalledWith(FLOW, false)` (`automation-activation-posture-gate.test.ts`, `http-dispatcher.test.ts`) will need the caller argument when the door starts passing it. That is the server half's edit, noted here so it is not a surprise. - A non-human caller (an agent or service principal) has no `actor` label on this channel; `AutomationContext` declares none. No reader needs one today. ## Verification All readings at head `f3ce50a7`, in the `objectstack-issue-26506` worktree based on `origin/main` `3fcafcd3`. - `pnpm --filter @objectstack/spec build` under the verify lock: VERDICT command-exit 0. - `pnpm --filter @objectstack/spec check:generated`: exit 0, all 14 generated artifacts up to date, and `git status` clean afterwards, so no generated artifact moved (`api-surface/contracts.json` records `IAutomationService` by name only). - `pnpm --filter @objectstack/spec typecheck` (tsc, scripts typecheck, `check:test-typecheck`) and vitest on the new pin, `automation-service.test.ts` and `automation-context-caller-param-keys.pin.test.ts`: VERDICT command-exit 0, Test Files 3 passed, Tests 22 passed. - `pnpm exec eslint --no-inline-config` on both changed `.ts` files: exit 0. <details><summary>Derived gates: 79 derived, 75 run with exit 0, 4 NOT MEASURED</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 79 families from the three changed paths; all were run serially and reconciled with `--ran` (79 accounted, 0 unrun). Four exited 3, PREREQUISITE NOT MET, because this container has a shallow clone and no full build. They read nothing this diff touches, and CI runs them: - `node scripts/check-plugin-teardown-shape.mjs --self-test` (needs an unshallowed `main`) - `pnpm --filter @objectstack/lint run check:doc-formula-expressions` (needs built packages) - `pnpm check:dual-build-cjs-loads` (needs every package's `dist`) - `pnpm check:lean-entry-closure` (needs `@objectstack/objectql` built) </details> Not run locally: the full dogfood battery (the title has no `!` and the declaration has no `(narrowing)` arm), `test:repo` and the repo-wide lint, which are CI's. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzgdxgk35nWqLB6EMzg --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzgdxgk35nWqLB6EMzg)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent ab3c776 commit d9bf777

3 files changed

Lines changed: 120 additions & 1 deletion

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/spec': patch
3+
---
4+
5+
feat(spec): `IAutomationService.toggleFlow` takes an optional caller, so switching a packaged flow on or off can name the admin who did it
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
`toggleFlow?(name, enabled)` gains an optional third parameter, `caller?: Pick<AutomationContext, 'userId'>`. A door that serves a person passes that person's id, so the `sys_metadata_activation` row the switch writes, and its `sys_audit_log` row, can name the administrator instead of a null actor. An absent caller, or one without a `userId`, means an unattributed write. The channel carries the acting user only: it grants nothing, since the authority gate stays at the door, and it names no tenant, since the activation ledger has no organization column.
11+
12+
The parameter is optional, so every current implementer and caller compiles unchanged. This is the contract half: the toggle door and `@objectstack/service-automation`'s `toggleFlow` start passing and writing the caller in a later change, and until then the flow switch's ledger row still carries no actor.

‎packages/spec/src/contracts/automation-service.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -991,10 +991,31 @@ export interface IAutomationService {
991991
* the automation service refuses it with `RESOURCE_CONFLICT` / 409 and
992992
* changes nothing. That flow's switch is its own `status` (`'obsolete'` /
993993
* `'active'`), published through {@link registerFlow}.
994+
*
995+
* `caller` names who made the request, so the activation-ledger row the
996+
* switch writes, and the audit row that write produces, attribute it to
997+
* that user. It carries {@link AutomationContext.userId} and nothing else:
998+
* the key {@link execute} reads for its acting user, narrowed to what the
999+
* write records.
1000+
* - No positions, permissions or posture. This method is no authority
1001+
* gate: ADR-0126 §5 gates the switch at the door that receives the
1002+
* request, and the ledger write itself runs elevated. A channel that
1003+
* carried grants would invite a second, divergent gate here.
1004+
* - No tenant. The ledger is deployment state with no organization column
1005+
* (ADR-0126 as amended by ADR-0131 D6).
1006+
*
1007+
* A door that serves a person passes that person's id. An absent `caller`,
1008+
* or one without a `userId`, means an unattributed write: the ledger row
1009+
* and its audit row carry no actor. That is the honest answer for an
1010+
* in-process caller with no person behind it, never the answer for a door
1011+
* that has one. Attribution only: the channel grants nothing, and an
1012+
* implementation neither refuses nor widens the switch on it.
1013+
*
9941014
* @param name - Flow name (snake_case)
9951015
* @param enabled - Whether to enable (true) or disable (false)
1016+
* @param caller - Who made the request; absent means an unattributed write
9961017
*/
997-
toggleFlow?(name: string, enabled: boolean): Promise<void>;
1018+
toggleFlow?(name: string, enabled: boolean, caller?: Pick<AutomationContext, 'userId'>): Promise<void>;
9981019

9991020
/**
10001021
* List execution runs for a flow
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26506] `IAutomationService.toggleFlow`'s caller channel — who switched a
5+
* packaged flow on or off, so the activation-ledger row and its audit row can
6+
* name that user instead of writing a null actor.
7+
*
8+
* Pinned here, at the type level, because a TypeScript interface member has no
9+
* Zod schema to assert against (the `automation-context-caller-param-keys`
10+
* pin's form, compiled by `check:test-typecheck` under `tsconfig.test.json`):
11+
*
12+
* 1. **The third parameter is exactly `Pick<AutomationContext, 'userId'>`,
13+
* optional.** The acting-user key `execute` already reads, and nothing
14+
* else: no grants (the authority gate stays at the door) and no tenant
15+
* (the ledger has no organization column). A caller literal carrying
16+
* positions or a record does not compile.
17+
* 2. **Additive.** A two-argument call still compiles, and so does an
18+
* implementation written against the two-parameter signature, so no
19+
* current implementer or caller moves.
20+
*
21+
* ⛔ Not pinned here: that the doors pass the caller and that the ledger write
22+
* carries it. That is the server half, `@objectstack/runtime`'s toggle door
23+
* and `@objectstack/service-automation`'s `toggleFlow` (#26474).
24+
*/
25+
26+
import { describe, it, expect } from 'vitest';
27+
28+
import type { AutomationContext, IAutomationService } from './automation-service';
29+
30+
/** Type-level identity: true iff A and B are the same type. */
31+
type Eq< A, B > = (< T >() => T extends A ? 1 : 2) extends (< T >() => T extends B ? 1 : 2) ? true : false;
32+
/** Compile error when the argument is not `true`. */
33+
type Assert< T extends true > = T;
34+
35+
type ToggleFlow = NonNullable< IAutomationService['toggleFlow'] >;
36+
type ToggleFlowParams = Parameters< ToggleFlow >;
37+
38+
// Exported deliberately — an unread alias is TS6196, and a pin no program compiles is no pin at all.
39+
40+
/** The third parameter is the caller, narrowed to the acting user, optional. */
41+
export type CallerIsTheActingUserOnly = Assert< Eq< ToggleFlowParams[2], Pick< AutomationContext, 'userId' > | undefined > >;
42+
/** It is the last parameter, and the two existing ones keep their place. */
43+
export type ToggleFlowArity = Assert< Eq< ToggleFlowParams['length'], 2 | 3 > >;
44+
export type NameAndEnabledUnchanged = Assert< Eq< [ToggleFlowParams[0], ToggleFlowParams[1]], [string, boolean] > >;
45+
46+
/** Additive: an implementation written against the two-parameter signature still satisfies the contract. */
47+
export const twoParameterToggle: ToggleFlow = async (_name: string, _enabled: boolean) => {};
48+
export class TwoParameterService implements Pick< IAutomationService, 'execute' | 'listFlows' | 'toggleFlow' > {
49+
async execute() { return { success: true }; }
50+
async listFlows() { return []; }
51+
async toggleFlow(_name: string, _enabled: boolean): Promise< void > {}
52+
}
53+
54+
/** Additive: a two-argument call still compiles. */
55+
export const twoArgumentCall = (service: IAutomationService) => service.toggleFlow?.('showcase_urgent_task_alert', false);
56+
export const callerCall = (service: IAutomationService) =>
57+
service.toggleFlow?.('showcase_urgent_task_alert', false, { userId: 'usr_admin' });
58+
59+
/** A caller that names no user is allowed, and reads as an unattributed write. */
60+
export const anonymousCaller: ToggleFlowParams[2] = {};
61+
62+
// @ts-expect-error — grants are not the channel's: the authority gate stays at the door.
63+
export const callerWithPositions: ToggleFlowParams[2] = { userId: 'usr_admin', positions: ['admin'] };
64+
// @ts-expect-error — the channel is not an execution context: no record, no params.
65+
export const callerWithRecord: ToggleFlowParams[2] = { userId: 'usr_admin', record: { id: 'r1' } };
66+
67+
describe('IAutomationService.toggleFlow — the caller channel', () => {
68+
it('an implementation reads the caller id without a cast, and absent when not passed', async () => {
69+
const seen: Array< string | undefined > = [];
70+
const service: Pick< IAutomationService, 'toggleFlow' > = {
71+
toggleFlow: async (_name, _enabled, caller?) => {
72+
seen.push(caller?.userId);
73+
},
74+
};
75+
await service.toggleFlow?.('showcase_urgent_task_alert', false, { userId: 'usr_admin' });
76+
await service.toggleFlow?.('showcase_urgent_task_alert', true);
77+
expect(seen).toEqual(['usr_admin', undefined]);
78+
});
79+
80+
it('a two-parameter implementation still runs when a caller is passed', async () => {
81+
const service = new TwoParameterService();
82+
await expect(service.toggleFlow('showcase_urgent_task_alert', false)).resolves.toBeUndefined();
83+
const asContract: Pick< IAutomationService, 'toggleFlow' > = service;
84+
await expect(asContract.toggleFlow?.('showcase_urgent_task_alert', false, { userId: 'usr_admin' })).resolves.toBeUndefined();
85+
});
86+
});

0 commit comments

Comments
 (0)