Skip to content

fix(approvals): "the approval ended here" is judged by the content of the body the run ran, so it survives restarts - #38825

Merged
objectstack-fleet[bot] merged 11 commits into
mainfrom
claude/issue-37218-approval-ended-durable-witness
Dec 1, 2026
Merged

objectstack-fleet[bot] merged 11 commits into
mainfrom
claude/issue-37218-approval-ended-durable-witness

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

Fixes #37218

Clause-②: yes (widening: AutomationEngine gains getRunFlowChecksum and getFlowBodyChecksum; RunRecord gains optional flowChecksum; the exported ApprovalResumeSurface drops the optional getFlowVersionHistory and gains optional getRunFlowChecksum and getFlowBodyChecksum)
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:审批人和提交人在记录的审批面板上看已决定的请求时,"审批在此结束"这一行在每次重启或流程重新加载后不再消失;只有流程确实被改过时才不显示。
  • 为什么做:这是"审批去向"功能(告诉大家一条审批走到哪一步、是否结束)的后续修补,之前它对历史请求在每次部署后就悄悄失效。
  • 出错会怎样:最坏情况是某条已决定请求少显示"审批在此结束"(与改动前相同的保守方向),不会显示错误的结论;改动可直接撤回。
  • 要你做什么:无

What changes

A decided request's flow_route.outcome.ended ("The approval ended here") is served only when the run ran the flow body armed now. That proof used to read this process's registration history (newest registration, registered before the run started), so every restart and every re-registration of the flow dropped the line, and two narrow cases (a rollback undone after the run started; a replica that registered an edit before another replica started the run on the older body) served it for a body the run did not run.

The witness is now the body's content:

  • service-automation (the producer). A run's context carries a stamp naming the run and the content checksum of its body ($flowChecksum, run-flow-checksum.ts), written where the run starts beside $rootRun and carried through every pause and resume. The terminal record carries it (RunRecord.flowChecksum), and the sys_automation_run terminal row now writes flow_checksum on every run that paused (it was NULL on every finished run). A strand's row keeps its snapshot's pin first, as before. A run whose pinned body could no longer be found, and that resumed on another body, records none. Two reads: AutomationEngine.getRunFlowChecksum(runId) (memory, terminal row, paused row, in getRun's order) and AutomationEngine.getFlowBodyChecksum(flow).
  • plugin-approvals. ranArmedBody delegates to the new run-body-witness.ts: the run's recorded checksum equals the armed body's, else "not known". It no longer reads getFlowVersionHistory. The in-memory registration-time check is dropped rather than kept as a fast path: its only extra answers are the N7 cases, which it gets wrong.
  • spec. The ended sentence on ApprovalRequestRow.flow_route.outcome says this (doc text only).
  • N2. "Later" stays a later created_at: a pin shows the sibling case unreachable (an approval in a parallel branch, a loop body or a try_catch body is refused at parse; a subflow or map child files its requests under its own run id), and the attachFlowRoute docblock says so.

Why the producer is in service-automation, not a read-side accessor only: measured on d97aaae, the terminal row of a run that paused and then finished wrote flow_checksum = NULL (serializeConsumedSuspension(undefined)), so no durable identity of a finished run existed to read.

Tests

  • packages/plugins/plugin-approvals/src/flow-route.integration.test.ts, new top-level describe over a shared durable store: restart and same-content re-registration keep ended: true; rollback-undone and two-replica cases serve no ended; a control for two replicas holding the same body serves it.
  • packages/plugins/plugin-approvals/src/approval-route.test.ts: the N2 sibling pin, with a green control.
  • packages/services/service-automation/src/flow-version-pinning.test.ts: terminal record carries the run's body checksum; a restart reads it back; resumed after an edit names the started body; a lost pinned body records none; a run parked before the stamp gets its pin; a context carrying another run's stamp is not this run's identity.
  • packages/services/service-automation/src/suspended-run-store.test.ts: the object store writes, clears and reads back flow_checksum on terminal rows, and a strand keeps its snapshot's pin.

Ablation (reverted in the tree only, then restored from HEAD): the plugin's approval-service.ts at the base turns the 4 new plugin pins red (restart, re-registration, rollback undone, two replicas); run-history.ts at the base turns 5 of the engine pins red.

Acceptance notes

  • A run that finished before this release has no checksum on its row, so its decided requests do not serve ended (they already lost it at the restart an upgrade makes). A run paused before the release and finished after gets the pin its suspension recorded.
  • A run that never paused records no checksum on its terminal row: the execute-path record reads the caller's context, not the run's. No approval request exists for such a run, so ended is unaffected.
  • Residual: a run parked before this release that had already resumed once on a lost or unrecorded body was re-pinned to the armed body by the existing resume; the resume here takes that pin. Narrow, and pre-existing in what the pin means.
  • ADR-0162's table row citing approval-service.ts#ranArmedBody ("cannot always prove which flow body a run ran ... after an edit of the flow, or the registration a restart makes") is now partly stale: a restart no longer defeats the proof. The declaration is kept so the anchor resolves; the ADR text is left for its owner.
  • Clause-②: the diff adds public members to AutomationEngine (getRunFlowChecksum, getFlowBodyChecksum) and an optional RunRecord.flowChecksum. By the service-automation: a suspended run resumes on the flow version it started on, not on the definition registered under its name #28405 precedent that reads yes (widening); the claim's no is copied as dispatched and flagged in the report.
  • A contract review is owed for the ended sentence in packages/spec/src/contracts/approval-service.ts.

Read first (by risk):

  1. packages/services/service-automation/src/run-flow-checksum.ts: the stamp rules (own run only, null never re-derived, unrecovered resume clears).
  2. packages/services/service-automation/src/suspended-run-store.ts writeTerminal: flow_checksum now written on every terminal row, snapshot pin first.
  3. packages/services/service-automation/src/run-resume.ts at the segment context: resumeRunFlowChecksum.

Two-minute check: pnpm --filter @objectstack/plugin-approvals exec vitest run src/flow-route.integration.test.ts shows the describe "the approval-ended witness is the content of the body the run ran" with 5 passing tests.

Verification

All readings on head b21c5e1 (after merging origin/main 440574f once).

Builds and typecheck
  • pnpm --filter '@objectstack/plugin-approvals...' build --concurrency=2 under the verify lock: VERDICT command-exit 0.
  • pnpm --filter @objectstack/spec check:generated: "All 14 generated artifacts are up to date".
  • pnpm --filter @objectstack/service-automation typecheck and pnpm --filter @objectstack/plugin-approvals typecheck: VERDICT command-exit 0, both test layers OK.
Tests
  • @objectstack/plugin-approvals vitest: Test Files 142 passed (142), Tests 2255 passed (2255).
  • @objectstack/service-automation vitest: Test Files 301 passed (301), Tests 4467 passed (4467).
