@sudoke/kernel 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,8 +41,11 @@ There is a single assembly regime — the historical compat/strict split was rem
41
41
  consistency check demands, at seal time:
42
42
 
43
43
  - an undo policy for every registered event type (declaring support or `{ kind: 'unavailable' }` —
44
- the answer is declared, silence is a defect), each with a `mayRead` hook (origin-read rights are a
45
- declared decision, never a default allow), and every undo handler a `mayPreview` hook;
44
+ the answer is declared, silence is a defect), each with an origin-read decision — a `mayRead` hook
45
+ on the policy itself, or the app-wide default gate registered once (`registerUndoReadGate`;
46
+ a policy-level hook wins where present). Read rights are a declared decision, never a default
47
+ allow — an assembly declaring neither fails the boot;
48
+ - every undo handler a declared `compensationCommand` that resolves to a registered command;
46
49
  - a declared semver version on every command and query;
47
50
  - a storage engine providing the operation-ledger capability.
48
51
 
@@ -105,7 +108,11 @@ including the caller's `viewRevision`. A replayed
105
108
  success additionally carries `producedBy` — the contract that PRODUCED the stored result (commandName·
106
109
  versions·protocolVersion·the role that executed); rows older than producer tracking answer
107
110
  `{ unknown: true }`. Redeliveries re-check the current rights first — undo redeliveries re-derive the
108
- permission view structurally (the verdict never depends on error-code spelling), and a removed
111
+ permission view structurally (the verdict never depends on error-code spelling); when the source
112
+ operation carries a STORED compensation, its recorded envelope re-proves the rights whatever the
113
+ CURRENT policy consensus says (supported·unavailable·mixed alike — the policy may have moved since
114
+ the compensation was stored; a removed compensation command leaves nothing re-provable → refused),
115
+ and a removed
109
116
  command's stored result returns only while the account is valid AND the recorded rights still hold:
110
117
  the producer's role AND, for scoped commands, the app policy's verdict on the RECORDED normalized
111
118
  target (stamped beside every result and on every event envelope as `policyTarget` at write time —
@@ -120,13 +127,19 @@ envelope (`undoOfOperationId`·`undoSourceSeq`·`undoHandlerVersion`).
120
127
 
121
128
  ```ts
122
129
  const status = await undoStatus({ sourceSeqs: [seq] }, identity) // per-seq support·processing state
130
+ // at most UNDO_STATUS_MAX_SEQS (100) seqs per call — a larger bundle is a stage-4 input refusal,
131
+ // never a silent truncation
123
132
  const preview = await previewUndo({ sourceSeq: seq }, identity)
124
- // preview.status: available | warning | blocked | unavailable | already_undone
133
+ // preview.status: available | warning | blocked | unavailable | already_undone | denied
134
+ // denied = a permission refusal (read gate, handler gate, compensation-command role·delegation) —
135
+ // carries no operation facts, the same vocabulary undoStatus answers 'denied' with
125
136
  // preview.changes (before = current value, after = the value execution will set), losses, blockers, planHash
126
137
  const done = await executeUndo(
127
138
  { sourceSeq: seq, expectedPlanHash: preview.planHash, acceptLosses: true, requestKey: 'retry-key' },
128
139
  identity,
129
140
  )
141
+ // a permission refusal on execution keeps its OWN stage and code (1~3 — e.g. gate.role_denied);
142
+ // business blockers (a later change, plan defects) answer as stage-8 undo refusals
130
143
  ```
131
144
 
132
145
  Contract highlights:
@@ -134,25 +147,34 @@ Contract highlights:
134
147
  - **The unit is the operation** — one atomic command run (batch items are separate operations under one
135
148
  batchId). Selecting any event row of the operation resolves to the whole operation; partial undo does
136
149
  not exist. `undoStatus` and `previewUndo` share ONE per-operation judgment — every event row of one
137
- operation answers the same read verdict and the same undo consensus (a single unavailable event type
138
- makes the whole operation unavailable; multiple handlers answer `undo.operation_mixed_policies`),
139
- while the response keeps the requested seq as the anchor.
140
- - **The planner is domain-owned** (`registerUndoHandler`): `plan(source, identity)` is read-only and
141
- returns exactly one registered compensation command, `dependsOn` state tokens, `changes`·`preserved`·
142
- `losses`·`blockers`. The plan is machine-consumed, so the kernel validates its shape completely
143
- (required `changes` array, string `preserved` entries, JSON-representable `before`/`after`,
144
- non-negative integer loss counts) — a malformed plan answers `undo.plan_invalid` and never reaches
145
- the hash, the preview or the execution.
146
- - **Origin-read rights live on the POLICY** (`mayRead` on every `registerUndoPolicies` entry) — REQUIRED
147
- in strict mode: it runs before ANY branch (supported·unavailable·mixed·legacy·already-undone) answers
148
- anything about an operation, and a refusal carries no operation facts (no id, no processing state, no
149
- policy reason). Supported handlers refine further with `mayPreview` (equally required). An
150
- optional `roles` on the policy scopes its CATALOG exposure; exposure and the read verdict are
151
- independent decisions.
150
+ operation answers the same read verdict, the same compensation-command verdict and the same undo
151
+ consensus (a single unavailable event type makes the whole operation unavailable; multiple handlers
152
+ answer `undo.operation_mixed_policies`), while the response keeps the requested seq as the anchor.
153
+ A status row never promises a handler to an identity that cannot run the compensation: the shared
154
+ gates (origin-read → declared compensation command → handler hook) run in that fixed order before
155
+ any state — `already_undone` included — is consulted, on both paths.
156
+ - **The planner is domain-owned** (`registerUndoHandler`) and DECLARES its compensation command
157
+ (`compensationCommand` — exactly one registered command, resolved at the seal): the kernel checks the
158
+ current identity's access to the declared command BEFORE `plan()` runs (an unauthorized identity
159
+ never triggers plan computation and never learns the blockers a plan would have named), and a plan
160
+ naming any other command is a defect (`undo.plan_invalid`). `plan(source, identity)` is read-only and
161
+ returns `dependsOn` state tokens, `changes`·`preserved`·`losses`·`blockers`. The plan is
162
+ machine-consumed, so the kernel validates its shape completely (required `changes` array, string
163
+ `preserved` entries, JSON-representable `before`/`after`, non-negative integer loss counts) — a
164
+ malformed plan answers `undo.plan_invalid` and never reaches the hash, the preview or the execution.
165
+ - **Origin-read rights are a declared decision** — a `mayRead` hook on the policy, or the app-wide
166
+ default gate (`registerUndoReadGate`, one registration serving every policy that declares no
167
+ `mayRead`; the policy-level hook wins where present). It runs before ANY branch
168
+ (supported·unavailable·mixed·legacy·already-undone) answers anything about an operation, and a
169
+ refusal carries no operation facts (no id, no processing state, no policy reason). For a supported
170
+ consensus the DECLARED compensation command's access check follows (same refusal shape — status and
171
+ preview agree), then the OPTIONAL `mayPreview` hook refines further. An optional `roles` on the
172
+ policy scopes its CATALOG exposure; exposure and the read verdict are independent decisions.
152
173
  - **The preview judges the compensation through the SAME static+dynamic checks a direct call would
153
174
  face** (schema·delegation·role·app-policy target·preconditions·invariants·transitions) — 'available'
154
- means a call NOW would pass stages 1~7; a denied target blocks and leaks nothing (status answers
155
- carry a 'denied' state too).
175
+ means a call NOW would pass stages 1~7. Every permission refusal (read gate, handler gate,
176
+ compensation-command role·delegation, denied target) answers `denied` and leaks nothing; on
177
+ execution such refusals keep their own stage and code (1~3), never a stage-8 re-wrap.
156
178
  - **Conflicts are sequence-based, never value-based** — the planner decides with ledger facts; a later
157
179
  same-field change blocks even when the value round-tripped. Hard conflicts are never forceable; the
