Skip to content

Commit b53e70f

Browse files
feat(showcase): a paid invoice declares closedStates; the three paid-invoice line hooks are removed (ADR-0162 item 3) (#38917)
Fixes #37771 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:示例应用里已付款的发票,普通用户改表头、删整张、改/加/挪/删明细,现在一律被系统拒绝并提示「记录已关闭」;以前表头和明细的大部分字段其实能改,整张也能删。 - 为什么做:单据关闭态锁定的最后一块:用发票上的一行声明替掉示例应用里三段手写的拦截代码,作为平台这项能力的运行证明,也给其他应用一个照抄的样例。 - 出错会怎样:只影响示例应用里已付款的发票;最坏是示例里有人本来想改已付款发票被拦住;去掉这一行声明即可恢复旧行为。 - 要你做什么:无。 ## What changes - `examples/app-showcase/src/data/objects/invoice.object.ts`: the invoice declares `closedStates: { status: ['paid'] }` (ADR-0162 D1). The comments that named the hooks, and the `tax_rate` and line-field comments, now say what the server does. The `readonlyWhen` predicates and the `userActions` gating stay, because the console renders from them. - `examples/app-showcase/src/data/hooks/index.ts`: the three paid-invoice line hooks (`showcase_guard_paid_invoice_line_add` / `_move` / `_remove`), their shared prelude and the three exported sentences (`PAID_INVOICE_LINE_ADD_REFUSAL`, `_REMOVE_`, `_MOVE_`) are deleted. `allHooks` now holds five hooks. - `examples/app-showcase/test/paid-invoice-line-lock.test.ts`: the same harness, now asserting the platform's lock (`code` `RECORD_LOCKED`, `status` 409, `reason` `record_closed` / `master_closed`, `lockReason` `closed_state`) where it asserted the three app sentences. It adds the outcomes that change by design: editing the paid header, deleting the paid invoice, editing a line (both a field with `readonlyWhen` and fields without it). A system write is shown to be unbound. The REVERSE block now drops `closedStates` from the invoice instead of unbinding hooks. Per AGENTS.md, a new pin for a component with a shared harness file goes into that file, so this card adds no new test file. - `examples/app-showcase/test/approval-resume-relation-expand.test.ts` (claim amendment 1): its kernel now registers a minimal `job` service ahead of the approvals plugin. An approval on an object that declares `closedStates` opens only on a host with a job service (ADR-0162 Execution item 8), and without one the invoice sign-off's first request was refused. - Dogfood tests that pinned a caller write on a paid showcase invoice or its lines, each edited only at those pins: - `packages/qa/dogfood/test/invoice-conditional-rules-server.dogfood.test.ts`: a `tax_rate` PATCH on the paid INV-1003 now answers `409 RECORD_LOCKED` instead of 200. The re-read still shows the value unchanged, and the draft control is unchanged. - `packages/qa/dogfood/test/showcase-readonly-when-parent.dogfood.test.ts`: the paid line and paid header PATCHes now answer `409 RECORD_LOCKED`, and the frozen values still survive. A field `readonlyWhen` leaves open no longer lands. The mixed `updateMany` reports the locked row as a `RECORD_LOCKED` failure while the open row lands (now under `continueOnError`). The header comment names where the field-level strip and the dropped-fields header stay pinned. - `packages/qa/dogfood/test/showcase-crud-persona-matrix.dogfood.test.ts`: a comment that named the removed hooks (no behaviour change). - `docs/qa/platform-checklist/areas/records-forms.json`: the item `records-forms.object-hook-lifecycle` (revision 13 to 14, with a history entry) names the five seeded hooks. It also says the showcase seeds no `beforeDelete` hook, and drops the guards from `automated.ref`. No clause changed. - No changeset: `@objectstack/example-showcase` and `@objectstack/dogfood` are private, and nothing else is published (`skip-changeset`). ## Dogfood record The showcase was booted in this container from this worktree: `pnpm --filter @objectstack/example-showcase dev -- --fresh -p 38771`, with a fresh seed each time. BEFORE was taken on `origin/main` `ac97540f75`, AFTER on this branch. The caller is the seeded admin `admin@objectos.ai`, an ordinary user session (`role: user`), not a system context. All writes went over REST at `/api/v1/data/*`. | Write | Before (main) | After (this branch) | |---|---|---| | 1 header PATCH `{region, tax_rate}` on paid INV-1003 | 200; stored: region amer to emea, tax_rate 8 to 8 (stripped) | 409 `RECORD_LOCKED` "Invoice 'INV-1003' is closed, so it and its lines can no longer be changed or deleted"; stored: region amer, tax_rate 8 | | 2 DELETE paid INV-1005 | 200; the row is gone | 409 `RECORD_LOCKED` "Invoice 'INV-1005' is closed, so it and its lines can no longer be changed or deleted"; the row is still there | | 3a line PATCH `{description, position, service_start}` under paid INV-1003 | 200; stored: description to "edited after payment", position 0 to 7, service_start null to 09:30:00 | 409 `RECORD_LOCKED` "This Invoice is closed, so it and its lines can no longer be changed or deleted"; nothing changed | | 3b line PATCH `{quantity, unit_price, description}` under paid INV-1003 | 200; quantity 6 and unit_price 49.99 stripped, description lands | 409 `RECORD_LOCKED` (same sentence); nothing changed | | 4a POST a line under paid INV-1003 | 400 `HOOK_ABORTED` "This invoice is paid, so its lines are locked: a line cannot be added to it." | 409 `RECORD_LOCKED` "This Invoice is closed, so it and its lines can no longer be changed or deleted" | | 4b move a draft line onto paid INV-1003 | 400 `HOOK_ABORTED` "A paid invoice's lines are locked: a line cannot be moved onto or off a paid invoice." | 409 `RECORD_LOCKED` (same sentence) | | 4c move the paid line off INV-1003 | 400 `HOOK_ABORTED` (the move sentence) | 409 `RECORD_LOCKED` (same sentence) | | 4d DELETE the paid line of INV-1003 | 400 `HOOK_ABORTED` "This invoice is paid, so its lines are locked: a line cannot be removed from it." | 409 `RECORD_LOCKED` (same sentence) | | control: draft INV-1004 PATCH `{tax_rate}` | 200 | 200 | After rows 1-4, INV-1003 still totals 299.94 with its one line, both before and after. **Seed:** `Seeds: com.example.showcase 141 rows` on both boots. On the AFTER boot the paid INV-1003 carries its seeded line (total 299.94), so the seed loads finished invoices as a system write, which ADR-0162 D5 leaves unbound. No seed file changed. **Flows, checked in the running app** (the submitter is the seeded persona `phone.demo@example.com` holding `showcase_contributor`; the approver is the dev admin holding the finance / legal / manager positions; the readings were identical before and after): - `showcase_invoice_signoff`, approve path. The submitter flips INV-1004 draft to sent (200), and a request opens `pending`. A caller edit while it is pending lands (200; `lockRecord: false`, and `sent` is not closed). The admin approves (200), the request ends `approved`, and the run ends `completed`. A caller edit after the run lands (200), so no hold is left on the record. - `showcase_invoice_signoff`, reject path (INV-1002). The reject is 200, the request ends `rejected`, the run's system `flag_held` write puts the invoice back to `draft`, and the run ends `completed`. A caller edit afterwards lands. - `showcase_release_signoff` (a `map` over two `showcase_task` records). It triggers and pauses, each task's request opens and is approved, and the run ends `completed`. `showcase_task` declares no `closedStates`, and the map is not under a record. - ADR-0162 item 7 and item 8 refuse none of these on this host. The sign-off mirrors no status onto the invoice, and the host runs a `job` service. The no-job-service case is the one that breaks a test, see Acceptance notes. ## Tests <details><summary>Local runs at head b50ff46</summary> - `pnpm --filter @objectstack/example-showcase exec vitest run --maxWorkers=2 test/paid-invoice-line-lock.test.ts`: 16/16 passed. - `pnpm --filter @objectstack/example-showcase exec vitest run --maxWorkers=2 test/approval-resume-relation-expand.test.ts`: 12/12 passed. Before the job service was added (5be97d0) it was 9/12. - `pnpm --filter @objectstack/example-showcase exec vitest run --maxWorkers=2` (the whole showcase suite): 49 files, 551/551 passed. - `pnpm --filter @objectstack/dogfood exec vitest run --maxWorkers=2` over every dogfood test file that names `showcase_invoice` (24 files), plus `authz-conformance`, `controlled-by-parent`, `owner-anchor-and-bulk-writes` and `flow-runas`: before the dogfood edits, exactly the two files above were red (1 + 6 tests). After them, `invoice-conditional-rules-server` and `showcase-readonly-when-parent` pass 11/11, and the rest passed unedited. - `pnpm --filter @objectstack/example-showcase typecheck`, `pnpm --filter @objectstack/dogfood typecheck`: exit 0. Both tsconfigs include their `test/` trees. - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: OK, 11 anchors judged, 0 lost. - `node scripts/pm/dispatch-gates.mjs --commands` at b50ff46 (the same 64 as at 5be97d0): 61 run, 60 exit 0, and `check:adr-symbol-anchors` exit 1 (routed separately, see Acceptance notes). NOT MEASURED locally: `check-plugin-teardown-shape --self-test` exit 3 (shallow clone; its fixture is pinned to a commit), `check:dual-build-cjs-loads` exit 3 (needs a full build), `check:query-options-erasure` exit 124 at 5be97d0 (240 s local cap). CI ran the last one green at b50ff46. </details> ## Acceptance notes - The sign-off test's missing job service is fixed in this PR (claim amendment 1), see What changes. - **The ADR anchor repair was routed separately, to #38919, and has landed.** ADR-0162 lines 77 and 718 anchored the hook symbols this PR deletes; PR #38936 re-anchored them to the hooks file and merged at 2026-12-01T16:28Z. This branch merged `main` at 45e4457 (head 4262a3e), and `check:adr-symbol-anchors` and `Lint & Repo Gates` are green there. - The liveness row `object.closedStates` in `packages/spec/liveness/object.json` is already `live`, with its own runtime proof (`packages/qa/dogfood/test/closed-state-lock.test.ts`). The card's last Done-when box was met by the key's own card, so this PR does not move the row. - **Checklist drift outside the surface, carried by #38987** (review follow-ups of this PR, L1 S1 7318788194): `records-forms.conditional-rules-header` acceptance[2] still says a `tax_rate` PATCH on the paid INV-1003 answers 200 and is discarded (it now answers 409 and is refused), and `access-security.write-path-guards` acceptance[5] and its `automated.ref` still expect `droppedFields` / `readonly_when` on the paid invoice, where this PR re-points those pins in `showcase-readonly-when-parent.dogfood.test.ts` to `RECORD_LOCKED`. Not edited here. - The console's master-detail save puts the header first (ADR-0162 D4 names it, and Execution item 4 is its own card). In the showcase, a save that edits lines and sets `paid` in one batch would meet a closed header on the line writes. This was not driven here. ## Verification Read first: 1. `examples/app-showcase/src/data/objects/invoice.object.ts`: the `closedStates` block. It is the whole runtime change. 2. `packages/qa/dogfood/test/showcase-readonly-when-parent.dogfood.test.ts`: the re-pointed pins, especially the `updateMany` case, which now runs under `continueOnError`. 3. `examples/app-showcase/test/paid-invoice-line-lock.test.ts`: the `expectRecordLocked` assertion set, and the REVERSE block. Two-minute check: boot the showcase, sign in as `admin@objectos.ai`, and `PATCH /api/v1/data/showcase_invoice/INVOICE_ID` (the id of INV-1003) with `{"region":"emea"}`. You should get `409` with `code` `RECORD_LOCKED`, and the region unchanged on re-read. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ)_ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzhKEbEnW8pwZRgK2gJ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 670bc89 commit b53e70f

8 files changed

Lines changed: 206 additions & 214 deletions

File tree

‎docs/qa/platform-checklist/areas/records-forms.json‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4553,7 +4553,7 @@
45534553
"title": "Object lifecycle hooks fire on the write path with the right timing, gate, async and error semantics — driven over /api/v1/data/*, oracled by the record effect and the log line",
45544554
"since": "v15",
45554555
"status": "active",
4556-
"revision": 13,
4556+
"revision": 14,
45574557
"priority": "P1",
45584558
"surface": "mixed",
45594559
"personas": [
@@ -4562,15 +4562,15 @@
45624562
"fixtures": {
45634563
"app": "showcase",
45644564
"requires": [
4565-
"the eight seeded showcase hooks (examples/app-showcase/src/data/hooks/index.ts, bound via defineStack({ hooks: allHooks })) — the four this item drives, plus showcase_guard_task_reopen (showcase_task, beforeUpdate, condition previous.done == true && record.done != true, body throws a user-facing sentence, onError:'abort', priority 60), the refusal fixture records-forms.script-action-hook-refusal-toast drives, plus the three paid-invoice line guards on showcase_invoice_line, which this item does not drive: showcase_guard_paid_invoice_line_add (beforeInsert), showcase_guard_paid_invoice_line_move (beforeUpdate, condition record.invoice != previous.invoice) and showcase_guard_paid_invoice_line_remove (beforeDelete), each reading the header invoice under runAs:'system' and throwing a user-facing sentence when it is paid (onError:'abort', priority 60; a system write and a cascade delete pass); showcase_normalize_task_title (showcase_task, events ['beforeInsert','beforeUpdate'], trims title, priority 50, onError:'abort'); showcase_stamp_inquiry_defaults (showcase_inquiry, beforeInsert, stamps status='new'/source='web', onError:'abort'); showcase_audit_task_completion (showcase_task, afterUpdate, condition previous.done!=true && record.done==true, async, retryPolicy {maxRetries:3,backoffMs:1000}, capabilities:['log'], onError:'log', priority 90); showcase_warn_over_budget (showcase_project, afterUpdate, condition record.spent!=null && record.budget!=null && record.spent>record.budget, async, capabilities:['log'], onError:'log')",
4565+
"the five seeded showcase hooks (examples/app-showcase/src/data/hooks/index.ts, bound via defineStack({ hooks: allHooks })) — the four this item drives, plus showcase_guard_task_reopen (showcase_task, beforeUpdate, condition previous.done == true && record.done != true, body throws a user-facing sentence, onError:'abort', priority 60), the refusal fixture records-forms.script-action-hook-refusal-toast drives. A paid invoice is not guarded by a hook: showcase_invoice declares closedStates (ADR-0162) and the platform refuses a caller's write to it and its lines RECORD_LOCKED; showcase_normalize_task_title (showcase_task, events ['beforeInsert','beforeUpdate'], trims title, priority 50, onError:'abort'); showcase_stamp_inquiry_defaults (showcase_inquiry, beforeInsert, stamps status='new'/source='web', onError:'abort'); showcase_audit_task_completion (showcase_task, afterUpdate, condition previous.done!=true && record.done==true, async, retryPolicy {maxRetries:3,backoffMs:1000}, capabilities:['log'], onError:'log', priority 90); showcase_warn_over_budget (showcase_project, afterUpdate, condition record.spent!=null && record.budget!=null && record.spent>record.budget, async, capabilities:['log'], onError:'log')",
45664566
"showcase_task (title required text + done boolean, defaultValue false), showcase_inquiry (status select whose 'new' option is default:true + source plain text with NO default), showcase_project (budget/spent currency + the spent_within_budget script rule that REJECTS spent > budget*1.2)",
45674567
"seeded rows: not-done task 'Build homepage' (done:false) for the transition PATCH; already-done tasks 'Audit current IA' and 'App wireframes' (done:true) for the non-transition proof; projects 'Data Platform' (budget 600000 / spent 420000) and 'Website Relaunch' (budget 150000 / spent 60000)",
45684568
"server log capture — the async audit/warn bodies call ctx.log.info/warn, routed to the engine logger (packages/runtime/src/sandbox/body-runner.ts log: engineCtx.logger); AND the ability to register a scratch hook (throwing / ordered) for the variants the four fixtures cannot observe. A scratch hook needs no scratch package: a package-less PUT /api/v1/meta/hook/NAME of a fresh name saves env-wide on a stock boot (hook is allowRuntimeCreate in packages/spec/src/kernel/metadata-plugin.zod.ts; QA run #33048 read 200). Run-proven recipe (QA run #24616): on a scratch app copy, put every scratch hook on showcase_inquiry behind a name-prefix condition (record.name.startsWith('qa-…')) so it touches only the probe rows; for the fail-closed probe, `record.name.startsWith('qa-fc') && int(record.name) > 0` compiles and faults only for a 'qa-fc…' row",
45694569
"a real running server: hooks fire in the ObjectQL engine on the live /api/v1/data/* route, never on a simulated dispatch"
45704570
],
45714571
"knownGaps": [
45724572
"afterInsert and afterDelete have NO fixture hook — the four seeded hooks cover beforeInsert, beforeUpdate and afterUpdate only. Exercise these two events with a scratch log hook or record the variant knownGap; do not fake coverage.",
4573-
"beforeDelete's one seeded showcase hook is showcase_guard_paid_invoice_line_remove, an abort fixture that refuses removing a line under a paid invoice; it logs nothing and this item does not drive it, so for this item the abort-blocks-delete contract is pinned by the dogfood hef_ref_guard fixture (packages/qa/dogfood/test/hook-error-format.dogfood.test.ts), a test-only stack, not the showcase app; drive beforeDelete via a scratch hook or cite that pin.",
4573+
"the showcase seeds no beforeDelete hook, so for this item the abort-blocks-delete contract is pinned by the dogfood hef_ref_guard fixture (packages/qa/dogfood/test/hook-error-format.dogfood.test.ts), a test-only stack, not the showcase app; drive beforeDelete via a scratch hook or cite that pin.",
45744574
"priority ordering (lowest-first on the SAME object+event) is not fixture-covered: showcase_normalize_task_title (priority 50) and showcase_guard_task_reopen (priority 60) do share showcase_task/beforeUpdate, but neither logs and the guard fires only on a reopening write it then refuses, so their order is not observable from outside; ordering needs a scratch pair of logging hooks on one object+event with distinct priorities.",
45754575
"onError:'abort' ROLLBACK and onError:'log' SUPPRESSION are only observable with a hook that THROWS — the four hooks this item drives never throw (their trim/stamp/log bodies always succeed). The seeded hooks that throw are showcase_guard_task_reopen (beforeUpdate) and the three paid-invoice line guards on showcase_invoice_line; they are refusal fixtures this item does not drive, and the abort-rollback clause's verify names a scratch throwing beforeInsert, so none stands in for it here. The abort-rollback, log-tolerate and fail-closed-condition clauses each require a scratch throwing hook (or the cited dogfood abort pin).",
45764576
"the async audit/warn lines land AFTER the HTTP write resolves (fire-and-forget runs once the engine has moved on) — a log read taken before the async body executes shows no line; settle before judging any no-fire."
@@ -4581,7 +4581,7 @@
45814581
"beforeUpdate — FIXTURE: showcase_normalize_task_title (trims title on every task update)",
45824582
"afterUpdate — FIXTURE: showcase_audit_task_completion (task done-transition audit) and showcase_warn_over_budget (project over-budget warn)",
45834583
"afterInsert — SCRATCH/knownGap: no showcase hook targets afterInsert; add a scratch afterInsert log hook or record knownGap",
4584-
"beforeDelete — SCRATCH/knownGap: the one seeded showcase hook (showcase_guard_paid_invoice_line_remove) is an abort fixture this item does not drive; the abort-blocks-delete shape is pinned by the dogfood hef_ref_guard fixture (hook-error-format.dogfood.test.ts)",
4584+
"beforeDelete — SCRATCH/knownGap: the showcase seeds no beforeDelete hook; the abort-blocks-delete shape is pinned by the dogfood hef_ref_guard fixture (hook-error-format.dogfood.test.ts)",
45854585
"afterDelete — knownGap: no showcase hook and no dogfood pin; add a scratch afterDelete log hook to exercise",
45864586
"multi-event targeting — FIXTURE: showcase_normalize_task_title lists events ['beforeInsert','beforeUpdate'] — ONE hook fires on two write kinds (hook-binder registers per-event × per-object)",
45874587
"CEL condition — two-root transition semantics (#4770/#4784) — FIXTURE: showcase_audit_task_completion `previous.done != true && record.done == true`; since #4770 `record` is the record's STATE (stored ⊕ payload, total over declared fields), so `record.done == true` alone is true on every edit of an already-done row — `previous` is what makes 'just became done' expressible",
@@ -4686,7 +4686,7 @@
46864686
"ref": "packages/qa/dogfood/test/object-hook-lifecycle-showcase.dogfood.test.ts, on the showcase as shipped over REST with the server log read off stdout/stderr: acceptance[0] (a /data POST of an inquiry with no source reads back source web and status new), acceptance[1] (a padded title reads back trimmed after the POST and after the PATCH), acceptance[2] and negative[2] (done false → true logs 'task completed: TITLE' once settled), acceptance[3] and negative[3] (a priority-only PATCH of the done task logs no second line), acceptance[4] and acceptance[5] (a spent-only PATCH to 1100 over a stored budget of 1000 logs 'project over budget: NAME (1100 / 1000)'; an under-budget PATCH logs none). packages/qa/dogfood/test/object-hook-lifecycle-scratch.dogfood.test.ts, on scratch hooks over REST: acceptance[6] and negative[0] (a throwing beforeInsert under abort is 400 with its sentence and lands no row), acceptance[7] and negative[1] (a throwing async afterUpdate under log keeps the PATCH and logs '[hook] handler failed (onError=log; suppressing)' with the hook's name, never the fire-and-forget line), acceptance[8] and negative[4] (int(record.name) on a non-numeric name, under onError log, is 400 VALIDATION_ERROR naming the hook and 'operation aborted', never the condition source, no row and no '[REST] Unhandled error' line; a numeric name is the 201 control) and acceptance[9] (priority 10 logs before priority 90, declared in the opposite order). packages/qa/dogfood/test/showcase-public-form.dogfood.test.ts (the beforeInsert stamp on an anonymous inquiry submit) and packages/qa/dogfood/test/hook-error-format.dogfood.test.ts (the beforeDelete onError:'abort' throw → REST error body) stay named. packages/verify/src/harness.hook-refusal-door.test.ts (a handler hook's declared refusals catalogue answering one zh-CN envelope on both bootStack doors, the source handler and the artifact body) stays named too, as evidence of its own layer: no clause here scores a hook's refusals, which is new coverage for a checklist-author card, not this item's. The declarative-wrapper MECHANISM pins in packages/objectql (hook-condition-previous-scope.test.ts, hook-condition-merged-record.test.ts, hook-binder.test.ts, hook-condition-fail-loud.test.ts) stay evidence of their own layer"
46874687
},
46884688
"source": [
4689-
"examples/app-showcase/src/data/hooks/index.ts#allHooks (the four fixture hooks this item drives, the showcase_guard_task_reopen refusal fixture and the three showcase_guard_paid_invoice_line_* guards beside them, + allHooks export; header comments spell out the two-root #4784 transition and the != null / not has() #4770 rationale verbatim)",
4689+
"examples/app-showcase/src/data/hooks/index.ts#allHooks (the four fixture hooks this item drives, the showcase_guard_task_reopen refusal fixture beside them, + allHooks export; header comments spell out the two-root #4784 transition and the != null / not has() #4770 rationale verbatim)",
46904690
"packages/spec/src/data/hook.zod.ts#HookSchema (HookSchema + HookEvent enum beforeFind/afterFind/beforeInsert/afterInsert/beforeUpdate/afterUpdate/beforeDelete/afterDelete; defineHook; async 'after* only'; onError default 'abort'; empty-target refusal #4001)",
46914691
"packages/objectql/src/hook-wrappers.ts#wrapDeclarativeHook (wrapDeclarativeHook wrapping order condition→async→retry→timeout→onError; pickRecordPayload #4770 record = stored ⊕ payload total over declared fields; pickPreviousPayload #4784 previous binding; HookConditionError #4775 fail-closed, raised OUTSIDE onError; fireAndForget = async && isAfterEvent)",
46924692
"packages/objectql/src/hook-binder.ts#bindHooksToEngine (bindHooksToEngine: per-event × per-object engine.registerHook with priority; unresolved-body / empty-target skips)",
@@ -4774,6 +4774,12 @@
47744774
"date": "2026-11-15",
47754775
"change": "automated.ref names packages/verify/src/harness.hook-refusal-door.test.ts, which exists at the base and was missing (QA run #33785, ledger row 13). It is named as evidence of its own layer only; the hook-refusal locale coverage the same note asked for is new coverage, left to a checklist-author card. No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.",
47764776
"ref": "#33990"
4777+
},
4778+
{
4779+
"revision": 14,
4780+
"date": "2026-12-01",
4781+
"change": "The three paid-invoice line guard hooks left the showcase: showcase_invoice declares closedStates on status 'paid' (ADR-0162 Execution item 3) and the platform refuses those writes RECORD_LOCKED. fixtures.requires names five seeded hooks, the beforeDelete knownGap and variant say the showcase seeds no beforeDelete hook, and automated.ref drops the guards. No clause changed; this item never drove the guards.",
4782+
"ref": "#37771"
47774783
}
47784784
]
47794785
},

‎examples/app-showcase/src/data/hooks/index.ts‎

Lines changed: 3 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,9 @@ export const TASK_REOPEN_REFUSAL =
128128

129129
/**
130130
* beforeUpdate (gated) — the showcase's first hook that REFUSES a write, with a
131-
* sentence addressed to the user. (The three paid-invoice line guards below
132-
* refuse the same way.)
131+
* sentence addressed to the user. (A paid invoice is not guarded by a hook: the
132+
* invoice declares `closedStates`, and the platform refuses a caller's write to
133+
* it and its lines with `RECORD_LOCKED` — `src/data/objects/invoice.object.ts`.)
133134
*
134135
* `throw new Error('<sentence>')` from a sandboxed body is the business-refusal
135136
* shape: the write is aborted (`onError: 'abort'`) and the sentence travels to
@@ -161,129 +162,10 @@ export const GuardTaskReopenHook = {
161162
description: 'Refuses reopening a finished task (done true to false) with a user-facing sentence.',
162163
};
163164

164-
/**
165-
* The sentences the paid-invoice line guards refuse with. Exported so the
166-
* fixture's test quotes the same strings the hooks throw.
167-
*/
168-
export const PAID_INVOICE_LINE_ADD_REFUSAL =
169-
'This invoice is paid, so its lines are locked: a line cannot be added to it.';
170-
export const PAID_INVOICE_LINE_REMOVE_REFUSAL =
171-
'This invoice is paid, so its lines are locked: a line cannot be removed from it.';
172-
export const PAID_INVOICE_LINE_MOVE_REFUSAL =
173-
'A paid invoice\'s lines are locked: a line cannot be moved onto or off a paid invoice.';
174-
175-
/**
176-
* The shared prelude of the three guards: `paid(id)` reads the header's status.
177-
*
178-
* Two kinds of write pass every guard:
179-
* - a SYSTEM write (`ctx.session.isSystem`): the seed loads INV-1003's line
180-
* under a header that is already paid, and a migration or import restores
181-
* history. Every system writer passes by design — the seed, a script
182-
* action's `ctx.api`, a `runAs: 'system'` flow — and none writes
183-
* `showcase_invoice_line` in the showcase today. The platform's static
184-
* `readonly` strip exempts system writes the same way;
185-
* - a header that cannot be read: the engine's reference check answers a
186-
* dangling `invoice` with its own refusal, so the guard does not invent one.
187-
*/
188-
const PAID_HEADER_PRELUDE =
189-
"if (ctx.session && ctx.session.isSystem) return;" +
190-
"var paid = async function (id) {" +
191-
" if (!id) return false;" +
192-
" var header = await ctx.api.object('showcase_invoice').findOne({ where: { id: id } });" +
193-
" return !!header && header.status === 'paid';" +
194-
"};";
195-
196-
/**
197-
* beforeInsert / beforeUpdate / beforeDelete — a PAID invoice's lines are
198-
* locked against adding, moving and removing.
199-
*
200-
* `readonlyWhen: parent.status == 'paid'` on the line's `product`, `quantity`
201-
* and `unit_price` (`invoice.object.ts`) locks EDITS of an existing line. It is
202-
* insert-exempt by design, and it judges field values, not a line's existence,
203-
* so it cannot stop a line from being added, removed, or repointed at another
204-
* invoice. Each of those moves the paid `total`. A `validations[]` rule cannot
205-
* hold these either: no `validations[]` rule binds `parent`, and none runs on
206-
* delete. So the three guards are hooks, the mechanism
207-
* `ValidationRuleSchema.events` prescribes for that case.
208-
*
209-
* Each guard reads the header itself, under `runAs: 'system'`. The verdict is
210-
* the system's, and it must not depend on the writer's read grants on
211-
* invoices.
212-
*/
213-
export const GuardPaidInvoiceLineAddHook = {
214-
name: 'showcase_guard_paid_invoice_line_add',
215-
label: 'Guard Paid Invoice Line Add',
216-
object: 'showcase_invoice_line',
217-
events: ['beforeInsert'] as LifecycleEvent[],
218-
body: {
219-
language: 'js' as const,
220-
source:
221-
PAID_HEADER_PRELUDE +
222-
`if (await paid(ctx.input.invoice)) throw new Error(${JSON.stringify(PAID_INVOICE_LINE_ADD_REFUSAL)});`,
223-
capabilities: ['api.read'] as ('api.read')[],
224-
},
225-
runAs: 'system' as const,
226-
priority: 60,
227-
onError: 'abort' as const,
228-
description: 'Refuses adding a line to a paid invoice, with a user-facing sentence.',
229-
};
230-
231-
/**
232-
* The repoint half: an update that moves a line's `invoice` onto or off a paid
233-
* header. The condition gates the hook to that write, so an ordinary line
234-
* edit pays no header read.
235-
*/
236-
export const GuardPaidInvoiceLineMoveHook = {
237-
name: 'showcase_guard_paid_invoice_line_move',
238-
label: 'Guard Paid Invoice Line Move',
239-
object: 'showcase_invoice_line',
240-
events: ['beforeUpdate'] as LifecycleEvent[],
241-
condition: 'record.invoice != previous.invoice',
242-
body: {
243-
language: 'js' as const,
244-
source:
245-
PAID_HEADER_PRELUDE +
246-
"var before = ctx.previous ? ctx.previous.invoice : undefined;" +
247-
`if ((await paid(before)) || (await paid(ctx.input.invoice))) throw new Error(${JSON.stringify(PAID_INVOICE_LINE_MOVE_REFUSAL)});`,
248-
capabilities: ['api.read'] as ('api.read')[],
249-
},
250-
runAs: 'system' as const,
251-
priority: 60,
252-
onError: 'abort' as const,
253-
description: 'Refuses moving a line onto or off a paid invoice, with a user-facing sentence.',
254-
};
255-
256-
/**
257-
* The remove half. A cascade delete (`ctx.referentialCascadeDelete`) passes:
258-
* that is the header itself being deleted, not a line removed from a header
259-
* that stays.
260-
*/
261-
export const GuardPaidInvoiceLineRemoveHook = {
262-
name: 'showcase_guard_paid_invoice_line_remove',
263-
label: 'Guard Paid Invoice Line Remove',
264-
object: 'showcase_invoice_line',
265-
events: ['beforeDelete'] as LifecycleEvent[],
266-
body: {
267-
language: 'js' as const,
268-
source:
269-
PAID_HEADER_PRELUDE +
270-
"if (ctx.referentialCascadeDelete === true || !ctx.previous) return;" +
271-
`if (await paid(ctx.previous.invoice)) throw new Error(${JSON.stringify(PAID_INVOICE_LINE_REMOVE_REFUSAL)});`,
272-
capabilities: ['api.read'] as ('api.read')[],
273-
},
274-
runAs: 'system' as const,
275-
priority: 60,
276-
onError: 'abort' as const,
277-
description: 'Refuses removing a line from a paid invoice, with a user-facing sentence.',
278-
};
279-
280165
export const allHooks = [
281166
NormalizeTaskTitleHook,
282167
StampInquiryDefaultsHook,
283168
GuardTaskReopenHook,
284-
GuardPaidInvoiceLineAddHook,
285-
GuardPaidInvoiceLineMoveHook,
286-
GuardPaidInvoiceLineRemoveHook,
287169
AuditTaskCompletionHook,
288170
WarnOverBudgetHook,
289171
];

0 commit comments

Comments
 (0)