Derived gates
  • dispatch-gates --ran: 99 derived, 99 run, reconciled.
  • 95 exit 0. Not measured locally (CI owns): check:dual-build-cjs-loads and check:i18n (exit 3, PREREQUISITE NOT MET: need the full build), check:query-options-erasure and check:type-check-debt (timed out at 200 s on the shared box).
  • Re-run on the final head: check:adr-symbol-anchors, check:durability-log-level, check:startup-registry-verdict, check:nul-bytes, check:issue-citations, check:doc-authoring, the three changeset gates, check:closing-keyword-parity, check:cross-package-test-inputs, check:test-source-alias, check:engine-double-contract, all exit 0; check-platform-checklist --changed-from origin/main: OK, 44 anchors judged, 0 lost.
  • node scripts/pm/overlap-check.mjs: VERDICT clean (origin/main and docs(spec): screen-input refusal fields carry one entry per finding #38814 merge cleanly).

Generated by Claude Code

Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2
Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2
Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2
Co-authored-by: Claude <noreply@anthropic.com>
…proval-ended-durable-witness

# Conflicts:
#	packages/plugins/plugin-approvals/src/approval-service.ts
@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 3 package(s): @objectstack/plugin-approvals, @objectstack/service-automation, @objectstack/spec, touching 37 documentable anchor(s).

10 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/actions-as-tools.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp), /api/v1/automation/:name/runs/:runId (route, bridged from symbol runId — its route source's handler names it))
  • content/docs/api/client-sdk.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp))
  • content/docs/automation/approvals.mdx (via ApprovalService (symbol, a top-level class), flow_route (symbol, a field of interface ApprovalRequestRow), runId (symbol, a field of interface RunFlowChecksumStamp), completed_at (literal, a string literal in flowRoute), /api/v1/automation/:name/runs/:runId (route, bridged from symbol runId — its route source's handler names it))
  • content/docs/automation/flows.mdx (via ApprovalService (symbol, a top-level class), runId (symbol, a field of interface RunFlowChecksumStamp), /api/v1/automation/:name/runs/:runId (route, bridged from symbol runId — its route source's handler names it))
  • content/docs/automation/jobs.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp), completed_at (literal, a string literal in flowRoute))
  • content/docs/kernel/cluster.mdx (via AutomationEngine (symbol, a top-level class))
  • content/docs/protocol/objectql/query-syntax.mdx (via completed_at (literal, a string literal in flowRoute))
  • content/docs/ui/actions.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp))
  • content/docs/ui/dashboards.mdx (via completed_at (literal, a string literal in flowRoute))
  • content/docs/ui/views.mdx (via completed_at (literal, a string literal in flowRoute))