158
180
  confirmation pair is `acceptLosses` + `expectedPlanHash` (`undo.confirmation_required`,
@@ -168,9 +190,9 @@ Contract highlights:
168
190
  through the shared gate pipeline (no bypass lane, no nested transaction), and events·linkage·
169
191
  idempotency·audit commit or roll back together.
170
192
  - **Undoing an undo** compensates the compensation — it is a normal operation with its own policy. Undo
171
- handler versions are catalog content: a handler bump moves catalogRevision (and the published policy
172
- carries `handlerVersion`); per-command revisions stay stable — which command compensates an event is a
173
- plan-time decision, so catalogRevision·catalogStatus is the discovery surface for policy changes.
193
+ handler declarations are catalog content: a handler bump or a `compensationCommand` change moves
194
+ catalogRevision (the published policy carries `handlerVersion`·`compensationCommand`); per-command
195
+ revisions stay stable — catalogRevision·catalogStatus is the discovery surface for policy changes.
174
196
  - **Legacy rows** (written before the envelope) are addressed by exact seq; unprovable grouping answers
175
197
  `undo.legacy_operation_unknown`, missing prior state `undo.snapshot_missing`.
176
198
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sudoke/kernel",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "SUDOKE kernel — the 9-stage command gate, ledger, registries and async storage port behind every sudoke app",
5
5
  "type": "module",
6
6
  "files": [
package/src/catalog.ts CHANGED
@@ -31,7 +31,7 @@ const revisionOf = (v: unknown) => 'r1:' + createHash('sha256').update(canonical
31
31
  /** The kernel protocol format version — the shape of catalog·common request/response·undo contracts
32
32
  * this kernel speaks. Managed by kernel semver releases, independent of the npm package version and of
33
33
  * any app's catalogVersion. */
34
- export const PROTOCOL_VERSION = '1.0.0'
34
+ export const PROTOCOL_VERSION = '1.1.0'
35
35
 
36
36
  /** The full contract content of one command — hashed into its revision and embeddable into release
37
37
  * manifests (the validator's structural breaking detection diffs these trees). Shared error-code
@@ -113,16 +113,23 @@ export function computeCatalogRevisions(): CatalogRevisions {
113
113
  return { catalog, commands, queries }
114
114
  }
115
115
 
116
- /** The published form of an undo policy — supported entries carry the HANDLER's version: the handler
117
- * contract (what it plans, how it judges conflicts) is part of the undo surface, so its version moves
118
- * the catalog revision and shows in the catalog document. (Event-scoped policies cannot be folded into
119
- * per-command revisions statically — which command compensates for an event is a plan-time decision.
120
- * catalogRevision·catalogStatus is the discovery surface for policy and handler changes.) */
116
+ /** The published form of an undo policy — supported entries carry the HANDLER's version and the
117
+ * DECLARED compensation command: the handler contract (what it plans, how it judges conflicts) is
118
+ * part of the undo surface, so its version and declaration move the catalog revision and show in the
119
+ * catalog document. (Event-scoped policies cannot be folded into per-command revisions statically —
120
+ * which command compensates for an event is a plan-time decision. catalogRevision·catalogStatus is
121
+ * the discovery surface for policy and handler changes.) */
121
122
  export function publishedUndoPolicy(p: import('./types.js').EventUndoPolicy) {
122
123
  // the mayRead hook is enforcement, not published contract (functions never serialize); `roles` IS
123
124
  // published — it scopes this entry's catalog exposure and moves the catalog revision when it changes
124
125
  return p.kind === 'supported'
125
- ? { kind: p.kind, handlerId: p.handlerId, handlerVersion: undoHandlerOf(p.handlerId)?.version ?? null, ...(p.roles ? { roles: [...p.roles] } : {}) }
126
+ ? {
127
+ kind: p.kind,
128
+ handlerId: p.handlerId,
129
+ handlerVersion: undoHandlerOf(p.handlerId)?.version ?? null,
130
+ compensationCommand: undoHandlerOf(p.handlerId)?.compensationCommand ?? null,
131
+ ...(p.roles ? { roles: [...p.roles] } : {}),
132
+ }
126
133
  : { kind: p.kind, code: p.code, reason: p.reason, ...(p.roles ? { roles: [...p.roles] } : {}) }
127
134
  }
128
135
 
package/src/index.ts CHANGED
@@ -19,12 +19,13 @@ export { registerAppProtocol, protocolPreamble, PROTOCOL_BATCH, PROTOCOL_DELEGAT
19
19
  export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape, queryAccessOf } from './queries.js'
20
20
  export type { QueryDefinition, QueryOutcome, QueryRefusal } from './queries.js'
21
21
  export { registerRoles, registerCommand, lookupCommand, allCommands, inputShapeOf, catalogMeta, registerTransitionMachine, transitionRulesOf, allTransitionMachines, registerEventContracts, eventContractOf, allEventContractTypes, registerErrorCodes, errorCodeOf, allErrorCodes, catalogConsistencyErrors, completeAssembly, sealRegistries } from './registry.js'
22
- export { registerUndoHandler, registerUndoPolicies, undoPolicyOf, undoHandlerOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions, registerCatalogRelease } from './registry.js'
22
+ export { registerUndoHandler, registerUndoPolicies, registerUndoReadGate, undoPolicyOf, undoHandlerOf, undoReadGateOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions, registerCatalogRelease } from './registry.js'
23
23
  export type { TransitionRule } from './registry.js'
24
24
  export { buildCatalogDocument, catalogStatus, catalogChanges, catalogRevisionOf, commandRevisionOf, queryRevisionOf, viewRevisionOf, commandContractShape, queryContractShape, computeCatalogRevisions, responseMetaOf, PROTOCOL_VERSION } from './catalog.js'
25
25
  export { validateReleaseManifest, structuralBreakingChanges } from './releases.js'
26
26
  export type { CatalogReleaseManifest, ReleaseManifestContract } from './releases.js'
27
- export { previewUndo, executeUndo, undoStatus } from './undo.js'
27
+ export { previewUndo, executeUndo, undoStatus, UNDO_STATUS_MAX_SEQS } from './undo.js'
28
+ export type { UndoStatusRow } from './undo.js'
28
29
  export { roleAllowsCommand, delegationScopeEntries, commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
29
30
  export type { CommandAccess, CommandRestriction } from './visibility.js'
30
31
  export { registriesSealed, resetKernelForTests } from './state.js'
package/src/mcp.ts CHANGED
@@ -20,7 +20,7 @@ import { executeCommand } from './gate.js'
20
20
  import { identityFromToken, unauthenticated } from './auth.js'
21
21
  import { allQueries, executeQuery } from './queries.js'
22
22
  import { buildCatalogDocument, catalogChanges, catalogStatus } from './catalog.js'
23
- import { executeUndo, previewUndo, undoStatus } from './undo.js'
23
+ import { executeUndo, previewUndo, undoStatus, UNDO_STATUS_MAX_SEQS } from './undo.js'
24
24
  import { allCommands, inputShapeOf } from './registry.js'
25
25
  import { commandAccessOf, visibleQueriesFor } from './visibility.js'
26
26
 
@@ -230,7 +230,7 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
230
230
  'undo_status',
231
231
  {
232
232
  description: 'Per-sequence undo support·processing state (exact ledger sequences — the status is a list view, not an execution guarantee)',
233
- inputSchema: { sourceSeqs: z.array(z.number().int()).describe('exact ledger sequences to check (up to 100)') },
233
+ inputSchema: { sourceSeqs: z.array(z.number().int()).describe(`exact ledger sequences to check (at most ${UNDO_STATUS_MAX_SEQS} per call — a larger bundle is refused as an input error, never truncated)`) },
234
234
  },
235
235
  async (args: { sourceSeqs?: number[] }) => {
236
236
  const live = await requireLive('undo_status')
@@ -242,7 +242,7 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
242
242
  server.registerTool(
243
243
  'undo_preview',
244
244
  {
245
- description: 'Preview the undo of the operation behind a ledger sequence — the compensation plan, conflicts, losses and the plan hash, judged for your current identity against current state',
245
+ description: 'Preview the undo of the operation behind a ledger sequence — the compensation plan, conflicts, losses and the plan hash, judged for your current identity against current state (status denied = a permission refusal carrying no operation facts)',
246
246
  inputSchema: { sourceSeq: z.number().int().describe('any event sequence of the operation — the whole atomic operation is resolved') },
247
247
  },
248
248
  async (args: { sourceSeq?: number }) => {
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The single reader of a ledger row's operation envelope — the undo planner, the redelivery
3
+ * rights checks and the rebuilding projection all parse `row.meta` through here, so the
4
+ * envelope-vs-row precedence can never drift between two readers.
5
+ *
6
+ * eventVersion precedence (the kernel contract): the envelope's value wins; the row's own version
7
+ * column is the fallback. Rows carrying neither are legacy and answer undefined — callers resolve
8
+ * that as format version 1.
9
+ */
10
+ import type { EventOperationMeta } from './types.js'
11
+ import type { LedgerRow } from './storage.js'
12
+
13
+ /** The operation envelope a row carries — undefined when absent or non-JSON (a hand-edited row);
14
+ * the read never fails. */
15
+ export type OperationMeta = Partial<EventOperationMeta>
16
+
17
+ export function operationMetaOf(row: LedgerRow): OperationMeta | undefined {
18
+ if (!row.meta) return undefined
19
+ try {
20
+ return JSON.parse(row.meta) as OperationMeta
21
+ } catch {
22
+ return undefined
23
+ }
24
+ }
25
+
26
+ /** The event format version a stored row carries — envelope first, then the row's version column. */
27
+ export function ledgerEventVersionOf(row: LedgerRow): number | undefined {
28
+ return operationMetaOf(row)?.eventVersion ?? row.version
29
+ }
@@ -1,3 +1,4 @@
1
+ import { ledgerEventVersionOf } from './operation-meta.js'
1
2
  import { storageOf } from './storage.js'
2
3
  import { assertOpenFor, defaultKernelState, type RegisteredProjector } from './state.js'
3
4
  import type { DomainEvent } from './types.js'
@@ -102,17 +103,7 @@ export async function rebuildProjections(): Promise<void> {
102
103
  proj.initTables,
103
104
  async () => {
104
105
  for (const r of await storageOf().domainRows()) {
105
- // eventVersion reaches replay through the envelope (operation-ledger engines) or the legacy
106
- // version column; rows carrying neither are version 1 by definition
107
- let eventVersion: number | undefined = r.version
108
- if (r.meta) {
109
- try {
110
- const parsed = JSON.parse(r.meta) as { eventVersion?: number }
111
- if (parsed.eventVersion !== undefined) eventVersion = parsed.eventVersion
112
- } catch {
113
- // a non-JSON envelope on a hand-edited row falls back to the version column — the read never fails
114
- }
115
- }
106
+ const eventVersion = ledgerEventVersionOf(r)
116
107
  await applyDomainEvent(
117
108
  {
118
109
  type: r.type,
package/src/registry.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { GateError, type CommandDefinition, type ErrorCodeDefinition, type EventUndoPolicy, type UndoHandler, type CatalogRelease } from './types.js'
1
+ import { GateError, type CommandDefinition, type ErrorCodeDefinition, type EventUndoPolicy, type UndoHandler, type UndoMayRead, type CatalogRelease } from './types.js'
2
2
  import type { ZodTypeAny } from 'zod'
3
3
  import { describeShape } from './queries.js'
4
4
  import { assertOpenFor, defaultKernelState, frozenCopyOf, sealFor } from './state.js'
@@ -178,18 +178,35 @@ export function registerUndoPolicies(policies: Record<string, EventUndoPolicy>):
178
178
  }
179
179
  }
180
180
 
181
- /** Undo-handler registration — the domain's compensation planner. plan() is read-only and runs inside
182
- * one consistent read snapshot (preview) or inside the execution transaction (execute). */
181
+ /** Undo-handler registration — the domain's compensation planner. `compensationCommand` names the
182
+ * one registered command the handler plans with (existence is resolved at the seal — registration
183
+ * order is free). plan() is read-only and runs inside one consistent read snapshot (preview) or
184
+ * inside the execution transaction (execute). */
183
185
  export function registerUndoHandler(handler: UndoHandler): void {
184
186
  assertOpenFor(defaultKernelState, `registerUndoHandler ${handler.id}`)
185
187
  if (!handler.id?.trim() || !handler.version?.trim() || typeof handler.plan !== 'function')
186
188
  throw new Error('An undo handler needs id, version and a plan function')
189
+ if (!handler.compensationCommand?.trim())
190
+ throw new Error(`An undo handler needs compensationCommand — the registered command it plans with: ${handler.id}`)
187
191
  if (defaultKernelState.undoHandlers.has(handler.id)) throw new Error(`Undo handler registered twice: ${handler.id}`)
188
192
  defaultKernelState.undoHandlers.set(handler.id, frozenCopyOf({ ...handler }) as UndoHandler)
189
193
  }
190
194
 
195
+ /** The app-wide default origin-read gate — one registration serves every undo policy that declares
196
+ * no mayRead of its own (a policy-level hook wins where present). Undo answers never read without a
197
+ * decision: policies without mayRead AND no default gate fail the boot. The kernel does not interpret
198
+ * read scopes — the gate is the app's business judgment. */
199
+ export function registerUndoReadGate(gate: UndoMayRead): void {
200
+ assertOpenFor(defaultKernelState, 'registerUndoReadGate')
201
+ if (defaultKernelState.undoReadGate) throw new Error('The default undo read gate is registered twice — one gate per assembly')
202
+ if (typeof gate !== 'function') throw new Error('The default undo read gate must be a function')
203
+ defaultKernelState.undoReadGate = gate
204
+ }
205
+
191
206
  export const undoPolicyOf = (type: string): EventUndoPolicy | undefined => defaultKernelState.undoPolicies.get(type)
192
207
  export const undoHandlerOf = (id: string): UndoHandler | undefined => defaultKernelState.undoHandlers.get(id)
208
+ /** The registered default origin-read gate, when one exists — policies without their own mayRead fall back to it */
209
+ export const undoReadGateOf = (): UndoMayRead | undefined => defaultKernelState.undoReadGate ?? undefined
193
210
  /** All registered undo policies — a fresh record, published by the catalog document */
194
211
  export const allUndoPolicies = (): Record<string, EventUndoPolicy> => Object.fromEntries([...defaultKernelState.undoPolicies.entries()])
195
212
 
@@ -208,9 +225,6 @@ export const eventVersionOf = (type: string): number | undefined => defaultKerne
208
225
  /** All registered event versions — a fresh record (catalog fingerprint input) */
209
226
  export const allEventVersions = (): Record<string, number> => Object.fromEntries([...defaultKernelState.eventVersions.entries()])
210
227
 
211
- /** Kernel assembly options — compat (default) keeps the historical contract; strict additionally
212
- * demands undo coverage, declared versions, the operation-ledger capability and per-write contracts.
213
- * Sealed with the registries — configuring after the seal is a defect. */
214
228
  /** Registers the served catalog release declaration — the app-declared compatibility version plus the
215
229
  * change list of this release (what catalogChanges serves and the release validator checks). */
216
230
  export function registerCatalogRelease(release: CatalogRelease): void {
@@ -305,18 +319,21 @@ export function catalogConsistencyErrors(): string[] {
305
319
  const badQueryVersions = [...s.queries.values()].filter((q) => q.version !== undefined && !SEMVER_RE.test(q.version)).map((q) => q.name)
306
320
  if (badQueryVersions.length > 0)
307
321
  errors.push(`valid semver query versions are required: [${badQueryVersions.join(', ')}]`)
308
- // (the release catalogVersion is semver-checked at registration time, in every mode — no strict duplicate here)
309
- const hookless = [...s.undoHandlers.values()].filter((h) => typeof h.mayPreview !== 'function').map((h) => h.id)
310
- if (hookless.length > 0)
311
- errors.push(
312
- `a mayPreview hook is required on every undo handler — history-read rights are a declared decision, never a default allow — missing: [${hookless.join(', ')}]`,
313
- )
322
+ // (the release catalogVersion is semver-checked at registration time — no duplicate check here)
323
+ // the DECLARED compensation command must exist — the kernel checks plan-entry rights against it
324
+ // before the planner runs, so a dangling declaration would break every preview of this handler
325
+ const unregisteredCompensations = [...s.undoHandlers.values()]
326
+ .filter((h) => !s.commands.has(h.compensationCommand))
327
+ .map((h) => `${h.id} → '${h.compensationCommand}'`)
328
+ if (unregisteredCompensations.length > 0)
329
+ errors.push(`an undo handler's compensationCommand must be a registered command — dangling: [${unregisteredCompensations.join(', ')}]`)
314
330
  // the OPERATION-level read gate is a declared decision too — unavailable and mixed branches answer
315
- // operation facts, so every policy (not only supported handlers) must state who may read them
331
+ // operation facts, so every policy (not only supported handlers) must state who may read them:
332
+ // its own mayRead hook, or the app-wide default gate registered once (registerUndoReadGate)
316
333
  const readless = [...s.undoPolicies.entries()].filter(([, p]) => typeof p.mayRead !== 'function').map(([t]) => t)
317
- if (readless.length > 0)
334
+ if (readless.length > 0 && !s.undoReadGate)
318
335
  errors.push(
319
- `a mayRead hook is required on every undo policy — origin-read rights are a declared decision, never a default allow — missing: [${readless.join(', ')}]`,
336
+ `every undo policy needs a mayRead hook (or the app-wide default gate — registerUndoReadGate) — origin-read rights are a declared decision, never a default allow — missing: [${readless.join(', ')}]`,
320
337
  )
321
338
  if (!s.storage?.operationLedger)
322
339
  errors.push('the registered storage engine does not provide the operation-ledger capability — the kernel requires it')
package/src/state.ts CHANGED
@@ -23,7 +23,7 @@ import type { ProjectionHandler } from './projections.js'
23
23
  import type { QueryDefinition } from './queries.js'
24
24
  import type { TransitionRule } from './registry.js'
25
25
  import type { StoragePort } from './storage.js'
26
- import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy, CatalogRelease, CatalogRevisions, UndoHandler } from './types.js'
26
+ import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy, CatalogRelease, CatalogRevisions, UndoHandler, UndoMayRead } from './types.js'
27
27
 
28
28
  /** Registered projector — the app contract (AppProjector) collected into handler maps */
29
29
  export interface RegisteredProjector {
@@ -48,6 +48,9 @@ export interface KernelState {
48
48
  undoPolicies: Map<string, EventUndoPolicy>
49
49
  /** Undo handlers by id (registerUndoHandler) — domain-owned compensation planners */
50
50
  undoHandlers: Map<string, UndoHandler>
51
+ /** The app-wide default origin-read gate (registerUndoReadGate) — serves any undo policy that
52
+ * declares no mayRead of its own; null until registered (one per assembly) */
53
+ undoReadGate: UndoMayRead | null
51
54
  /** Event payload format versions per type (registerEventVersions) — absent = 1 */
52
55
  eventVersions: Map<string, number>
53
56
  /** The served catalog release declaration (registerCatalogRelease) — null when the app declares none */
@@ -134,6 +137,7 @@ export function freshKernelState(): KernelState {
134
137
  sealed: false,
135
138
  undoPolicies: new Map(),
136
139
  undoHandlers: new Map(),
140
+ undoReadGate: null,
137
141
  eventVersions: new Map(),
138
142
  catalogRelease: null,
139
143
  revisions: null,
package/src/storage.ts CHANGED
@@ -128,11 +128,12 @@ export interface StoragePort {
128
128
  /** Release the physical connection (optional) — file removal, e.g. test cleanup, requires it on platforms that lock open files */
129
129
  close?(): void
130
130
 
131
- /** Operation-ledger extension (optional capability — the close?() precedent). Engines that implement
132
- * it persist the kernel's event envelope (EventOperationMeta) beside the payload and serve the exact
133
- * lookups the undo contract needs. Engines without it keep working unchanged: the kernel runs in
134
- * an assembly without it refuses to boot — the undo APIs answer undo.storage_capability_missing only
135
- * to boot without it. Write methods here join the same serialized write lane as every other writer.
131
+ /** Operation-ledger extension — REQUIRED by the kernel's assembly check: an engine without it
132
+ * fails the boot (undo is part of the kernel contract). Engines that implement it persist the
133
+ * kernel's event envelope (EventOperationMeta) beside the payload and serve the exact lookups the
134
+ * undo contract needs. The field stays optional on the PORT (registerStorage accepts engines in
135
+ * earlier build stages; the seal is where completeness is demanded). Write methods here join the
136
+ * same serialized write lane as every other writer.
136
137
  *
137
138
  * Implementation requirements for engine authors (SQLite shape; other engines equivalently):
138
139
  * - a nullable metadata column beside the payload (JSON of EventOperationMeta) — legacy rows stay NULL
package/src/types.ts CHANGED
@@ -83,8 +83,8 @@ export interface CommandDefinition<I = any, O = any> {
83
83
  * result is checked against the output contract */
84
84
  execute: (input: I, identity: Identity) => Promise<{ events: DomainEvent[]; result: O }>
85
85
  /** Command contract version (semver) — the domain declares it for the whole contract
86
- * (input·output·refusal·permission·transition semantics). Required in strict mode; the catalog
87
- * publishes it and strict-mode writes carry it back (ContractMeta) */
86
+ * (input·output·refusal·permission·transition semantics). Required on every command (the seal
87
+ * refuses an undeclared version); the catalog publishes it and every write carries it back (ContractMeta) */
88
88
  version?: string
89
89
  /** Explicit revision for meaning changes no fingerprint can derive (functional refine bodies,
90
90
  * business-logic semantics). Bumped by the domain; folded into the command revision */
@@ -115,7 +115,7 @@ export interface EventOperationMeta {
115
115
  policyTarget?: string
116
116
  }
117
117
 
118
- /** The contract identity a strict-mode write carries beside the business input — the caller's view of
118
+ /** The contract identity every write carries beside the business input — the caller's view of
119
119
  * the command contract. Refused before execution when it no longer matches (gate.contract_changed /
120
120
  * gate.contract_required). Riding splitProtocolOptions, it never reaches the business schema. */
121
121
  export interface ContractMeta {
@@ -132,10 +132,12 @@ export interface ContractMeta {
132
132
  export type UndoMayRead = (source: SourceOperation, identity: Identity) => Promise<void>
133
133
 
134
134
  /** Undo policy per event type — supported (a handler plans the compensation) or explicitly unavailable
135
- * (a stable code + a concrete reason). Both kinds are declared; strict mode requires a policy for every
136
- * registered event type AND a mayRead hook on every policy — origin-read rights are a declared
137
- * decision, never a default allow. `roles` limits the policy's CATALOG exposure (absent = every
138
- * authenticated identity sees the policy entry; it never affects the mayRead verdict).
135
+ * (a stable code + a concrete reason). Both kinds are declared; the kernel requires a policy for every
136
+ * registered event type AND an origin-read decision for every policy — a `mayRead` hook on the policy
137
+ * itself, or the app-wide default gate registered once (registerUndoReadGate); a policy-level mayRead
138
+ * wins where present, and an assembly declaring neither fails the boot — origin-read rights are never
139
+ * a default allow. `roles` limits the policy's CATALOG exposure (absent = every authenticated
140
+ * identity sees the policy entry; it never affects the mayRead verdict).
139
141
  * Audit rows are never undo targets. */
140
142
  export type EventUndoPolicy =
141
143
  | { kind: 'supported'; handlerId: string; mayRead?: UndoMayRead; roles?: readonly Role[] }
@@ -195,21 +197,31 @@ export interface UndoPlan {
195
197
  blockers?: UndoPlanBlocker[]
196
198
  }
197
199
 
198
- /** Undo handler — owned by the domain. plan() is read-only (no business writes, no ledger appends, no
199
- * idempotency storage, no external effects) and runs inside one consistent read snapshot. */
200
+ /** Undo handler — owned by the domain. `compensationCommand` statically declares the ONE registered
201
+ * command this handler plans with: the kernel checks the current identity's access to it BEFORE the
202
+ * planner runs (an unauthorized identity never triggers plan computation — and never learns the
203
+ * blockers a plan would have named), the seal refuses a handler whose declared command is not
204
+ * registered, and a plan naming any other command is a defect (undo.plan_invalid). plan() is
205
+ * read-only (no business writes, no ledger appends, no idempotency storage, no external effects) and
206
+ * runs inside one consistent read snapshot. */
200
207
  export interface UndoHandler {
201
208
  id: string
202
209
  version: string
210
+ compensationCommand: string
203
211
  plan: (source: SourceOperation, identity: Identity) => Promise<UndoPlan>
204
- /** Optional per-source read permission (history-reading rights are business interpretation).
205
- * Absent = any identity that may run the compensation command may preview. Throw GateError to refuse. */
212
+ /** Optional per-source read refinement — runs AFTER the kernel's compensation-command access
213
+ * check, still before any state judgment (an identity without history rights learns nothing, not
214
+ * even whether a compensation exists). Throw GateError (stage 1~3) to refuse. */
206
215
  mayPreview?: (source: SourceOperation, identity: Identity) => Promise<void>
207
216
  }
208
217
 
209
218
  /** Preview of one undo, judged for the current user against the current state — static "a handler
210
- * exists" and "this call can run now" are different questions (status answers the latter). */
219
+ * exists" and "this call can run now" are different questions (status answers the latter).
220
+ * `denied` is the permission verdict (origin-read hook, handler gate, compensation-command role·
221
+ * delegation): like every permission refusal it carries no operation facts — no operationId, no
222
+ * processing state. */
211
223
  export interface UndoPreview {
212
- status: 'available' | 'warning' | 'blocked' | 'unavailable' | 'already_undone'
224
+ status: 'available' | 'warning' | 'blocked' | 'unavailable' | 'already_undone' | 'denied'
213
225
  sourceSeq: number
214
226
  operationId?: string
215
227
  handlerId?: string
package/src/undo.ts CHANGED
@@ -29,9 +29,10 @@ import { randomUUID } from 'node:crypto'
29
29
  import { currentIdentityOf, unauthenticated } from './auth.js'
30
30
  import { maskSecrets, storageOf, type LedgerRow, type OperationLedgerCapability } from './storage.js'
31
31
  import { appPolicy } from './policy.js'
32
- import { completeAssembly, lookupCommand, undoHandlerOf, undoPolicyOf } from './registry.js'
32
+ import { completeAssembly, lookupCommand, undoHandlerOf, undoPolicyOf, undoReadGateOf } from './registry.js'
33
33
  import { commandRevisionOf, responseMetaOf } from './catalog.js'
34
34
  import { canonicalJson } from './canonical.js'
35
+ import { ledgerEventVersionOf, operationMetaOf } from './operation-meta.js'
35
36
  import {
36
37
  assertLiveRoleAllows,
37
38
  assertRecordedDelegationCovers,
@@ -40,7 +41,7 @@ import {
40
41
  policyRefusalGateError,
41
42
  unprovableRefusal,
42
43
  } from './permissions.js'
43
- import { commandAccessOf, roleAllowsCommand } from './visibility.js'
44
+ import { commandAccessRefusalOf } from './visibility.js'
44
45
  import { reauthorize, validateDynamic, validateStatic } from './gate.js'
45
46
  import { refusalShapeOf, toGateError } from './gate-results.js'
46
47
  import type { ExecutionRefusal, ExecutionResult, ExecutionSuccess } from './gate-results.js'
@@ -53,33 +54,32 @@ import type { Identity, SourceOperation, UndoHandler, UndoPlan, UndoPlanChange,
53
54
  /** The pseudo-command undo attempts are recorded under (audit·idempotency) */
54
55
  const UNDO_COMMAND = 'undo'
55
56
 
57
+ /** The maximum sourceSeqs one undoStatus call accepts — a larger bundle is a stage-4 INPUT refusal
58
+ * (gate.schema_invalid), never a silent truncation; the caller pages. */
59
+ export const UNDO_STATUS_MAX_SEQS = 100
60
+
56
61
  function capability(): OperationLedgerCapability {
57
62
  const cap = storageOf().operationLedger
58
63
  if (!cap)
64
+ // Defense in depth: the assembly check (completeAssembly) already refuses engines without the
65
+ // capability at boot, so every undo entry point reaching here implies it exists. Kept because the
66
+ // port types the field optional — a future entry point added without the boot check must fail
67
+ // loudly here, never degrade to partial undo behavior.
59
68
  throw new GateError(
60
69
  0,
61
70
  'registry',
62
- 'Undo requires the operation-ledger storage capability — the registered engine does not provide it (compat mode answers this clearly; strict mode refuses to boot)',
71
+ 'Undo requires the operation-ledger storage capability — the registered engine does not provide it',
63
72
  { code: 'undo.storage_capability_missing' },
64
73
  )
65
74
  return cap
66
75
  }
67
76
 
68
- const parseMeta = (row: LedgerRow): { operationId?: string; commandName?: string; commandVersion?: string; commandRevision?: string; eventVersion?: number; policyTarget?: string } | undefined => {
69
- if (!row.meta) return undefined
70
- try {
71
- return JSON.parse(row.meta)
72
- } catch {
73
- return undefined
74
- }
75
- }
76
-
77
77
  /** Resolves the exact source operation behind a sequence — the whole operation, never a substitute row */
78
78
  async function resolveSource(cap: OperationLedgerCapability, sourceSeq: number): Promise<{ source: SourceOperation; operationId: string }> {
79
79
  const row = await cap.domainRowBySeq(sourceSeq)
80
80
  if (!row || row.kind !== 'domain')
81
81
  throw new GateError(0, 'registry', `No domain event at seq ${sourceSeq} (audit rows are never undo targets)`, { code: 'undo.source_not_found' })
82
- const meta = parseMeta(row)
82
+ const meta = operationMetaOf(row)
83
83
  if (meta?.operationId) {
84
84
  const rows = await cap.eventsOfOperation(meta.operationId)
85
85
  return { source: buildSource(rows.length > 0 ? rows : [row], sourceSeq, false), operationId: meta.operationId }
@@ -89,7 +89,7 @@ async function resolveSource(cap: OperationLedgerCapability, sourceSeq: number):
89
89
  }
90
90
 
91
91
  function buildSource(rows: LedgerRow[], sourceSeq: number, legacy: boolean): SourceOperation {
92
- const first = parseMeta(rows[0])
92
+ const first = operationMetaOf(rows[0])
93
93
  return {
94
94
  operationId: legacy ? `legacy:${sourceSeq}` : first?.operationId ?? `legacy:${sourceSeq}`,
95
95
  sourceSeq,
@@ -98,10 +98,7 @@ function buildSource(rows: LedgerRow[], sourceSeq: number, legacy: boolean): Sou
98
98
  ...(first?.commandVersion ? { commandVersion: first.commandVersion } : {}),
99
99
  ...(first?.commandRevision ? { commandRevision: first.commandRevision } : {}),
100
100
  events: rows.map((r) => {
101
- const meta = parseMeta(r)
102
- // envelope first, then the row's version column — the SAME precedence replay uses, so the
103
- // planner and a rebuilding projection never disagree about which format version a row carries
104
- const eventVersion = meta?.eventVersion !== undefined ? meta.eventVersion : r.version
101
+ const eventVersion = ledgerEventVersionOf(r)
105
102
  return {
106
103
  seq: r.seq,
107
104
  type: r.type,
@@ -135,14 +132,17 @@ const jsonValueOf = (v: unknown): boolean => {
135
132
  * off-shape plan is a loud defect, never a best-effort interpretation. The same completeness a
136
133
  * command's output contract enforces: a malformed plan never reaches the hash, the preview or the
137
134
  * execution. A blocked plan (blockers present) needs no compensation command — there is nothing to
138
- * execute. */
139
- function validateUndoPlan(plan: UndoPlan): void {
135
+ * execute. A plannable command must be exactly the handler's DECLARED compensation command — the
136
+ * kernel judged plan-entry rights against that declaration, so a different name would dodge it. */
137
+ function validateUndoPlan(plan: UndoPlan, handler: UndoHandler): void {
140
138
  const invalid = (why: string) =>
141
139
  new GateError(8, 'execute', `The undo handler returned an invalid plan — ${why}`, { code: 'undo.plan_invalid' })
142
140
  if (!plan || typeof plan !== 'object') throw invalid('not an object')
143
141
  const hasBlockers = Array.isArray(plan.blockers) && plan.blockers.length > 0
144
142
  if (!hasBlockers) {
145
143
  if (typeof plan.command !== 'string' || plan.command.length === 0) throw invalid('command missing')
144
+ if (plan.command !== handler.compensationCommand)
145
+ throw invalid(`the plan's command '${plan.command}' is not the handler's declared compensation command '${handler.compensationCommand}'`)
146
146
  if (!plan.input || typeof plan.input !== 'object' || Array.isArray(plan.input)) throw invalid('input must be a plain object')
147
147
  if (!lookupCommand(plan.command)) throw invalid(`the compensation command is not registered: ${plan.command}`)
148
148
  }
@@ -212,8 +212,10 @@ function planHashOf(
212
212
  }
213
213
 
214
214
  /** Everything a preview computes — the public projection plus the internals execution re-checks.
215
- * plan·handler are present only when a compensation is actually planned (status available|warning);
216
- * the judgment-only answers (unavailable·blocked·already_undone) carry the preview alone.
215
+ * plan·handler·parsedInput are present only when a compensation is actually planned (status
216
+ * available|warning); the judgment-only answers (unavailable·blocked·already_undone) carry the
217
+ * preview alone. parsedInput is the STATIC-CHECKED, schema-normalized compensation input — execution
218
+ * reuses it instead of re-running the identical static validation inside the same transaction.
217
219
  * permissionRefusal is set when a PERMISSION·GATE check refused (origin-read hook, role, delegation,
218
220
  * app-policy target — stages 1~3): the redelivery rights check throws on this flag, so the verdict
219
221
  * never depends on error-code spelling (codes are domain vocabulary). Business judgments (a later
@@ -222,14 +224,18 @@ interface ComputedPlan {
222
224
  preview: UndoPreview
223
225
  plan?: UndoPlan
224
226
  handler?: UndoHandler
227
+ parsedInput?: unknown
225
228
  operationId: string
226
229
  permissionRefusal?: GateError
227
230
  }
228
231
 
229
- /** The operation-level read gate + undo consensus, judged over EVERY event type of the operation —
230
- * shared by preview and status so ANY event row of one operation answers the SAME conclusion (the
231
- * status is a per-OPERATION lookup; the seq the caller picked is only the anchor). Read refusals
232
- * carry no operation facts; the consensus mirrors preview's rules: a type without a policy or an
232
+ /** The origin-read gates + undo consensus, judged over EVERY event type of the operation — the ONE
233
+ * judgment preview and status share, so ANY event row of one operation answers the SAME conclusion
234
+ * (the status is a per-OPERATION lookup; the seq the caller picked is only the anchor). Three gates
235
+ * run before any state is consulted: the policy's operation-level mayRead (whatever the policy kind),
236
+ * then — for a supported consensus — the DECLARED compensation command's access check, then the
237
+ * handler's plan-specific mayPreview. A refusal from any gate returns as readRefusal — no operation
238
+ * facts travel with it. The consensus mirrors preview's rules: a type without a policy or an
233
239
  * unavailable type makes the whole operation unavailable, supported types must agree on ONE handler. */
234
240
  async function readGateAndConsensus(
235
241
  source: SourceOperation,
@@ -246,7 +252,8 @@ async function readGateAndConsensus(
246
252
  > {
247
253
  const types = [...new Set(source.events.map((e) => e.type))]
248
254
  for (const type of types) {
249
- const readHook = undoPolicyOf(type)?.mayRead
255
+ // the policy's own hook decides; policies without one fall back to the app-wide default gate
256
+ const readHook = undoPolicyOf(type)?.mayRead ?? undoReadGateOf()
250
257
  if (readHook) {
251
258
  try {
252
259
  await readHook(source, identity)
@@ -256,6 +263,9 @@ async function readGateAndConsensus(
256
263
  }
257
264
  }
258
265
  const policies = types.map((type) => ({ type, policy: undoPolicyOf(type) }))
266
+ // Reachable even though the boot demands a policy for every REGISTERED event type: a re-assembly
267
+ // may retire an event type entirely (contract and policy both gone) while old ledger rows of it
268
+ // remain — those rows answer "no policy" (same defense-in-depth stance as capability())
259
269
  if (policies.some((x) => !x.policy))
260
270
  return { consensus: { kind: 'unavailable', code: 'undo.unavailable', reason: 'No undo policy registered for this event type' } }
261
271
  const unsupported = policies.find((x) => x.policy?.kind === 'unavailable')
@@ -263,6 +273,29 @@ async function readGateAndConsensus(
263
273
  return { consensus: { kind: 'unavailable', code: unsupported.policy.code, reason: unsupported.policy.reason } }
264
274
  const handlerIds = [...new Set(policies.map((x) => (x.policy as unknown as { handlerId: string }).handlerId))]
265
275
  if (handlerIds.length > 1) return { consensus: { kind: 'mixed' } }
276
+ // Compensation-command access — the handler's DECLARED command, judged HERE so preview and status
277
+ // answer the SAME verdict (a status row must not promise a handler to an identity that cannot run
278
+ // the compensation). Before the handler's own hook and before ANY state judgment (already_undone
279
+ // included): an identity that may not run the compensation learns nothing about the operation —
280
+ // not its processing state, not the blockers a plan would have named. A plan cannot dodge this —
281
+ // naming another command is a plan defect (validateUndoPlan). The stage·code-accurate refusal
282
+ // comes from the single derivation in visibility.ts (commandAccessRefusalOf); input-dependent
283
+ // checks (the actual target) stay on the planner's output, through validateStatic in computePreview.
284
+ // Both the handler and its declared command resolve post-seal (the consistency check refuses
285
+ // dangling references).
286
+ const handler = undoHandlerOf(handlerIds[0])!
287
+ const accessRefusal = commandAccessRefusalOf(lookupCommand(handler.compensationCommand)!, identity, 'compensation command')
288
+ if (accessRefusal) return { readRefusal: accessRefusal }
289
+ // Plan-specific read permission (the supported handler's optional hook) — runs AFTER the kernel's
290
+ // compensation-command check, still before any state judgment. ANY refusal here is a permission
291
+ // refusal — whatever its code spells.
292
+ if (handler.mayPreview) {
293
+ try {
294
+ await handler.mayPreview(source, identity)
295
+ } catch (err) {
296
+ return { readRefusal: toGateError(err, 3, 'policy') }
297
+ }
298
+ }
266
299
  return { consensus: { kind: 'supported', handlerId: handlerIds[0] } }
267
300
  }
268
301
 
@@ -270,12 +303,13 @@ async function computePreview(sourceSeq: number, identity: Identity): Promise<Co
270
303
  const cap = capability()
271
304
  const { source, operationId } = await resolveSource(cap, sourceSeq)
272
305
 
273
- // Origin-read rights FIRST — before ANY branch (unavailable·missing·mixed·supported·already_undone)
274
- // answers a fact about the operation: the POLICY's mayRead hook decides whether this identity may
275
- // learn anything at all, whatever the undo answer would have been. The same shared judgment answers
276
- // undoStatus — one operation, one conclusion, whatever row was selected. Supported handlers
277
- // additionally gate through their own mayPreview (plan-specific rights); this hook is the
278
- // operation-level gate. A refusal carries no operation facts — not the id, not the state, not the policy.
306
+ // Origin-read rights and the compensation-command verdict FIRST — before ANY branch
307
+ // (unavailable·missing·mixed·supported·already_undone) answers a fact about the operation. The read
308
+ // gates (the policy's operation-level mayRead, then — for a supported consensus — the declared
309
+ // compensation command's access check, then the handler's plan-specific mayPreview) decide whether
310
+ // this identity may learn anything at all, whatever the undo answer would have been. The same
311
+ // shared judgment answers undoStatus — one operation, one conclusion, whatever row was selected.
312
+ // A refusal carries no operation facts — not the id, not the state, not the policy.
279
313
  const gated = await readGateAndConsensus(source, identity)
280
314
  if (gated.readRefusal) return permissionRefusalOf(sourceSeq, gated.readRefusal, operationId)
281
315
 
@@ -286,23 +320,12 @@ async function computePreview(sourceSeq: number, identity: Identity): Promise<Co
286
320
  return judgmentOnly('blocked', sourceSeq, operationId, 'undo.operation_mixed_policies', 'The operation mixes event types with different undo handlers — a single compensation cannot cover it')
287
321
  const handler = undoHandlerOf(gated.consensus.handlerId)!
288
322
 
289
- // Plan-specific read permission (the handler's hook) — still before any state judgment: an identity
290
- // without history rights learns nothing, not even whether a compensation exists. Strict assemblies
291
- // require the hook on every handler. ANY refusal here is a permission refusal — whatever its code says.
292
- if (handler.mayPreview) {
293
- try {
294
- await handler.mayPreview(source, identity)
295
- } catch (err) {
296
- return permissionRefusalOf(sourceSeq, toGateError(err, 3, 'policy'), operationId)
297
- }
298
- }
299
-
300
323
  // One successful compensation per source operation — checked again inside the execution lock
301
324
  if ((await cap.compensationsOf(operationId)).length > 0)
302
325
  return { operationId, preview: { status: 'already_undone', sourceSeq, operationId, changes: [], preserved: [], losses: [], blockers: [] } }
303
326
 
304
327
  const plan = await handler.plan(source, identity)
305
- validateUndoPlan(plan)
328
+ validateUndoPlan(plan, handler)
306
329
 
307
330
  // A blocked plan answers as blocked — no compensation command to resolve or permit
308
331
  if ((plan.blockers ?? []).length > 0)
@@ -311,46 +334,37 @@ async function computePreview(sourceSeq: number, identity: Identity): Promise<Co
311
334
  preview: { status: 'blocked', sourceSeq, operationId, handlerId: handler.id, changes: [], preserved: [], losses: [], blockers: plan.blockers! },
312
335
  }
313
336
 
314
- // Compensation-execution permission — the CURRENT identity must be allowed to run the compensation,
315
- // judged on the planner's ACTUAL input: catalog visibility alone never means executable. The same
316
- // static gate checks a direct call would face (delegation·role·app-policy target·schema), then the
317
- // read-only dynamic checks (preconditions·invariants·transitions) — so 'available' means a call NOW
318
- // would pass stages 1~7, not merely that the command exists.
337
+ // Compensation-execution permission on the planner's ACTUAL input: the identity-level access to the
338
+ // declared command was judged in the shared gates above; visibility alone never means executable.
339
+ // The same static gate checks a direct call would face (delegation·app-policy target·schema), then
340
+ // the read-only dynamic checks (preconditions·invariants·transitions) — so 'available' means a call
341
+ // NOW would pass stages 1~7, not merely that the command exists.
319
342
  const def = lookupCommand(plan.command)!
320
- const access = commandAccessOf(def, identity)
321
- if (!access.visible)
322
- return permissionRefusalOf(
323
- sourceSeq,
324
- new GateError(3, 'policy', `The compensation command '${plan.command}' is not allowed for the current identity`, {
325
- code: 'gate.role_denied',
326
- }),
327
- operationId,
328
- )
329
343
  let parsedInput: unknown
330
344
  try {
331
345
  parsedInput = await validateStatic(def, plan.command, plan.input, identity)
332
346
  await validateDynamic(def, parsedInput, identity)
333
347
  } catch (err) {
334
348
  const refusal = toGateError(err, 3, 'policy')
335
- // stages 1~3 are permission·policy refusals (whatever the code spells); stage 4 is a planner
336
- // output defect, stages 5~7 are business judgments against the current state — only the first
337
- // kind withholds a stored result from its owner
338
- const computed: ComputedPlan = {
339
- ...judgmentOnly('blocked', sourceSeq, operationId, refusal.code ?? 'policy.denied', refusal.message),
340
- ...(refusal.stage <= 3 ? { permissionRefusal: refusal } : {}),
341
- }
342
- return computed
349
+ // stages 1~3 are permission·policy refusals (whatever the code spells) — they answer `denied`
350
+ // like every other permission refusal; stage 4 is a planner output defect, stages 5~7 are
351
+ // business judgments against the current state — only the first kind withholds a stored result
352
+ // from its owner
353
+ if (refusal.stage <= 3) return permissionRefusalOf(sourceSeq, refusal, operationId)
354
+ return judgmentOnly('blocked', sourceSeq, operationId, refusal.code ?? 'policy.denied', refusal.message)
343
355
  }
344
356
 
345
357
  const commandVersion = def.version ?? ''
346
358
  const commandRevision = commandRevisionOf(def.name) ?? ''
347
359
  const blockers = plan.blockers ?? []
348
360
  const losses = plan.losses ?? []
349
- const status: UndoPreview['status'] = blockers.length > 0 ? 'blocked' : losses.length > 0 ? 'warning' : 'available'
361
+ // blocked plans returned above — only available|warning remain here
362
+ const status: UndoPreview['status'] = losses.length > 0 ? 'warning' : 'available'
350
363
  return {
351
364
  operationId,
352
365
  handler,
353
366
  plan,
367
+ parsedInput,
354
368
  preview: {
355
369
  status,
356
370
  sourceSeq,
@@ -380,13 +394,15 @@ const judgmentOnly = (
380
394
  preview: { status, sourceSeq, operationId, changes: [], preserved: [], losses: [], blockers: [{ code, reason }] },
381
395
  })
382
396
 
383
- /** A PERMISSION refusal — the identity learns that it may not read this operation, and nothing else:
384
- * no operation id, no processing state, no policy metadata. Whatever the hook's code spells, the
385
- * redelivery rights check refuses on this shape (the flag, not the spelling). The operationId stays
386
- * INTERNAL (the redelivery check may still need it) — it never reaches the published preview. */
397
+ /** A PERMISSION refusal — the identity learns that it may not read or compensate this operation, and
398
+ * nothing else: no operation id, no processing state, no policy metadata. The preview status is
399
+ * `denied` — the same vocabulary undoStatus answers with for the same judgment. Whatever the hook's
400
+ * code spells, the redelivery rights check refuses on this shape (the flag, not the spelling). The
401
+ * operationId stays INTERNAL (the redelivery check may still need it) — it never reaches the
402
+ * published preview. */
387
403
  const permissionRefusalOf = (sourceSeq: number, refusal: GateError, operationId: string): ComputedPlan => ({
388
404
  operationId,
389
- preview: { status: 'blocked', sourceSeq, changes: [], preserved: [], losses: [], blockers: [{ code: refusal.code ?? 'policy.denied', reason: refusal.message }] },
405
+ preview: { status: 'denied', sourceSeq, changes: [], preserved: [], losses: [], blockers: [{ code: refusal.code ?? 'policy.denied', reason: refusal.message }] },
390
406
  permissionRefusal: refusal,
391
407
  })
392
408
 
@@ -394,10 +410,11 @@ const permissionRefusalOf = (sourceSeq: number, refusal: GateError, operationId:
394
410
  * The account must be valid NOW, and the permission view must still hold. Two shapes:
395
411
  * - not yet compensated: the preview pipeline is re-derived read-only and its PERMISSION refusal
396
412
  * (the internal flag, independent of error-code spelling) refuses the redelivery;
397
- * - already compensated (no live plan exists): the STORED compensation's envelope decides — its
398
- * commandName and target aggregate are re-checked against the current role·delegation·policy.
399
- * When the compensation command itself was removed, no material can re-prove the rights — the
400
- * stored result is refused clearly, never handed out and never re-run as new work.
413
+ * - a compensation is stored: its RECORDED envelope decides — commandName and recorded target are
414
+ * re-checked against the current role·delegation·policy, whatever the CURRENT policy consensus
415
+ * says (supported·unavailable·mixed alike — the policy may have moved since the compensation
416
+ * was stored). When the compensation command itself was removed, no material can re-prove the
417
+ * rights — the stored result is refused clearly, never handed out and never re-run as new work.
401
418
  * Business blockers (a later change, an unavailable policy, plan defects) never hide a result the
402
419
  * caller already owns. Never re-runs the original business schemas; the stored hash already pins
403
420
  * the request identity. */
@@ -410,11 +427,14 @@ async function assertUndoReadRights(sourceSeq: number, identity: Identity): Prom
410
427
  const computed = await computePreview(sourceSeq, judged)
411
428
  if (computed.permissionRefusal) throw computed.permissionRefusal
412
429
 
413
- if (computed.preview.status === 'already_undone') {
414
- const cap = capability()
415
- const compSeq = (await cap.compensationsOf(computed.operationId))[0]
416
- const row = compSeq !== undefined ? await cap.domainRowBySeq(compSeq) : undefined
417
- const meta = row ? parseMeta(row) : undefined
430
+ // A STORED compensation re-proves on its RECORDED envelope whatever the CURRENT policy consensus
431
+ // says — the policy may have flipped unavailable or mixed since the compensation was stored, and a
432
+ // consensus-first answer would hand the stored result to an identity whose rights no longer hold.
433
+ // The stored fact (the compensation exists), not the preview's status, decides whether this step runs.
434
+ const compSeq = (await capability().compensationsOf(computed.operationId))[0]
435
+ if (compSeq !== undefined) {
436
+ const row = await capability().domainRowBySeq(compSeq)
437
+ const meta = row ? operationMetaOf(row) : undefined
418
438
  const def = meta?.commandName ? lookupCommand(meta.commandName) : undefined
419
439
  if (!def || !row)
420
440
  throw new GateError(
@@ -442,12 +462,11 @@ async function assertUndoReadRights(sourceSeq: number, identity: Identity): Prom
442
462
  }
443
463
  }
444
464
 
445
- /** Wraps a computation in the engine's consistent read snapshot when it provides one — a preview is one
446
- * point-in-time view, never a collage of reads from different moments. Engines without the capability
447
- * (the memory fixture) run the closure directly. */
465
+ /** Wraps a computation in the engine's consistent read snapshot — a preview is one point-in-time
466
+ * view, never a collage of reads from different moments. Every engine that passes the boot check
467
+ * provides the capability (see capability()'s defense note). */
448
468
  async function withReadSnapshot<T>(fn: () => Promise<T>): Promise<T> {
449
- const cap = storageOf().operationLedger
450
- return cap ? cap.readSnapshot(fn) : fn()
469
+ return capability().readSnapshot(fn)
451
470
  }
452
471
 
453
472
  /** Preview one undo — a read-only judgment for the current identity; never a promise that a later
@@ -462,49 +481,51 @@ export async function previewUndo(input: { sourceSeq: number }, identity: Identi
462
481
  }
463
482
  }
464
483
 
484
+ /** One row of undoStatus — per-seq support·processing state (the requested seq stays the anchor;
485
+ * the OPERATION behind it is judged as a whole through the shared read gates + consensus). A denied
486
+ * row carries the refusal code and nothing else. */
487
+ export interface UndoStatusRow {
488
+ sourceSeq: number
489
+ status: 'supported' | 'unavailable' | 'blocked' | 'already_undone' | 'not_found' | 'denied'
490
+ operationId?: string
491
+ legacy?: boolean
492
+ handlerId?: string
493
+ code?: string
494
+ reason?: string
495
+ }
496
+
465
497
  /** Per-seq support·processing state — the list-view companion (buttons are not execution guarantees;
466
- * what really runs is decided by preview and execution). Origin-read rights gate the ANSWER: a denied
467
- * identity learns nothing about the operation — not its existence, not its processing state. */
498
+ * what really runs is decided by preview and execution). The shared gates gate the ANSWER: origin-read
499
+ * rights, then — for a supported consensus — the DECLARED compensation command's access check and the
500
+ * handler's hook. A denied identity learns nothing about the operation — not its existence, not its
501
+ * processing state, not its handler. */
468
502
  export async function undoStatus(
469
503
  input: { sourceSeqs: number[] },
470
504
  identity: Identity | null,
471
- ): Promise<
472
- | {
473
- ok: true
474
- results: Array<{
475
- sourceSeq: number
476
- status: 'supported' | 'unavailable' | 'blocked' | 'already_undone' | 'not_found' | 'denied'
477
- operationId?: string
478
- legacy?: boolean
479
- handlerId?: string
480
- code?: string
481
- reason?: string
482
- }>
483
- }
484
- | ExecutionRefusal
485
- > {
505
+ ): Promise<{ ok: true; results: UndoStatusRow[] } | ExecutionRefusal> {
486
506
  completeAssembly()
487
507
  if (!identity) return unauthenticated('Login required — undo status is not public')
488
508
  try {
509
+ // the bundle cap is an input contract — over the limit the WHOLE call refuses (fix the input),
510
+ // never a partial answer that quietly drops the tail
511
+ if ((input.sourceSeqs?.length ?? 0) > UNDO_STATUS_MAX_SEQS)
512
+ throw new GateError(
513
+ 4,
514
+ 'schema',
515
+ `sourceSeqs carries ${input.sourceSeqs.length} entries — at most ${UNDO_STATUS_MAX_SEQS} per call (page the rest)`,
516
+ { code: 'gate.schema_invalid' },
517
+ )
489
518
  const cap = capability()
490
519
  const results = await withReadSnapshot(async () => {
491
- const out: Array<{
492
- sourceSeq: number
493
- status: 'supported' | 'unavailable' | 'blocked' | 'already_undone' | 'not_found' | 'denied'
494
- operationId?: string
495
- legacy?: boolean
496
- handlerId?: string
497
- code?: string
498
- reason?: string
499
- }> = []
500
- for (const seq of (input.sourceSeqs ?? []).slice(0, 100)) {
520
+ const out: UndoStatusRow[] = []
521
+ for (const seq of input.sourceSeqs ?? []) {
501
522
  const row = await cap.domainRowBySeq(seq)
502
523
  if (!row || row.kind !== 'domain') {
503
524
  out.push({ sourceSeq: seq, status: 'not_found' })
504
525
  continue
505
526
  }
506
527
  // the seq is only the ANCHOR — the OPERATION behind it is judged as a whole (the same shared
507
- // read gate + consensus preview uses), so every event row of one operation answers the same
528
+ // read gates + consensus preview uses), so every event row of one operation answers the same
508
529
  // conclusion. The response keeps the requested seq.
509
530
  const { source, operationId } = await resolveSource(cap, seq)
510
531
  const gated = await readGateAndConsensus(source, identity)
@@ -512,20 +533,6 @@ export async function undoStatus(
512
533
  out.push({ sourceSeq: seq, status: 'denied', code: gated.readRefusal.code ?? 'policy.denied' })
513
534
  continue
514
535
  }
515
- // the supported handler's mayPreview (the plan-specific read right) — a refusal answers
516
- // 'denied' with no operation facts, exactly like the operation-level gate
517
- if (gated.consensus.kind === 'supported') {
518
- const handler = undoHandlerOf(gated.consensus.handlerId)
519
- if (handler?.mayPreview) {
520
- try {
521
- await handler.mayPreview(source, identity)
522
- } catch (err) {
523
- const refusal = toGateError(err, 3, 'policy')
524
- out.push({ sourceSeq: seq, status: 'denied', code: refusal.code ?? 'policy.denied' })
525
- continue
526
- }
527
- }
528
- }
529
536
  const undone = (await cap.compensationsOf(operationId)).length > 0
530
537
  out.push({
531
538
  sourceSeq: seq,
@@ -595,7 +602,11 @@ export async function executeUndo(
595
602
  throw new GateError(3, 'policy', 'Identity invalid at execution time — log in again', { code: 'auth.relogin_required' })
596
603
 
597
604
  const computed = await computePreview(input.sourceSeq, current)
598
- const { preview, plan, handler, operationId } = computed
605
+ const { preview, plan, handler, parsedInput, operationId } = computed
606
+ // A permission refusal answers AS the permission refusal it is — its own stage and code (1~3,
607
+ // e.g. gate.role_denied·gate.delegation_denied·a read-gate code), never re-wrapped as a stage-8
608
+ // execution error. Business blockers (a later change, plan defects) stay stage-8 undo refusals.
609
+ if (computed.permissionRefusal) throw computed.permissionRefusal
599
610
  if (preview.status === 'already_undone')
600
611
  throw new GateError(8, 'execute', `The source operation already has a successful compensation (seq ${input.sourceSeq}) — compensate that compensation instead`, { code: 'undo.already_undone' })
601
612
  if (preview.status === 'unavailable' || preview.status === 'blocked') {
@@ -615,12 +626,19 @@ export async function executeUndo(
615
626
  { code: 'undo.confirmation_required' },
616
627
  )
617
628
  // Past the guards a compensation exists — narrow the optional internals for the pipeline below
618
- if (!plan || !handler) throw new GateError(8, 'execute', 'No compensation plan to execute', { code: 'undo.plan_invalid' })
629
+ if (!plan || !handler || parsedInput === undefined)
630
+ throw new GateError(8, 'execute', 'No compensation plan to execute', { code: 'undo.plan_invalid' })
619
631
 
620
632
  // The compensation passes the FULL gate pipeline, inside this transaction — same checks as any
621
- // write, no bypass lane, no nested transaction (runCommand is the shared transaction-internal core)
633
+ // write, no bypass lane, no nested transaction (runCommand is the shared transaction-internal
634
+ // core). The static checks (schema·delegation·role·policy) are NOT repeated here: computePreview
635
+ // ran them on the same input against the same identity inside this same transaction moments
636
+ // earlier, and nothing between then and here mutates anything (the hash·loss guards are pure), so
637
+ // a repeat would answer identically — its parsed output is threaded through ComputedPlan instead.
638
+ // validateDynamic IS repeated deliberately: it must run with the REAUTHORIZED identity (fresh
639
+ // role·scopes from reauthorize), while the preview's run judged the request-start identity —
640
+ // invariants may consult identity scopes, so the execution-side run is not the preview's in disguise.
622
641
  const def = lookupCommand(plan.command)!
623
- const parsedInput = await validateStatic(def, plan.command, plan.input, current)
624
642
  const reauthed = await reauthorize(def, plan.command, parsedInput, current)
625
643
  await validateDynamic(def, parsedInput, reauthed)
626
644
  const op: OperationContext = {
package/src/visibility.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  * with the app (registerRoles · app policy). Delegation target restrictions surface the raw scope
16
16
  * suffixes — interpreting what a target names is the reader's (app policy's) job.
17
17
  */
18
- import type { CommandDefinition, Identity, Role } from './types.js'
18
+ import { GateError, type CommandDefinition, type Identity, type Role } from './types.js'
19
19
  import type { TransitionRule } from './registry.js'
20
20
  import { allCommands, allTransitionMachines, catalogMeta } from './registry.js'
21
21
  import { allQueries, type QueryDefinition } from './queries.js'
@@ -44,6 +44,22 @@ export type CommandRestriction =
44
44
 
45
45
  export type CommandAccess = { visible: false } | { visible: true; restriction?: CommandRestriction }
46
46
 
47
+ /** The delegation entry decision behind the visibility answer and the refusal derivation — the ONE
48
+ * place the entry rules live (command selection via delegationScopeEntries; a target-restricted-only
49
+ * entry set never covers a target-free command, because the gate extracts no target from it) */
50
+ function delegationViewOf(
51
+ del: NonNullable<Identity['delegation']>,
52
+ def: CommandDefinition<any>,
53
+ ): { visible: false } | { visible: true; targets?: string[] } {
54
+ const entries = delegationScopeEntries(del.scopes, def.name)
55
+ if (entries.length === 0) return { visible: false }
56
+ if (!entries.some((sc) => !sc.includes(':'))) {
57
+ if (def.scope === 'none') return { visible: false }
58
+ return { visible: true, targets: entries.map((sc) => sc.slice(sc.indexOf(':') + 1)) }
59
+ }
60
+ return { visible: true }
61
+ }
62
+
47
63
  /** Whether (and under what restriction) an identity may be told about a command. Pure — no input,
48
64
  * no targetOf, no policy call: a delegation with only target-restricted entries is announced as
49
65
  * restricted rather than proven per-target (proving needs an input; the gate re-checks at execution).
@@ -54,19 +70,40 @@ export function commandAccessOf(def: CommandDefinition<any>, identity: Identity
54
70
  if (!identity) return { visible: false }
55
71
  if (!roleAllowsCommand(def, identity.role)) return { visible: false }
56
72
  if (identity.delegation) {
57
- const entries = delegationScopeEntries(identity.delegation.scopes, def.name)
58
- if (entries.length === 0) return { visible: false }
59
- if (!entries.some((sc) => !sc.includes(':'))) {
60
- if (def.scope === 'none') return { visible: false }
73
+ const view = delegationViewOf(identity.delegation, def)
74
+ if (!view.visible) return { visible: false }
75
+ if (view.targets)
61
76
  return {
62
77
  visible: true,
63
- restriction: { type: 'delegation-targets', targets: entries.map((sc) => sc.slice(sc.indexOf(':') + 1)) },
78
+ restriction: { type: 'delegation-targets', targets: view.targets },
64
79
  }
65
- }
66
80
  }
67
81
  return def.scope !== 'none' ? { visible: true, restriction: { type: 'target-policy' } } : { visible: true }
68
82
  }
69
83
 
84
+ /** The refusal for a command this identity may not approach at all — the SAME internal rules
85
+ * commandAccessOf applies (role vs delegation scope entries), derived in this one place so gate-adjacent
86
+ * checks (undo's plan-entry gate) answer with the accurate stage·code without re-stating them.
87
+ * Undefined when the command IS accessible; `subject` only shapes the sentence (e.g. 'compensation
88
+ * command'). Pure, like every visibility derivation. */
89
+ export function commandAccessRefusalOf(
90
+ def: CommandDefinition<any>,
91
+ identity: Identity | null,
92
+ subject = 'command',
93
+ ): GateError | undefined {
94
+ if (commandAccessOf(def, identity).visible) return undefined
95
+ if (identity?.delegation && !delegationViewOf(identity.delegation, def).visible)
96
+ return new GateError(
97
+ 2,
98
+ 'delegation',
99
+ `The ${subject} '${def.name}' is outside this delegation's scopes — this token's scopes: ${identity.delegation.scopes.join(', ')}`,
100
+ { code: 'gate.delegation_denied' },
101
+ )
102
+ return new GateError(3, 'policy', `The ${subject} '${def.name}' is not allowed for the current identity`, {
103
+ code: 'gate.role_denied',
104
+ })
105
+ }
106
+
70
107
  /** Personal catalog guidance — catalogMeta() entries for the commands this identity may use,
71
108
  * annotated with the target restriction. catalogMeta() and allCommands() walk the same ordered
72
109
  * registry, so indexes pair 1:1. Deriving writes nothing (registry·ledger·audit untouched) */