⛔ 7 release-owned page(s) also name something this change touched. These are read-only:

  • content/docs/releases/v16.mdx (via AutomationEngine (symbol, a top-level class))
  • content/docs/releases/v17/17-0.mdx (via AutomationEngine (symbol, a top-level class), runId (symbol, a field of interface RunFlowChecksumStamp))
  • content/docs/releases/v17/17-1.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp), /api/v1/automation/:name/runs/:runId (route, bridged from symbol runId — its route source's handler names it))
  • content/docs/releases/v17/17-3.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp))
  • content/docs/releases/v17/17-6.mdx (via ApprovalService (symbol, a top-level class), AutomationEngine (symbol, a top-level class), runId (symbol, a field of interface RunFlowChecksumStamp), /api/v1/automation/:name/runs/:runId (route, bridged from symbol runId — its route source's handler names it))
  • content/docs/releases/v17/17-7.mdx (via runId (symbol, a field of interface RunFlowChecksumStamp), /api/v1/automation/:name/runs/:runId (route, bridged from symbol runId — its route source's handler names it))
  • content/docs/releases/v18/18-1.mdx (via ApprovalService (symbol, a top-level class))

content/docs/releases/ is RELEASE-OWNED (AGENTS.md "Documentation Guardrails"): release
notes are written centrally at release time, and a code PR that edits them is the exact PR
that guardrail exists to stop. They are still audited — read-only. If one of them is actually
wrong, file an issue or open a dedicated docs-only PR; do not edit it here.

What this run could not see
  • 1 anchor(s) matched too much of the corpus to be a work list: created_at (literal, 49 pages)
  • 2 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 182 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 7625001f9b7918edb08d6413bc24026d692f6e94 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 718955dcdd7303601d8595da76ab02be566286ba — the merge of head e8c5a1ebb8598b9ff46fa84c0f1322d4d0b6bef3 into base 7625001f9b7918edb08d6413bc24026d692f6e94, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 718955dcdd7303601d8595da76ab02be566286ba && git checkout 718955dcdd7303601d8595da76ab02be566286ba
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 7625001f9b7918edb08d6413bc24026d692f6e94 e8c5a1ebb8598b9ff46fa84c0f1322d4d0b6bef3 && git checkout -B drift-repro 7625001f9b7918edb08d6413bc24026d692f6e94 && git merge --no-ff e8c5a1ebb8598b9ff46fa84c0f1322d4d0b6bef3

node scripts/docs-audit/affected-docs.mjs --json 7625001f9b7918edb08d6413bc24026d692f6e94

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 7625001f9b7918edb08d6413bc24026d692f6e94 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 7cd28d224e8cdcee4f3562ca0576dce328482fe3
Local-runs: none
Scope: packages/spec/src/contracts/approval-service.ts + packages/plugins/plugin-approvals/src/run-body-witness.ts, packages/plugins/plugin-approvals/src/approval-service.ts, packages/services/service-automation/src/run-flow-checksum.ts, packages/services/service-automation/src/engine.ts, packages/services/service-automation/src/dag-traversal.ts, packages/services/service-automation/src/run-history.ts, packages/services/service-automation/src/run-resume.ts, packages/services/service-automation/src/suspended-run-store.ts, packages/services/service-automation/src/sys-automation-run.object.ts, packages/plugins/plugin-approvals/src/flow-route.integration.test.ts, packages/plugins/plugin-approvals/src/approval-route.test.ts, packages/services/service-automation/src/flow-version-pinning.test.ts, packages/services/service-automation/src/suspended-run-store.test.ts, .changeset/37218-approval-ended-durable-witness.md

Read: card #37218 and its thread (claim 7297251064, report 7299073795), the PR body, and the diff of the head against merge-base 440574f (15 files). Nothing was built or run. All line numbers are at the head.

① Derived judgments

The sentence under review is ApprovalRequestRow.flow_route.outcome.ended, packages/spec/src/contracts/approval-service.ts:408-429. It says ended: true is served only when the run's durable record names the checksum of the body it ran and the armed body has the same checksum, and it lists what answers false.

Holds against the code:

  • The witness. run-body-witness.ts:44-60 answers true only for ran === armed, with armed a non-empty string (:54). A missing reader, an unhashed body, an absent run checksum and a throwing read all answer false. approval-service.ts:14963 asks it only after a terminal run status, and :14943-14944 only for a decided request of a root run whose armed body hosts no child run.
  • Restart. A new engine has an empty ring, so getRunFlowChecksum (run-flow-checksum.ts:144-155) reads loadTerminal, and the row carries the checksum (suspended-run-store.ts:817, :937). Pinned by flow-route.integration.test.ts "a run, then a restart that registers the same body again"; on the old witness the body is registered after the run started, so the pin is red there.
  • An identical body registered again. The checksum is hashSpec(definition, 'flow') over the body as handed to registerFlow (engine.ts:5849, flow-identity.ts), so equal content gives an equal checksum. Pinned ("the same content registered again in the same process").
  • N7 (a), rollback undone. rollbackFlow re-arms the history's own object, whose checksum is its own; the run stamped the body it started on (engine.ts:8534). The two differ, so no ended. The pin asserts the whole flow_route with no outcome, and its 5 ms wait puts every registration strictly before the run start, so the old witness answers true there and the pin is red on it.
  • N7 (b), two replicas. The reader's armed body is the edit, the row names the older body, so no ended. Pinned with a control (same body on both replicas serves it).
  • A run that never paused records none: the execute-path recordLog calls pass the caller's context (engine.ts:8697-8710, :8904-8916), which carries no stamp for this run id (run-flow-checksum.ts:56-61). No request is affected: the approval node either opens a request and suspends, or auto-approves and opens none (approval-node.ts:266-280, approval-service.ts:7885-7891).
  • An unrecovered pin whose run then finishes without a strand records none: the segment context is stamped null (run-flow-checksum.ts:92-96, called at run-resume.ts:2019-2027), null is never re-derived on a later resume (:97), and the record field is undefined (:113-114). Pinned over the in-memory store.
  • A run that finished before the release has a NULL column and answers false, as the sentence says.

Does not hold (F1, must-fix): a stranded run's row answers the snapshot's pin as the run's identity.

  • writeTerminal writes flow_checksum: snapshot.flow_checksum ?? record.flowChecksum ?? null (suspended-run-store.ts:817), and deserializeTerminal reads that one column back as RunRecord.flowChecksum (:937). The column now carries two different facts: the pin a restore re-arms the pause on, and the body the run ran.
  • They differ exactly in the case the sentence names. Path: a run parks on body A; A is lost (a code-loaded flow upgraded under the run); the resume is unrecovered (run-resume.ts:1010-1014) and its context is stamped null; on body B the run parks again, and the suspension is re-pinned to B (run-resume.ts:2266) while the context keeps the null stamp; the next resume fails at a node, so the terminal record is written with consumed.run (run-resume.ts:2383). The record's flowChecksum is undefined, the snapshot's is B, and the row stores B.
  • In the process that ran it, the ring's side map holds nothing (engine.ts:10893-10895), so no ended. After a restart, on another replica, or once the ring evicts the entry, loadTerminal answers B, B equals the armed body, failed is a terminal status (approval-service.ts:833), and the last decided request reads ended: true. The run ran A, then B.
  • The sentence says such a run "recorded no checksum (... or resumed on another body when the one it started on could no longer be found)" and answers false. The changeset says the same ("records none"). The object store contradicts both, and the answer appears at a restart, which is the class of defect this card is about. InMemorySuspendedRunStore keeps the record whole and answers none, so the two stores disagree.
  • Variant: a strand in the first segment after the unrecovered resume stores A, the lost pin. It serves ended: true wherever A is armed again (a package rolled back, or a replica still on the old package), for a run whose last segment ran B.
  • No pin covers it. suspended-run-store.test.ts "a strand's row keeps its snapshot's pin" asserts the column and the snapshot, never loadTerminal(...).flowChecksum. flow-version-pinning.test.ts "a run whose pinned body was lost" uses the in-memory store and a resume that completes.

② Semver level

  • patch is right for all three packages. AGENTS.md Post-Task step 3: the level follows the metadata-protocol kind alone, Metadata-protocol: none takes patch, and a non-protocol widening ships patch. No authorable key, value or type changes, so none is right.
  • The changeset names every published package whose shipped surface moves: @objectstack/spec (the jsdoc ships in the declaration file), @objectstack/service-automation (two public engine methods, optional RunRecord.flowChecksum, and flow_checksum now written on terminal rows), @objectstack/plugin-approvals (the witness). Both declaration lines are line-initial in the PR body and the changeset, and they agree with the claim as amended.
  • The widening is needed. No existing seam serves the consumer: flowChecksumOf is private; the plugin cannot hash the body itself, because the checksum is over the body as handed to registerFlow and the plugin holds the parsed one; getRun answers an entry the run-detail route serves verbatim, so putting the checksum there would change a served payload; reading sys_automation_run from the plugin would cross the owning service. Both methods have their first consumer in this diff. They stay engine-local and off IAutomationService, as getFlowVersionHistory and getFlowSlot are.
  • One part goes past the first consumer: the paused-row arm of getRunFlowChecksum (F2 below).
  • Nit: the Clause-② line names the engine widening only. The plugin's exported ApprovalResumeSurface (index.ts:22) also drops the optional getFlowVersionHistory and gains the two optional reads (approval-service.ts:351-352). No engine and no structural provider breaks; only an object literal typed as the interface that still lists the dropped member would. The changeset body does say the plugin no longer reads it.

③ Boundary flags

  • Author: the PR's user.login is objectstack-fleet[bot].
  • Open question 1 (Clause-② line): closed. The PR body and the changeset read yes (widening) at this head; the claim was amended to match.
  • Open question 2 (file surface): the amended claim lists the service-automation files. The premise is right: at the merge-base serializeConsumedSuspension(undefined) wrote flow_checksum: null on every terminal row without a snapshot (suspended-run-store.ts:1085-1099), so a read-side accessor alone had nothing to read. Whether to split the PR is the seat's call.
  • $flowChecksum on the run context: no new exposure. It rides where $rootRun rides. seedRunVariables runs before the stamp and copies only the record, previous and declared variables (dag-traversal.ts:1311-1337), so it reaches no flow variable or CEL scope. The ring entry is left untouched (the checksum sits in a side WeakMap, engine.ts:3339), and runRecordToLogEntry copies fields by name, so the run-detail payload is unchanged. A caller cannot forge it: a starting run overwrites the key (engine.ts:8534, dag-traversal.ts:1445) and a stamp is read only for its own run id (pinned by "a context that carries another run's stamp").
  • sys_automation_run: no schema change. The diff to sys-automation-run.object.ts is comment-only; the column exists since service-automation: a suspended run resumes on the flow version it started on, not on the definition registered under its name #28405. The row behaviour change is that flow_checksum is now written on terminal rows.
  • Security: no permission, sharing, credential or authentication behaviour is touched. The Audience paragraph of the contract is unchanged, and ended discloses nothing new.
  • SQL push-down: no new id materialisation or in-app join. The read adds one keyed row read per single-request get.
  • Dev flag, ADR-0162: handled correctly. The ADR is not edited, and a private delegating ranArmedBody (approval-service.ts:14976) keeps the anchor resolving. The stale words are in two places, not one: the table row (ADR-0162 line 742) and the Decision prose (line 277, "after an edit of the flow or a restart it cannot prove which body the run ran"). The decision it supports still stands, since an edit still defeats the proof. The report says "noted, not filed"; the seat owes the follow-up card to the ADR owner and should name both lines.
  • Dev flag, gates not measured locally (check:dual-build-cjs-loads, check:i18n, check:query-options-erasure, check:type-check-debt): CI owns them. At review time the head's check-runs were incomplete: Check Changeset, Governed Surface Queue Guard, PR-body guards, ESLint, source-gate typecheck and query-options erasure were green; Build Core, Test Core 1 to 12, the workspace and consumer typechecks and four lint groups were still running. The PR is a draft.
  • Outside the L2 faces, for the seat's ACCEPT: content/docs/automation/approvals.mdx:1270-1273 still teaches the old witness ("known only while the flow has not been registered again since the run started: after an edit, a rollback or a restart ... not served ended"). After this PR a restart and a same-content registration keep the line. The docs-drift check flagged the page.

④ Design judgment

packages/spec/src/contracts/approval-service.ts: the sentence is the right contract. It names content identity, says what keeps and what loses the answer, and stays fail-closed. It is exact against the code except for F1. First consumer: the approvals get in the same diff.

run-flow-checksum.ts, the producer: the stamp rules are sound and small. A stamp names its run, so a child never inherits its parent's; null is a recorded "no single body" and is never re-derived; the stamp sites match the two stampRootRun sites. cancelRun, settleUnresumableSuspension and failSuspendedRun pass the parked context, so a run that ends where it waited still records its body.

run-body-witness.ts, the plugin witness: correct and minimal. Dropping the registration-time check rather than keeping it as a fast path is right, since its only extra answers were the N7 cases.

Pins: the plugin pins assert the substance (whole flow_route objects, with controls) and each would be red on the old witness for the reason given in ①. The engine pins assert the record field and the two reads. Gap: every "durable" integration pin runs over InMemorySuspendedRunStore, which stores the record object whole, so none of them crosses the column where F1 lives.

Findings:

  • F1, must-fix. A terminal row that carries a consumed snapshot answers the snapshot's pin as RunRecord.flowChecksum (suspended-run-store.ts:817 and :937), so a run that resumed on another body after its pinned body was lost, and then stranded, serves ended: true after a restart. Detail in ①. To close: the pin and the run's identity must not be read from one value when they differ. Either a row with a consumed snapshot answers no run identity (fail-closed; then the sentence and the changeset say a stranded run is never served ended), or the two are carried apart so the row answers what the record carried. Pins owed: an object-store pin where the record carries no checksum and the snapshot is pinned, asserting loadTerminal(...).flowChecksum is undefined; and an engine pin for lost body, second pause, failed resume, read from a second engine over a store that goes through the column.
  • F2, should-fix. getRunFlowChecksum falls through to the paused row and answers the suspension's pin (run-flow-checksum.ts:154). Its doc says "the body the run ran" and "undefined when the run recorded none". For the same unrecovered run parked again, that pin is B while its stamp is null. For any run at its first pause the answer also depends on where it is asked: none in the process that parked it (the ring entry was recorded with the caller's context, engine.ts:8840-8851), the pin after a restart. The plugin never reaches this arm, because it asks only after a terminal status. Drop the arm, or read the stamp off the parked context.
  • F3, should-fix. The N2 pin does not show the sibling case unreachable. It pins that an approval inside a parallel, loop or try_catch region is refused at parse, and the attachFlowRoute docblock (approval-service.ts:14909-14915) concludes that a run opens its requests one at a time. A node with two unconditional out-edges is not a region and parses; the engine runs those targets under Promise.all (dag-traversal.ts:845-852), and nothing refuses a suspension there. With two approval steps as targets, what stands between the flow and two pending requests of one run is the find-then-insert guard "one pending request per (object, record)" (approval-service.ts:7733-7740), which is not atomic and is not what the pin or the docblock cites. Not run here; read only. To close the card's third Done-when: pin that structure (at most one request of the run is ever pending), or measure "later" from the decision.
  • Nit. The contract's gloss on "recorded no checksum" lists two causes. The code has two more: a body that could not be hashed (run-flow-checksum.ts:69), and a run parked before the stamp whose suspension pinned none (:98). false is right in all of them.
  • Nit, accepted deviation. A run parked before the release that had already resumed once on a lost or unpinned body carries the later body's pin, and the resume takes it (the PR's "Residual"). The information is gone from those rows; the fail-closed alternative would cost every run in flight over the upgrade its line. One-time and stated in the PR body.
  • Nit. The docs paragraph and the two ADR-0162 lines in ③. The docs page can be corrected in the delta this FAIL already owes; the ADR needs its owner.
  • Nit. The Clause-② wording in ②.

To fix before a PASS: F1 (must-fix), then F2 and F3 (should-fix). The nits do not block.

Implemented-by: claude/issue-37218-approval-ended-durable-witness
Reviewed-by: session_01QSeKYnrQ7UMtHofKQVjcH2

VERDICT: FAIL

…answers finished runs only

Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2
Co-authored-by: Claude <noreply@anthropic.com>
…the contract and the changeset

Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: e8c5a1ebb8598b9ff46fa84c0f1322d4d0b6bef3
Local-runs: none
Scope: packages/spec/src/contracts/approval-service.ts + packages/plugins/plugin-approvals/src/approval-route.ts, packages/plugins/plugin-approvals/src/approval-service.ts, packages/services/service-automation/src/run-flow-checksum.ts, packages/services/service-automation/src/engine.ts, packages/services/service-automation/src/suspended-run-store.ts, packages/plugins/plugin-approvals/src/approval-route.test.ts, packages/plugins/plugin-approvals/src/flow-route.integration.test.ts, packages/services/service-automation/src/suspended-run-store.test.ts, .changeset/37218-approval-ended-durable-witness.md, content/docs/automation/approvals.mdx

Delta read of the patch round against FAIL 7299347767 on 7cd28d2: the diff of 7cd28d2 to this head (11 files, two commits), the patch-round report 7299896145, and the code the delta cites, re-read at this head. Nothing was built or run. The parts of the first record the delta does not touch stand as written there.

① Derived judgments

F1 is closed. A strand records no run identity, on both stores.

  • The producer: runRecordFlowChecksum answers none for any record that carries a consumed suspension (run-flow-checksum.ts:116), so the in-memory store and the ring hold none for a strand.
  • The object store: the write is unchanged (flow_checksum: snapshot.flow_checksum ?? record.flowChecksum ?? null, suspended-run-store.ts:818), so the column still carries the pause's pin. The read no longer answers it as the run's identity: readTerminalFlowChecksum (:1179) returns none when variables_json is set, the same discriminator deserializeConsumedSuspension keys on (:1218). A dropped snapshot leaves its notice in variables_json, so it reads none too.
  • The strand-restore path still works. The snapshot is rebuilt with flowChecksum: readFlowChecksum(row) (:1229), untouched by the delta, so a restore re-arms the pause on its pin. The store pin asserts both halves on one row: consumedSuspension.flowChecksum is the pin and flowChecksum is undefined.
  • A restored strand that then finishes writes a record with no snapshot. The upsert clears variables_json, and the column becomes the record's own checksum. That is the body the restored run ran from its pause; the failed segment is discarded by the restore itself.
  • The path I named is pinned end to end over the persistent store (suspended-run-store.test.ts:1820): park on A, a second engine holding only B resumes unrecovered and parks again pinned to B, the next resume throws, the row's column is B, and a third engine holding B reads getRunFlowChecksum as undefined. The report's ablation shows it red on the 7cd28d2 store.
  • The sentence now lists the strand among the causes of no checksum (spec approval-service.ts:428-432), and the changeset and the guide list the same five.

F2 is closed. getRunFlowChecksum answers finished runs only: the newest ring entry, else loadTerminal, and nothing from the paused row (run-flow-checksum.ts:153-159). The ring side map is set only for terminal entries (engine.ts:10899), so a parked run answers none in the process that parked it and after a restart alike. The engine jsdoc and the changeset say "finished run".

F3 is closed by the card's other arm. The dev measured the sibling reachable (a node with two unconditional out-edges to two approval steps opens two pending requests in one run), so the parse-refusal pin was withdrawn and routeOutcome measures "later" from the decision: completed_at, compared against the other rows' created_at (approval-route.ts:184, :191).

  • It is right for a decided request. The run is parked at a request until it is decided, so every step the approval went on to opens after that decision; a request opened before it is a sibling. Both stamps come from the service's own clock as ISO strings and both columns are Field.datetime, so the string comparison holds.
  • Every write that makes a request not pending stamps completed_at (approval-service.ts:7209-7210, :8847, :9662, :10033-10036, :10295, :10348, :12645), and routeOutcome is called only for a row that is not pending. So a row this service decided always has a decision time.
  • It is not fail-closed for a row with none: it falls back to created_at, the reading before this delta, and a pin says so ("as before"). No write path in this tree produces such a row. See the nit in ④.
  • The contract sentence for step now says "opened after this one was decided" and names the fan-out sibling (spec approval-service.ts:399-402). It matches the code.

② Semver level

  • Still patch on the three packages, for the reason in the first record: Metadata-protocol: none, and a non-protocol change ships patch.
  • New on a published surface in this delta: only text in packages/spec (the step sentence and the longer gloss on "recorded no checksum"). No type changes. The served flow_route.outcome.step changes in one case, the fan-out sibling, and the changeset says so.
  • getRunFlowChecksum is smaller than at 7cd28d2 (no paused-row arm). It has never been released, so this is not a narrowing.
  • routeOutcome and flowRoute gained completed_at in their parameter types. Neither is exported from the plugin's entry (index.ts names nothing from approval-route.ts), and the key is optional on ApprovalRequestRow.
  • The Clause-② line now names the ApprovalResumeSurface change, identically in the changeset and the PR body. Closes that nit.

③ Boundary flags

  • Author: the PR's user.login is objectstack-fleet[bot].
  • Open questions in report 7299896145: none.
  • Out-of-scope finding, fan-out (class a, public door): a node with two unconditional out-edges to two approval steps opens two pending requests on one record. Only the first holds the run's suspension; the second is pending with nothing under it, and the find-then-insert guard at approval-service.ts:7733-7740 did not stop it. This is a defect of its own, outside this card. The seat owes the card. Note for it: the integration pin at flow-route.integration.test.ts:701 asserts that both requests open, so the fix for that defect will have to rework this pin.
  • Out-of-scope finding, ADR-0162: the report now names both stale places (the prose near line 277 and the table row near line 742). The ADR is not edited. The seat owes the follow-up to its owner.
  • Docs: content/docs/automation/approvals.mdx now teaches the content witness, the five causes and the decision-time later step. Closes the note I left for the seat.
  • No new exposure, no schema change to sys_automation_run, no security behaviour touched. SQL push-down: the delta adds no read; completed_at is on the row already held.
  • Check-runs on this head at review time: every completed run is green, including Build Core, Check Changeset, Governed Surface Queue Guard, PR-body guards, the lint groups, source, consumer and debt typechecks, and Test Core 3 to 12. Still running: Test Core 1 and 2, the workspace typecheck, Type Check UI and several Test UI shards. The PR is a draft. The all-green check before landing is the seat's.

④ Design judgment

packages/spec/src/contracts/approval-service.ts: both sentences hold against the code at this head. ended is fail-closed in every case the first record listed, and now for a strand. step says what routeOutcome computes.

suspended-run-store.ts and run-flow-checksum.ts: the fix is the smaller of the two closings I offered and it is the right one. A run that can still be restored has not stopped for good, so answering none is true to the sentence, not only safe. The producer and the reader each enforce it, so a store that keeps the record whole and one that goes through the column agree.

approval-route.ts: one line of logic, with the reason in the docblock. The unit pins cover the sibling, a request opened after the decision, and the fallback. The integration pin measures the fan-out on the real engine before it asserts the route.

Findings, all nits:

  • Nit. Tie-break. A request stamped in the same millisecond as the decision is dropped (the comparison at approval-route.ts:191 skips a row created at or before the decision time). The gap is now machine time: the decision stamp is taken at the start of the decide call and the next step's request is stamped after the resume. A sibling cannot tie (it opens with the request, before any decision of it), so a tie can only be a real later step, and dropping it would leave the decided request reading "ended here" once the run ends. It needs the whole decide, resume and open chain inside one millisecond on one clock, which a store with real I/O does not do; an in-memory driver might. Skipping only rows created strictly before the decision would remove it. Follow-up card, not this PR.
  • Nit. The fallback for a row with no decision time reads from the opening, so on such a row a sibling would again be served as the later step. The contract sentence does not mention the fallback. No write path here produces the row; the fail-closed answer would be no outcome.
  • Nit. The gloss "failed after a resume and can still be restored" is narrower than the code. A record carrying a consumed suspension also covers an ancestor failed where it waited because a descendant stranded (run-resume.ts:933-958), and a strand whose snapshot was over the row budget. false is right for all of them.
  • Nit, carried. The pre-release residual from the first record (a run parked before the release that had already resumed once on a lost body takes its later pin) is unchanged and stated in the PR body.

F1, F2 and F3 are closed. Nothing at must-fix or should-fix is open.

Implemented-by: claude/issue-37218-approval-ended-durable-witness
Reviewed-by: session_01QSeKYnrQ7UMtHofKQVjcH2

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

L1 ACCEPT · PR #38825 (#37218) · head e8c5a1ebb8598b9ff46fa84c0f1322d4d0b6bef3 · read 2026-12-01T03:49Z

席位核对

  1. Shape. Draft, base main, Fixes #37218 first after the seat signature; no keyword binds another card. All three Done-when rows are delivered (durable witness, N7 a/b, N2 by the card's decision-time arm), so Fixes is right.
  2. Premise measured. The dispatch's hypothesis was half wrong: a finished run's terminal sys_automation_run row wrote flow_checksum NULL, so the durable identity had to be produced in service-automation (run-flow-checksum.ts), not only read. F3 was measured REACHABLE (two unconditional out-edges to two approval steps open two pending requests), so N2 took the card's other arm.
  3. Gates (check-runs at this head). 64 success · 14 expected skip · 0 failed · 0 pending; Lint & Repo Gates and TypeScript Type Check success. L2 at CONTRACT_REVIEW_TIER: FAIL 7299347767 on 7cd28d22 (F1 must-fix, F2/F3 should-fix) → delta PASS 7300022646 on this head. Suites: plugin-approvals 2256/2256, service-automation 4468/4468; ablations red on the prior head for F1 (2 failed) and N2 (3 failed).
  4. Accepted deviations. (a) Clause-② corrected from no to yes (widening …) and the claim's file surface widened to the producer files, both in place on claim 7297251064 (the seat's error at claim time; precedent service-automation: a suspended run resumes on the flow version it started on, not on the definition registered under its name #28405). (b) L2 nits — same-millisecond tie-break and the narrow no-checksum gloss — accepted here and carried by approvals: flow_route later-step comparison drops a request stamped in the same millisecond as the decision, and the no-checksum gloss names fewer causes than the code #38839 (Blocked-by: #38825). (c) Commit d8d8296c carries both the F1/F2 and the N2 code under one message.
  5. Out of scope. The fan-out defect the dev measured (two pending requests, the second with no suspension) is pre-existing on main and filed as approvals: a node fanning out to two approval steps opens two pending requests in one run, and the second has no suspension, so deciding it never moves the run #38838; the integration pin [N2] a node fanning out … here records today's behaviour, and approvals: a node fanning out to two approval steps opens two pending requests in one run, and the second has no suspension, so deciding it never moves the run #38838 notes that its fix flips it (7300035661). carrier: ADR-0162 is stale in two places (~line 277 and the table row ~742: "a restart defeats the proof"); governed text, not edited here — after merge the landing seat adds a row to the open "ADR revisions, week of …" card. content/docs/automation/approvals.mdx is rewritten in this PR, so the docs-drift list's other pages name only generic anchors (runId, completed_at). Skills-docs: not owed.
  6. Landing. Not governed (check-governed-merges --pr 38825: 0 of 17 paths, +860/-74, under 3000). K = 0. git merge-tree against main 7625001 clean; no merge=os-regen path in the diff. 拆分 service-automation engine.ts(12,298 行)为职责模块,只搬不改 #38667 (the engine.ts split) is pm:blocked on this PR and unlocks when it merges. Ready + auto-merge now.

Clause-②: yes (widening …) · Metadata-protocol: none

@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-37218-approval-ended-durable-witness branch December 1, 2026 04:18
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…acade over eight facet modules (steps 2 and 3 of the engine split) (objectstack-ai#38889)

repo:objectstack@os-justin · os-justin ·
session_01QSeKYnrQ7UMtHofKQVjcH2

Fixes objectstack-ai#38667

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户无感:自动化引擎的主类按职责拆成八个文件,类本身只留下各方法的签名和一行转发,流程运行、恢复、注册的行为都不变。
-
属于自动化引擎拆分(大文件计划第四张卡)的第二、三步:第一步已合并;这一步之后,后续自动化相关的卡可以各改各的文件,并且有门禁防止主类重新长回去。
- 若拆分有误,会表现为自动化流程注册或运行出错;这次只搬代码,整体撤回这次合并即可恢复原状。
- 改动超过三千行,需要你批准后才能合并。

## What changes

Steps 2 and 3 of the card, on top of step 1 (objectstack-ai#38846, merged). Per the
maintainer's ruling on this card (7305055957: 「A: keep the facade
(Recommended)」), the 2,000-line target is dropped and the facade form
holds.

`AutomationEngine` in
`packages/services/service-automation/src/engine.ts` becomes a
delegating facade: the bodies of **145 members** move into static
methods of eight facet classes, each body exactly as it stood (not
re-indented, not formatted, not edited), with a `this` parameter added
where the body reads the engine. Every member stays on the class with
its signature and (when public) its docblock as a one-call stub, `return
XFacet.m.call(xHost.of(this), …)`, so the published declaration, an
instance spy and a subclass override are what they were. A private
member's docblock moved with its body. The engine's state (all 74
fields) stays on the class. `engine.ts` goes from **9,813 to 7,735
lines**.

The shape is the objectql `registry.ts` split's: each facet module
declares the `AutomationEngine` members its bodies read as an interface
typed by indexed access on the class (`AutomationEngine['x']`), so a
member renamed or retyped on the class is a compile error in the facet;
each method's `this` is the `Pick` of that interface it reads.
`engine-facet-hosts.ts` holds one host per facet per engine (a
`WeakMap`, built on first use), filled by the factory the class's one
static block installs: a method goes as a closure that calls it on the
engine at call time, a field as a getter, and the five fields a body
assigns (`nodeTypeVocabularySealed`, `packagedFlowSource`,
`packagedFlowDefaults`, `packagedFlowDefaultSource`,
`flowCredentialSource`) also with a setter. Facet modules import
`engine.ts` for types only, so there is no evaluation cycle; `index.ts`
re-exports nothing from them.

### Every moved member and its new file

`*` marks a public member (its docblock stays on the class); every other
member is private and its docblock moved with its body. "Host" is the
number of engine members the facet's bodies read.

| New module | Lines | Members | Host | Members moved |
|---|---|---|---|---|
| `engine-dispatch-facet.ts` | 157 | 5 | 9 | `readScheduledWorkPolicy`,
`slotKeyedRunStore`, `missedRunLimit`*, `recordMissedRun`*,
`noteRunStarted` |
| `engine-extensions-facet.ts` | 686 | 26 | 37 |
`resolveTriggerBinding`, `activateFlowTrigger`, `triggerRun`,
`deactivateFlowTrigger`, `getActiveTriggerBindings`*,
`assertSameOriginOrFree`, `connectorInstance`,
`resolveConnectorAction`*, `resolveConnectorActionInputSchema`*,
`resolveConnectorActionEffect`*, `organizationLocale`*,
`getConnectorOrigin`*, `getConnectorDegradedReason`*,
`getConnectorDegradedHold`*, `registerConnectorProvider`*,
`unregisterConnectorProvider`*, `getRegisteredConnectorProviders`*,
`getConnectorDescriptors`*, `getRegisteredNodeTypes`*,
`getActionDescriptors`*, `getRegisteredTriggerTypes`*, `knownNodeTypes`,
`getUnknownNodeTypeAudit`*, `sealNodeTypeVocabulary`*,
`getSealedNodeTypeVocabulary`*, `warnUnknownNodeTypes` |
| `engine-flow-slots-facet.ts` | 814 | 41 | 55 | `flowArmHolder`,
`loaderOwnerOf`, `placeFlowSlot`, `bindPackagelessActivation`,
`flowActivationBinds`*, `moveFlowRecords`, `flowKeyNow`,
`sharedFlowNameRefusal`, `resolveFlowKey`, `bareFlowKey`,
`servedBareFlowKey`, `isDisabledHolderSlot`, `isDisabledSoleHolder`,
`flowSlotPackage`, `flowSlotName`, `flowSlotKeysOf`,
`loneSharedFlowKey`, `settleFlowName`, `isSharedFlowKey`,
`executeSlot`*, `setPackagedFlowSource`*,
`setPackagedFlowDefaultSource`*, `packagedFlowOwner`*,
`inboundHookSlot`*, `disabledHolderHookRefused`,
`packagedFlowSlotOwner`*, `isPackagedFlow`,
`refuseUnpackagedDefaultActive`, `isShippedFlowName`,
`packagedFlowDefault`, `refreshPackagedFlowDefaults`*,
`flowNameRefusal`, `connectorNameRefusal`*,
`resolveConnectorInstanceFor`*, `codeRegisteredInstance`,
`flowCallerPackage`*, `armedFlowPackage`*, `flowHolder`*,
`durableFlowHolder`*, `flowHolderPackage`*, `flowDispatchHolder`* |
| `engine-registration-facet.ts` | 585 | 21 | 58 |
`judgeFlowRegistration`, `dryRun`*, `registerFlow`*, `unregisterFlow`*,
`withdrawFlow`*, `withdrawFlowSlot`*, `withdrawFlowKey`,
`recordFlowRefusal`*, `getFlowRegistration`*, `recordFlowShadowing`*,
`getShadowedFlows`*, `listFlows`*, `getFlow`*, `getRunFlow`*,
`flowKeyOfRun`*, `getFlowSlot`*, `getHeldFlow`*, `registrationChecks`,
`validateFlowExpressions`, `getValueType`, `validateNodeInputSchemas` |
| `engine-connector-doors-facet.ts` | 247 | 16 | 9 |
`setFlowCredentialSource`*, `pullConnectorSource`*,
`requireConnectorCredentialDoor`, `attachConnectorCredentialPubSub`*,
`resyncConnectorCredentialPubSub`*, `listConnectorCredentialRefs`*,
`setConnectorCredential`*, `clearConnectorCredential`*,
`requireConnectorConnectionDoor`, `getConnectorConnection`*,
`beginConnectorConnection`*, `completeConnectorConnection`*,
`revokeConnectorConnection`*, `holdsFlowCredential`*,
`resolveFlowCredential`*, `flowCredentialHoldings`* |
| `engine-enablement-facet.ts` | 410 | 12 | 20 | `isFlowEnabled`,
`describeDisabledFlow`, `subflowTargets`, `resolvedFlowCallKey`,
`declineOntoDisabledSubflows`, `declineOntoSuspendingSubflowNotice`,
`declineOntoRegionSuspendingCall`, `declineOntoSubflowRetriedCallout`,
`toggleFlow`*, `toggleFlowSlot`*, `getFlowVersionHistory`*,
`rollbackFlow`* |
| `engine-run-facet.ts` | 1084 | 8 | 35 | `getFlowBodyChecksum`*,
`execute`*, `failRunBeforeFirstNode`, `executeKey`, `runRegion`*,
`retryExecution`, `recordLog`, `compactStepsForHistory` |
| `engine-resume-facet.ts` | 676 | 16 | 20 | `persistSuspendedRun`,
`claimAdvance`, `resolveSuspendedNodeType`,
`resolveDeclaredResumeAuthority`, `resolveSuspensionChainForCancel`,
`hasSuspendedRun`*, `unresumableSuspensionCause`*, `recoverStoredFlow`,
`heldFlowVersion`, `suspendedMapParentOf`*, `suspensionOf`*,
`refuseInvalidScreenInput`, `buildSubflowResumeSignal`,
`bubbleToParent`, `refuseRestore`, `getSuspendedScreen`* |
| `engine-facet-hosts.ts` | 61 | | | the `FacetHost` holder and the
eight host instances |

The cut: **run** (`getFlowBodyChecksum` with the run checksum from
objectstack-ai#38825, `execute`, `executeKey`, `runRegion`, `retryExecution`, the run
log), **resume** (suspension persistence and claims, resume authority,
the suspension chain, screen input, bubbling to the parent, restore
refusals), **registration** (`registerFlow`, judging, withdrawing,
refusals, shadowing, reading flows back, the registration-time checks),
plus **flow slots**, **dispatch**, **extensions** (triggers, connectors,
providers, resolvers, the node-type vocabulary), **connector doors** and
**enablement** (subflow guards, toggles, version history, rollback).
`getRunFlowChecksum` was already a one-call delegation to
`run-flow-checksum.ts` and stays as it was.

**Stay on the class.** All fields; the 127 members that were already
delegations at the base (the objectstack-ai#25222 per-call host stubs and plain
forwards: the facade gate accepts them as they are, and converting them
is not part of this card per the ruling); and seven members with
`exceptions` rows (card objectstack-ai#38667), each with its reason in the registry:
- `constructor`: state-owning, it writes the engine's fields from its
arguments.
- `flowSlots`, `flowLedgerDisabled`, `flowCallKey`: fields whose
initializers hold arrows over the engine's own state; they run at
construction, or are the value itself.
- `resolveCanonicalDescriptor`, `resolveResumeAuthority`,
`walkSuspensionChain`: their bodies read private statics of the class
(`MAX_ALIAS_HOPS`, `RESUME_AUTHORITY_WHEN_UNDECLARED`,
`MAX_SUSPENSION_CHAIN_DEPTH`, `LINKED_RUN_PREFIXES`), which a module
outside the class cannot read.

### The facade gate (ask 3)

`scripts/facade-delegation-registry.json` gains a `facades` row for
`AutomationEngine` (card objectstack-ai#38667), a `ceilings` row for `engine.ts`
(`baseLines` 7735 at `baseCommit` 53e745f, `maxLines` 7835 =
`CEILING_MARGIN` 100, ruling 6897467376) and the seven `exceptions` rows
above. The gate's self-test holds `DECLARED_WATCH_HINTS` equal to the
registry's facade files, so `scripts/check-facade-delegation-only.mjs`
gains the one path string; nothing else in the gate changes.

### Gate citations of the moved code, edited outside the package
(declared)

- `scripts/facade-delegation-registry.json`: the rows above.
- `scripts/check-facade-delegation-only.mjs`: one `DECLARED_WATCH_HINTS`
string.
- `scripts/tenant-audit-census.mjs`: 14 `UNTYPED_RECEIVERS` rows
(`engine: false`), one per facet file and receiver: the engine's own
in-memory `Map`/`Set` fields a facet body calls `.delete(...)` on.
Inside the class the census read the field's type; through
`AutomationEngine['x']` on the host it cannot.
-
`docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-automation.md`:
the shard regenerated by `node scripts/tenant-audit-census.mjs --write`.
Two of those deletes, `this.flowRefusals.delete(name)` and
`this.sharedSlotTriggerWarned.delete(name)` in
`engine-registration-facet.ts`, are now placed as engine writes by the
census's `name: string` parameter rule (they are in-memory map deletes,
not data-engine writes), so the shard counts 42 write sites where it
counted 40. A precision limit of the census through the host, noted
here, not worked around: the bodies are moved unedited.
- `packages/spec/liveness/flow.json` and `connector.json`: 10 citations
re-pointed to the module that now holds the body they name
(`engine-run-facet.ts#retryExecution` and the retry-backoff keys;
`engine-extensions-facet.ts#getConnectorDescriptors`); no verdict
changes. The ledger ships in `@objectstack/spec`, so the changeset names
that package with a `patch` too.

### Net growth past a pure move (package source: 9,813 lines in
`engine.ts` before; 7,735 + 4,659 in the facets + 61 in the hosts module
after, +2,642)

- `engine.ts` (`git diff --numstat`: +469 -2,547): 145 one-line
forwarding calls; the static host block (266 lines); a 12-line import
block for the facets and hosts; the rest are stub signatures re-spelled
(`async` dropped so each stub returns the facet's own promise;
`registrationChecks` and `validateFlowExpressions` take their
destructured option bag as `options` and hand it on). Import specifiers
only the moved bodies read are pruned.
- Each facet: the moved text (the base member from its signature, or its
docblock when private, to its closing brace) plus what is new: header,
imports, host interface, class wrapper, a one-line docblock pointing
each public member's body at the class's docblock, and a `this:` line
where the parameter list is multi-line. The signatures exist on both
sides by design (the class keeps the contract).

| Facet | Lines | Moved base text | New | Public pointers | `this` lines
|
|---|---|---|---|---|---|
| `engine-dispatch-facet.ts` | 157 | 88 | 69 | 2 | 0 |
| `engine-extensions-facet.ts` | 686 | 528 | 158 | 18 | 2 |
| `engine-flow-slots-facet.ts` | 814 | 630 | 184 | 16 | 2 |
| `engine-registration-facet.ts` | 585 | 426 | 159 | 15 | 2 |
| `engine-connector-doors-facet.ts` | 247 | 135 | 112 | 14 | 0 |
| `engine-enablement-facet.ts` | 410 | 318 | 92 | 4 | 0 |
| `engine-run-facet.ts` | 1084 | 968 | 116 | 3 | 3 |
| `engine-resume-facet.ts` | 676 | 551 | 125 | 5 | 5 |

- `engine-facet-hosts.ts`: 61 lines, new.
- No type is re-declared, no name changes, no body is edited.

## Tests

No test file changed.

<details><summary>service-automation typecheck and suite at 91b6bff:
301 files, 4,468 tests pass</summary>

Dependency closure built (`os-verify-lock.sh -c "pnpm --filter
'@objectstack/service-automation^...' build --concurrency=2"`, VERDICT
command-exit 0); `pnpm --filter @objectstack/service-automation
typecheck` (tsc plus `check:test-typecheck`) VERDICT command-exit 0;
`pnpm --filter @objectstack/service-automation exec vitest run
--maxWorkers=2`: `Test Files 301 passed (301)`, `Tests 4468 passed
(4468)`, VERDICT command-exit 0. The same 301 files and 4,468 tests as
`main`. Taken at 91b6bff, whose package source is the head's: the
head's one later commit changes only the registry's `baseCommit`.
</details>

<details><summary>Move verifier: 145 facet methods identical to the base
member</summary>

A throwaway verifier (not committed) parses `engine.ts` at main
(f3f3265) and every facet module, and compares each facet method with
the base member of the same name: body text, parameters (the added
`this` aside), return type, type parameters, `async`, and for a private
member its docblock. `145 facet methods: 145 identical to the base
member (body, parameters, return type, type parameters, async; a private
member's docblock), 0 problem(s)`. Negative control: one token changed
in `engine-run-facet.ts` reds `getFlowBodyChecksum: body`.
</details>

<details><summary>Published declaration, built at main (f3f3265) and at
the head</summary>

`dist/index.d.ts` (and `dist/index.d.cts`, identical to it in both
builds): 156 top-level declarations before and after, none added or
dropped, the export list equal as a set (130 names), each module's
import specifiers equal as sets. 152 declarations byte-identical,
**`AutomationEngine` among them**. The other 4 (`SysAutomationRun`,
`SysSyncRun`, `SysFlowDispatch`, `SysFlowCredential`, Zod-inferred
object shapes) are equal once the order the printer lists a
string-literal union's members in is set aside (`"code" | "secret" |
"user" | "record"` vs `"user" | "secret" | "record" | "code"`: the same
members). Positive controls on copies of the head build: renaming one
`AutomationEngine` member, and changing `getFlowBodyChecksum(flow:
unknown)` to `(flow: string)`, each red `AutomationEngine`.
</details>

<details><summary>Facade gate</summary>

`node scripts/check-facade-delegation-only.mjs`: exit 0,
`AutomationEngine: 351 members — 273 delegations, 71 fields, 7 named
exception(s) (objectstack-ai#38667)`, `engine.ts: 7735 lines, ceiling 7835 (100 left;
ruling 6897467376)`, `8 facade class(es) in 6 file(s) hold delegations
only, 28 named exception(s)`. `--self-test`: 44 cases pass.
</details>

<details><summary>Derived gate families at 8b19bf8</summary>

`node scripts/pm/dispatch-gates.mjs --commands` (no paths; derived from
the tree of objectstack-ai/objectstack at 8b19bf8) named 100 commands;
all 100 were run there, each exit code captured before any pipe, and
`--ran` reconciled the record: `100 derived famil(ies) accounted for —
98 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3)`.

Among the 98 at exit 0: `check:facade-delegation-only` and the gate's
`--self-test`, `check-tenant-audit-census` and its self-test (with the
14 rows and the regenerated shard), `pnpm --filter @objectstack/spec run
check:liveness` (red before the 10 citations were re-pointed, green
after), `check:platform-checklist`, `check:adr-anchors`,
`check:system-context-census`, `check:dispatcher-error-vocabulary`,
`check:pm-dispatch-gates`, `check-plugin-teardown-shape` and its
self-test, and the changeset gates.

NOT MEASURED (each exited 3, prerequisite not met: they read the built
`dist/` of every workspace package, and this container built only this
package's dependency closure; CI runs them):
- `pnpm check:dual-build-cjs-loads`
- `pnpm check:published-readme-exports`

Outside the derived set: `node scripts/check-platform-checklist.mjs
--changed-from origin/main` exit 0 (15 anchors judged, 0 lost).
`scripts/pm/overlap-check.mjs`: merges cleanly into origin/main
3c617a2 (4 commits past this branch's base; they touch spec form/view
conversions and the CLI, none of this PR's files).
</details>

## Acceptance notes

- `engine.ts` is 7,735 lines, not below 2,000: the maintainer ruled the
facade form holds and the 2,000-line target is dropped for this card
(7305055957). What remains is the public docblocks (the published
contract), the 74 documented fields, the stubs, the 127 earlier
delegations with their docblocks, and the host block.
- `plugin.ts` is untouched: no helper of it moves with the engine's.
- The cards that follow on the engine land in the facet of their
concern; the ceiling reds a PR that grows `engine.ts` by more than 100
lines.

## Verification

Read first, by risk:
1. `engine.ts`, the `static` block at the end of the class: every field
a body assigns needs its setter there (five do), or the write lands on
nothing; the eight host interfaces type-check that every member a body
reads is there.
2. `engine-facet-hosts.ts`: the host is built once per engine and
cached, so a body's `this` is the same object across calls.
3. `engine-run-facet.ts` `executeKey`: its one bare `this`
(`startConditionHolds.call(this, …)`) now hands the run host, which
carries `evaluateCondition`, the one member `startConditionHolds` reads.

Two-minute check: `pnpm --filter @objectstack/service-automation test`
(expect 301 files, 4,468 tests passing) and `node
scripts/check-facade-delegation-only.mjs` (expect the `AutomationEngine`
line: 351 members, 273 delegations, 71 fields, 7 named exceptions, and
`engine.ts: 7735 lines, ceiling 7835`).

---
_Generated by [Claude
Code](https://claude.ai/code/session_01QSeKYka8mG8XtvFU8AvP9X)_

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

2 participants