@sudoke/kernel 0.3.1 → 0.4.0

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/src/undo.ts ADDED
@@ -0,0 +1,671 @@
1
+ /**
2
+ * Undo (restore) — the kernel's common compensation contract.
3
+ *
4
+ * Undo is a NEW WRITE, never a rewrite: the original ledger rows stay untouched, the compensation is one
5
+ * registered command that re-enters the full gate (schema·policy·preconditions·invariants·transitions·
6
+ * output·event contracts), and the compensation events carry the undo linkage on their envelope.
7
+ *
8
+ * Shape of the flow:
9
+ * - previewUndo({sourceSeq}) — resolves the exact source operation (any event row of an operation
10
+ * resolves to the WHOLE operation; partial undo does not exist), checks origin-read and
11
+ * compensation-execution permissions for the CURRENT identity, runs the domain planner read-only
12
+ * inside one consistent read snapshot, and answers with the common preview shape plus a server-keyed
13
+ * plan hash. Statuses are judged for the current user against current state — "a handler exists" and
14
+ * "this call can run now" are different questions.
15
+ * - executeUndo({sourceSeq, expectedPlanHash, acceptLosses, requestKey}) — re-derives the plan INSIDE
16
+ * one write-lock transaction (state·permission·contract may have moved since the preview), refuses on
17
+ * drift (undo.plan_changed), demands explicit loss confirmation (undo.confirmation_required), guards
18
+ * one successful compensation per source operation, runs the compensation through the shared gate
19
+ * pipeline (runCommand — no bypass lane, no nested transaction), and commits compensation events·
20
+ * linkage·idempotency·audit atomically.
21
+ * - undoStatus({sourceSeqs}) — the bundle lookup (support·processing state per exact seq).
22
+ *
23
+ * Legacy rows (written before the operation envelope existed) are addressed by their exact seq; the
24
+ * ledger can no longer prove their operation grouping, so the planner decides what it can still justify
25
+ * and the kernel answers undo.legacy_operation_unknown / undo.snapshot_missing for the rest. Undoing an
26
+ * undo compensates the compensation — the compensation operation itself is a normal operation.
27
+ */
28
+ import { randomUUID } from 'node:crypto'
29
+ import { currentIdentityOf, unauthenticated } from './auth.js'
30
+ import { maskSecrets, storageOf, type LedgerRow, type OperationLedgerCapability } from './storage.js'
31
+ import { appPolicy } from './policy.js'
32
+ import { completeAssembly, lookupCommand, undoHandlerOf, undoPolicyOf } from './registry.js'
33
+ import { commandRevisionOf, responseMetaOf } from './catalog.js'
34
+ import { canonicalJson } from './canonical.js'
35
+ import {
36
+ assertLiveRoleAllows,
37
+ assertRecordedDelegationCovers,
38
+ judgedIdentityOf,
39
+ liveIdentityOf,
40
+ policyRefusalGateError,
41
+ unprovableRefusal,
42
+ } from './permissions.js'
43
+ import { commandAccessOf, roleAllowsCommand } from './visibility.js'
44
+ import { reauthorize, validateDynamic, validateStatic } from './gate.js'
45
+ import { refusalShapeOf, toGateError } from './gate-results.js'
46
+ import type { ExecutionRefusal, ExecutionResult, ExecutionSuccess } from './gate-results.js'
47
+ import { auditSettled, refuse, tryRecordOutsideTx } from './gate-audit.js'
48
+ import { keyedDigestOf, producerOf, replayOrReject, settleConcurrentRetry, storeIdempotency } from './idempotency.js'
49
+ import { runCommand, type OperationContext } from './execution-core.js'
50
+ import { GateError } from './types.js'
51
+ import type { Identity, SourceOperation, UndoHandler, UndoPlan, UndoPlanChange, UndoPreview } from './types.js'
52
+
53
+ /** The pseudo-command undo attempts are recorded under (audit·idempotency) */
54
+ const UNDO_COMMAND = 'undo'
55
+
56
+ function capability(): OperationLedgerCapability {
57
+ const cap = storageOf().operationLedger
58
+ if (!cap)
59
+ throw new GateError(
60
+ 0,
61
+ '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)',
63
+ { code: 'undo.storage_capability_missing' },
64
+ )
65
+ return cap
66
+ }
67
+
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
+ /** Resolves the exact source operation behind a sequence — the whole operation, never a substitute row */
78
+ async function resolveSource(cap: OperationLedgerCapability, sourceSeq: number): Promise<{ source: SourceOperation; operationId: string }> {
79
+ const row = await cap.domainRowBySeq(sourceSeq)
80
+ if (!row || row.kind !== 'domain')
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)
83
+ if (meta?.operationId) {
84
+ const rows = await cap.eventsOfOperation(meta.operationId)
85
+ return { source: buildSource(rows.length > 0 ? rows : [row], sourceSeq, false), operationId: meta.operationId }
86
+ }
87
+ // Legacy — no envelope: the single selected row is everything the ledger can prove about the grouping
88
+ return { source: buildSource([row], sourceSeq, true), operationId: `legacy:${sourceSeq}` }
89
+ }
90
+
91
+ function buildSource(rows: LedgerRow[], sourceSeq: number, legacy: boolean): SourceOperation {
92
+ const first = parseMeta(rows[0])
93
+ return {
94
+ operationId: legacy ? `legacy:${sourceSeq}` : first?.operationId ?? `legacy:${sourceSeq}`,
95
+ sourceSeq,
96
+ legacy,
97
+ ...(first?.commandName ? { commandName: first.commandName } : {}),
98
+ ...(first?.commandVersion ? { commandVersion: first.commandVersion } : {}),
99
+ ...(first?.commandRevision ? { commandRevision: first.commandRevision } : {}),
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
105
+ return {
106
+ seq: r.seq,
107
+ type: r.type,
108
+ aggregateType: r.aggregate_type ?? '',
109
+ aggregateId: r.aggregate_id ?? '',
110
+ payload: JSON.parse(r.payload),
111
+ ...(eventVersion !== undefined ? { eventVersion } : {}),
112
+ }
113
+ }),
114
+ }
115
+ }
116
+
117
+ /** STRICT JSON values for plan data (before/after) — the plan is hashed with canonical JSON,
118
+ * published in previews and re-derived at execution, so a value must round-trip IDENTICALLY through
119
+ * JSON. JSON.stringify "succeeds" on a Date (an ISO string) while masking and hashing would see
120
+ * different things — only plain JSON values (null·boolean·finite number·string·array·plain object,
121
+ * recursively) are accepted; anything else is a plan defect caught here. */
122
+ const jsonValueOf = (v: unknown): boolean => {
123
+ if (v === null || typeof v === 'boolean' || typeof v === 'string') return true
124
+ if (typeof v === 'number') return Number.isFinite(v)
125
+ if (Array.isArray(v)) return v.every(jsonValueOf)
126
+ if (v && typeof v === 'object') {
127
+ const proto = Object.getPrototypeOf(v)
128
+ if (proto !== Object.prototype && proto !== null) return false // Date, Map, class instances… — not plain JSON
129
+ return Object.values(v).every(jsonValueOf)
130
+ }
131
+ return false // undefined, functions, symbols, bigints
132
+ }
133
+
134
+ /** Structural plan validation — the plan is machine-consumed (hashed, previewed, executed), so an
135
+ * off-shape plan is a loud defect, never a best-effort interpretation. The same completeness a
136
+ * command's output contract enforces: a malformed plan never reaches the hash, the preview or the
137
+ * execution. A blocked plan (blockers present) needs no compensation command — there is nothing to
138
+ * execute. */
139
+ function validateUndoPlan(plan: UndoPlan): void {
140
+ const invalid = (why: string) =>
141
+ new GateError(8, 'execute', `The undo handler returned an invalid plan — ${why}`, { code: 'undo.plan_invalid' })
142
+ if (!plan || typeof plan !== 'object') throw invalid('not an object')
143
+ const hasBlockers = Array.isArray(plan.blockers) && plan.blockers.length > 0
144
+ if (!hasBlockers) {
145
+ if (typeof plan.command !== 'string' || plan.command.length === 0) throw invalid('command missing')
146
+ if (!plan.input || typeof plan.input !== 'object' || Array.isArray(plan.input)) throw invalid('input must be a plain object')
147
+ if (!lookupCommand(plan.command)) throw invalid(`the compensation command is not registered: ${plan.command}`)
148
+ }
149
+ // changes is a REQUIRED member (declare [] when nothing visible changes) — an omitted changes list
150
+ // is a defective plan, not an empty one
151
+ if (!Array.isArray(plan.changes)) throw invalid('changes must be an array (declare [] when nothing visible changes)')
152
+ for (const c of plan.changes ?? []) {
153
+ if (!c || typeof c.target !== 'string' || c.target.length === 0) throw invalid('a change needs a target')
154
+ if (c.field !== undefined && typeof c.field !== 'string') throw invalid('change.field must be a string')
155
+ if (!jsonValueOf(c.before) || !jsonValueOf(c.after)) throw invalid('change.before/after must be plain JSON values (dates and class instances are not — serialize them yourself)')
156
+ }
157
+ for (const arr of [plan.losses, plan.blockers] as const)
158
+ for (const e of arr ?? []) {
159
+ if (!e || typeof e.code !== 'string' || !e.code || typeof e.reason !== 'string') throw invalid('losses/blockers entries need code and reason')
160
+ if ('count' in (e as object) && (!Number.isInteger((e as unknown as { count?: unknown }).count) || ((e as unknown as { count: number }).count ?? 0) < 0))
161
+ throw invalid('loss count must be a non-negative integer')
162
+ }
163
+ if (plan.dependsOn !== undefined) {
164
+ if (typeof plan.dependsOn !== 'object' || Array.isArray(plan.dependsOn)) throw invalid('dependsOn must be a record of string tokens')
165
+ for (const v of Object.values(plan.dependsOn)) if (typeof v !== 'string') throw invalid('dependsOn values must be strings')
166
+ }
167
+ if (plan.preserved !== undefined) {
168
+ if (!Array.isArray(plan.preserved)) throw invalid('preserved must be an array')
169
+ for (const p of plan.preserved) if (typeof p !== 'string') throw invalid('preserved entries must be strings')
170
+ }
171
+ }
172
+
173
+ /** Normalized change entries carry secrets in the VALUE under before/after — the shared key-based
174
+ * masking cannot see them (the keys spell before/after, not password). A field named like a secret
175
+ * masks its values in previews. The domain remains responsible for never planning secret restorations;
176
+ * this extends the kernel's existing key rule to the normalized shape. */
177
+ const maskChangeValues = (changes: UndoPlanChange[]) =>
178
+ changes.map((c) => (c.field && /pass(word)?/i.test(c.field) ? { ...c, before: '[masked]', after: '[masked]' } : c))
179
+
180
+ /** The plan hash — server-keyed (business values may ride inside the plan), domain-separated from the
181
+ * idempotency hash. Covers the source identity, the handler and command contracts, the compensation
182
+ * input, the dependency tokens and the whole change·preserved·loss·blocker projection: any movement
183
+ * moves the hash, and execution demands the exact same hash the preview showed. */
184
+ function planHashOf(
185
+ source: SourceOperation,
186
+ handler: UndoHandler,
187
+ plan: UndoPlan,
188
+ commandVersion: string | undefined,
189
+ commandRevision: string | undefined,
190
+ ): string {
191
+ return (
192
+ 'u1:' +
193
+ keyedDigestOf(
194
+ 'undo-plan',
195
+ canonicalJson({
196
+ operationId: source.operationId,
197
+ sourceSeq: source.sourceSeq,
198
+ handlerId: handler.id,
199
+ handlerVersion: handler.version,
200
+ command: plan.command,
201
+ commandVersion: commandVersion ?? '',
202
+ commandRevision: commandRevision ?? '',
203
+ input: plan.input,
204
+ dependsOn: plan.dependsOn ?? {},
205
+ changes: plan.changes,
206
+ preserved: plan.preserved ?? [],
207
+ losses: plan.losses ?? [],
208
+ blockers: plan.blockers ?? [],
209
+ }),
210
+ )
211
+ )
212
+ }
213
+
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.
217
+ * permissionRefusal is set when a PERMISSION·GATE check refused (origin-read hook, role, delegation,
218
+ * app-policy target — stages 1~3): the redelivery rights check throws on this flag, so the verdict
219
+ * never depends on error-code spelling (codes are domain vocabulary). Business judgments (a later
220
+ * change, plan defects, stages 4~7) set no flag — they never hide a result the caller owns. */
221
+ interface ComputedPlan {
222
+ preview: UndoPreview
223
+ plan?: UndoPlan
224
+ handler?: UndoHandler
225
+ operationId: string
226
+ permissionRefusal?: GateError
227
+ }
228
+
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
233
+ * unavailable type makes the whole operation unavailable, supported types must agree on ONE handler. */
234
+ async function readGateAndConsensus(
235
+ source: SourceOperation,
236
+ identity: Identity,
237
+ ): Promise<
238
+ | { readRefusal: GateError }
239
+ | {
240
+ readRefusal?: undefined
241
+ consensus:
242
+ | { kind: 'supported'; handlerId: string }
243
+ | { kind: 'unavailable'; code: string; reason: string }
244
+ | { kind: 'mixed' }
245
+ }
246
+ > {
247
+ const types = [...new Set(source.events.map((e) => e.type))]
248
+ for (const type of types) {
249
+ const readHook = undoPolicyOf(type)?.mayRead
250
+ if (readHook) {
251
+ try {
252
+ await readHook(source, identity)
253
+ } catch (err) {
254
+ return { readRefusal: toGateError(err, 3, 'policy') }
255
+ }
256
+ }
257
+ }
258
+ const policies = types.map((type) => ({ type, policy: undoPolicyOf(type) }))
259
+ if (policies.some((x) => !x.policy))
260
+ return { consensus: { kind: 'unavailable', code: 'undo.unavailable', reason: 'No undo policy registered for this event type' } }
261
+ const unsupported = policies.find((x) => x.policy?.kind === 'unavailable')
262
+ if (unsupported && unsupported.policy?.kind === 'unavailable')
263
+ return { consensus: { kind: 'unavailable', code: unsupported.policy.code, reason: unsupported.policy.reason } }
264
+ const handlerIds = [...new Set(policies.map((x) => (x.policy as unknown as { handlerId: string }).handlerId))]
265
+ if (handlerIds.length > 1) return { consensus: { kind: 'mixed' } }
266
+ return { consensus: { kind: 'supported', handlerId: handlerIds[0] } }
267
+ }
268
+
269
+ async function computePreview(sourceSeq: number, identity: Identity): Promise<ComputedPlan> {
270
+ const cap = capability()
271
+ const { source, operationId } = await resolveSource(cap, sourceSeq)
272
+
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.
279
+ const gated = await readGateAndConsensus(source, identity)
280
+ if (gated.readRefusal) return permissionRefusalOf(sourceSeq, gated.readRefusal, operationId)
281
+
282
+ // Policy consensus over EVERY event type of the operation — one operation, one compensation
283
+ if (gated.consensus.kind === 'unavailable')
284
+ return judgmentOnly('unavailable', sourceSeq, operationId, gated.consensus.code, gated.consensus.reason)
285
+ if (gated.consensus.kind === 'mixed')
286
+ 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
+ const handler = undoHandlerOf(gated.consensus.handlerId)!
288
+
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
+ // One successful compensation per source operation — checked again inside the execution lock
301
+ if ((await cap.compensationsOf(operationId)).length > 0)
302
+ return { operationId, preview: { status: 'already_undone', sourceSeq, operationId, changes: [], preserved: [], losses: [], blockers: [] } }
303
+
304
+ const plan = await handler.plan(source, identity)
305
+ validateUndoPlan(plan)
306
+
307
+ // A blocked plan answers as blocked — no compensation command to resolve or permit
308
+ if ((plan.blockers ?? []).length > 0)
309
+ return {
310
+ operationId,
311
+ preview: { status: 'blocked', sourceSeq, operationId, handlerId: handler.id, changes: [], preserved: [], losses: [], blockers: plan.blockers! },
312
+ }
313
+
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.
319
+ 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
+ let parsedInput: unknown
330
+ try {
331
+ parsedInput = await validateStatic(def, plan.command, plan.input, identity)
332
+ await validateDynamic(def, parsedInput, identity)
333
+ } catch (err) {
334
+ 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
343
+ }
344
+
345
+ const commandVersion = def.version ?? ''
346
+ const commandRevision = commandRevisionOf(def.name) ?? ''
347
+ const blockers = plan.blockers ?? []
348
+ const losses = plan.losses ?? []
349
+ const status: UndoPreview['status'] = blockers.length > 0 ? 'blocked' : losses.length > 0 ? 'warning' : 'available'
350
+ return {
351
+ operationId,
352
+ handler,
353
+ plan,
354
+ preview: {
355
+ status,
356
+ sourceSeq,
357
+ operationId,
358
+ handlerId: handler.id,
359
+ command: { name: plan.command, version: commandVersion, revision: commandRevision },
360
+ // before = the current value, after = the value the execution will set; secrets masked by the
361
+ // shared key rule and, for normalized entries, by the field-name rule (maskChangeValues)
362
+ changes: maskChangeValues(maskSecrets(plan.changes) as UndoPlanChange[]),
363
+ preserved: plan.preserved ?? [],
364
+ losses,
365
+ blockers,
366
+ ...(status === 'available' || status === 'warning' ? { planHash: planHashOf(source, handler, plan, commandVersion, commandRevision) } : {}),
367
+ },
368
+ }
369
+ }
370
+
371
+ /** A judgment with nothing to execute — no fabricated plan or handler, the preview speaks alone */
372
+ const judgmentOnly = (
373
+ status: 'unavailable' | 'blocked',
374
+ sourceSeq: number,
375
+ operationId: string,
376
+ code: string,
377
+ reason: string,
378
+ ): ComputedPlan => ({
379
+ operationId,
380
+ preview: { status, sourceSeq, operationId, changes: [], preserved: [], losses: [], blockers: [{ code, reason }] },
381
+ })
382
+
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. */
387
+ const permissionRefusalOf = (sourceSeq: number, refusal: GateError, operationId: string): ComputedPlan => ({
388
+ operationId,
389
+ preview: { status: 'blocked', sourceSeq, changes: [], preserved: [], losses: [], blockers: [{ code: refusal.code ?? 'policy.denied', reason: refusal.message }] },
390
+ permissionRefusal: refusal,
391
+ })
392
+
393
+ /** Revalidates the right to SEE a stored undo result — a redelivery is a fresh READ of a past outcome.
394
+ * The account must be valid NOW, and the permission view must still hold. Two shapes:
395
+ * - not yet compensated: the preview pipeline is re-derived read-only and its PERMISSION refusal
396
+ * (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.
401
+ * Business blockers (a later change, an unavailable policy, plan defects) never hide a result the
402
+ * caller already owns. Never re-runs the original business schemas; the stored hash already pins
403
+ * the request identity. */
404
+ async function assertUndoReadRights(sourceSeq: number, identity: Identity): Promise<void> {
405
+ const current = await liveIdentityOf(identity, () =>
406
+ new GateError(3, 'policy', 'Identity invalid at replay time — log in again', { code: 'auth.relogin_required' }))
407
+ // the CURRENT assignment scopes — a redelivery is judged with live assignments (the same refresh
408
+ // verifyReplayRights and reauthorize apply)
409
+ const judged = await judgedIdentityOf(current)
410
+ const computed = await computePreview(sourceSeq, judged)
411
+ if (computed.permissionRefusal) throw computed.permissionRefusal
412
+
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
418
+ const def = meta?.commandName ? lookupCommand(meta.commandName) : undefined
419
+ if (!def || !row)
420
+ throw new GateError(
421
+ 3,
422
+ 'policy',
423
+ 'The compensation command no longer exists — the stored result cannot be re-proven for this caller, so it is refused (never re-run)',
424
+ { code: 'gate.unknown_command' },
425
+ )
426
+ // the recorded material decides — role against the live definition, delegation against the
427
+ // RECORDED target (never a synthetic input object replayed through the business targetOf: input
428
+ // field names are not rights material, and a command whose target field differs from the event
429
+ // aggregate would extract nothing)
430
+ assertLiveRoleAllows(def, current.role, `Only roles [${def.allowedRoles.join('/')}] may read this stored undo result (current role: ${current.role})`)
431
+ if (current.delegation) await assertRecordedDelegationCovers(current.delegation, def.name, def.scope, meta?.policyTarget, 2)
432
+ if (def.scope !== 'none') {
433
+ // the normalized target recorded at write time — never guessed from the aggregate id or field
434
+ // names; a compensation envelope predating target recording cannot be re-proven, so it refuses
435
+ const target = meta?.policyTarget
436
+ if (target === undefined)
437
+ throw unprovableRefusal('The stored compensation carries no recorded target — the right cannot be re-proven, so the result is refused')
438
+ const refusal = await appPolicy().authorize(judged, def.scope, target)
439
+ // a replay verdict keeps the ERROR-CODE default guidance (review F1 — same rule as verifyReplayRights)
440
+ if (refusal) throw policyRefusalGateError(refusal)
441
+ }
442
+ }
443
+ }
444
+
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. */
448
+ async function withReadSnapshot<T>(fn: () => Promise<T>): Promise<T> {
449
+ const cap = storageOf().operationLedger
450
+ return cap ? cap.readSnapshot(fn) : fn()
451
+ }
452
+
453
+ /** Preview one undo — a read-only judgment for the current identity; never a promise that a later
454
+ * execution will pass (execution re-derives everything under the lock). */
455
+ export async function previewUndo(input: { sourceSeq: number }, identity: Identity | null): Promise<UndoPreview | ExecutionRefusal> {
456
+ completeAssembly()
457
+ if (!identity) return unauthenticated('Login required — undo preview is not public')
458
+ try {
459
+ return (await withReadSnapshot(() => computePreview(input.sourceSeq, identity))).preview
460
+ } catch (err) {
461
+ return refusalShapeOf(toGateError(err, 8, 'execute'))
462
+ }
463
+ }
464
+
465
+ /** 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. */
468
+ export async function undoStatus(
469
+ input: { sourceSeqs: number[] },
470
+ 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
+ > {
486
+ completeAssembly()
487
+ if (!identity) return unauthenticated('Login required — undo status is not public')
488
+ try {
489
+ const cap = capability()
490
+ 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)) {
501
+ const row = await cap.domainRowBySeq(seq)
502
+ if (!row || row.kind !== 'domain') {
503
+ out.push({ sourceSeq: seq, status: 'not_found' })
504
+ continue
505
+ }
506
+ // 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
508
+ // conclusion. The response keeps the requested seq.
509
+ const { source, operationId } = await resolveSource(cap, seq)
510
+ const gated = await readGateAndConsensus(source, identity)
511
+ if (gated.readRefusal) {
512
+ out.push({ sourceSeq: seq, status: 'denied', code: gated.readRefusal.code ?? 'policy.denied' })
513
+ continue
514
+ }
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
+ const undone = (await cap.compensationsOf(operationId)).length > 0
530
+ out.push({
531
+ sourceSeq: seq,
532
+ ...(gated.consensus.kind === 'mixed'
533
+ ? {
534
+ status: 'blocked' as const,
535
+ operationId,
536
+ legacy: source.legacy,
537
+ code: 'undo.operation_mixed_policies',
538
+ reason: 'The operation mixes event types with different undo handlers — a single compensation cannot cover it',
539
+ }
540
+ : gated.consensus.kind === 'unavailable'
541
+ ? {
542
+ status: 'unavailable' as const,
543
+ operationId,
544
+ legacy: source.legacy,
545
+ code: gated.consensus.code,
546
+ reason: gated.consensus.reason,
547
+ }
548
+ : {
549
+ status: undone ? ('already_undone' as const) : ('supported' as const),
550
+ operationId,
551
+ legacy: source.legacy,
552
+ handlerId: gated.consensus.handlerId,
553
+ }),
554
+ })
555
+ }
556
+ return out
557
+ })
558
+ return { ok: true, results }
559
+ } catch (err) {
560
+ return refusalShapeOf(toGateError(err, 8, 'execute'))
561
+ }
562
+ }
563
+
564
+ /** Execute one undo — the write path. Order of checks inside the transaction is fixed (the handover
565
+ * contract): identity·permission recheck → plan re-derivation → plan hash → loss confirmation → the
566
+ * one-compensation guard → the compensation through the full gate pipeline → atomic commit of events·
567
+ * linkage·idempotency·audit. */
568
+ export async function executeUndo(
569
+ input: { sourceSeq: number; expectedPlanHash: string; acceptLosses?: boolean; requestKey?: string },
570
+ identity: Identity | null,
571
+ ): Promise<ExecutionResult> {
572
+ completeAssembly()
573
+ if (!identity) return unauthenticated('Login required — undo execution is not public')
574
+ const requestKey = typeof input.requestKey === 'string' && input.requestKey.length > 0 ? input.requestKey.slice(0, 100) : undefined
575
+ // The idempotent identity of an undo request — a different source, plan or confirmation is a different
576
+ // request (and the same key with a different one of those is an input conflict, never a replay).
577
+ const hashValue = { sourceSeq: input.sourceSeq, expectedPlanHash: input.expectedPlanHash, acceptLosses: input.acceptLosses === true }
578
+ const rawInput = hashValue // scalars only — nothing to mask at this boundary (the compensation input is masked inside runCommand's audit)
579
+ try {
580
+ // Replay probe — a stored success is returned as-is (response-loss retries never re-run a
581
+ // compensation), but a redelivery is a fresh READ: the current identity and the origin·compensation
582
+ // rights are revalidated first (a downgraded role or a revoked target never receives the old result)
583
+ if (requestKey) {
584
+ const replayed = await replayOrReject(identity, UNDO_COMMAND, requestKey, hashValue)
585
+ if (replayed) {
586
+ await assertUndoReadRights(input.sourceSeq, identity)
587
+ await tryRecordOutsideTx('replay', UNDO_COMMAND, identity, rawInput)
588
+ return replayed.ok ? { ...replayed, meta: responseMetaOf(undefined, identity) } : replayed
589
+ }
590
+ }
591
+
592
+ const out = await storageOf().immediate(async () => {
593
+ const current = await currentIdentityOf(identity)
594
+ if (!current)
595
+ throw new GateError(3, 'policy', 'Identity invalid at execution time — log in again', { code: 'auth.relogin_required' })
596
+
597
+ const computed = await computePreview(input.sourceSeq, current)
598
+ const { preview, plan, handler, operationId } = computed
599
+ if (preview.status === 'already_undone')
600
+ 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
+ if (preview.status === 'unavailable' || preview.status === 'blocked') {
602
+ const b = preview.blockers[0]
603
+ throw new GateError(8, 'execute', `This operation cannot be undone: ${b?.reason ?? 'unavailable'}`, { code: b?.code ?? 'undo.unavailable' })
604
+ }
605
+ if (preview.planHash !== input.expectedPlanHash)
606
+ throw new GateError(8, 'execute', 'The undo plan changed since the preview (state·permission·contract moved) — preview again and confirm the new plan hash', {
607
+ code: 'undo.plan_changed',
608
+ recovery: { action: 'refresh' },
609
+ })
610
+ if (preview.losses.length > 0 && input.acceptLosses !== true)
611
+ throw new GateError(
612
+ 8,
613
+ 'execute',
614
+ `The plan reports losses — ${preview.losses.map((l) => l.reason).join('; ')} — resend the same plan with acceptLosses:true to confirm them`,
615
+ { code: 'undo.confirmation_required' },
616
+ )
617
+ // 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' })
619
+
620
+ // 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)
622
+ const def = lookupCommand(plan.command)!
623
+ const parsedInput = await validateStatic(def, plan.command, plan.input, current)
624
+ const reauthed = await reauthorize(def, plan.command, parsedInput, current)
625
+ await validateDynamic(def, parsedInput, reauthed)
626
+ const op: OperationContext = {
627
+ operationId: 'op_' + randomUUID(),
628
+ commandName: def.name,
629
+ ...(def.version ? { commandVersion: def.version } : {}),
630
+ ...(commandRevisionOf(def.name) ? { commandRevision: commandRevisionOf(def.name)! } : {}),
631
+ undo: { sourceOperationId: operationId, sourceSeq: input.sourceSeq, handlerVersion: handler.version },
632
+ }
633
+ // One success record that traces the whole attempt: the compensation command, its masked input,
634
+ // and the undo linkage back to the source operation
635
+ const r = await runCommand(def, def.name, parsedInput, plan.input, reauthed, op, {
636
+ undo: { sourceSeq: input.sourceSeq, operationId, handlerId: handler.id },
637
+ })
638
+ // A successful compensation proves itself through its ledger events — the one-compensation guard
639
+ // and undo status read that linkage. Zero events would leave an unprovable "success" (repeatable
640
+ // with a fresh key), so a no-op compensation is refused whole; nothing commits.
641
+ if (r.eventTypes.length === 0)
642
+ throw new GateError(8, 'execute', 'The compensation command wrote no events — an undo success must leave ledger linkage, so a no-op compensation is refused', {
643
+ code: 'undo.plan_invalid',
644
+ })
645
+ if (requestKey) await storeIdempotency(current, UNDO_COMMAND, requestKey, hashValue, r.result, r.eventTypes, producerOf(def.name, def, reauthed.role, parsedInput))
646
+ return { ...r, commandName: def.name }
647
+ })
648
+
649
+ const success: ExecutionSuccess = {
650
+ ok: true,
651
+ result: out.result,
652
+ events: out.eventTypes,
653
+ meta: responseMetaOf(out.commandName, identity),
654
+ }
655
+ return success
656
+ } catch (err) {
657
+ if (requestKey) {
658
+ try {
659
+ const settled = await settleConcurrentRetry(identity, UNDO_COMMAND, requestKey, hashValue)
660
+ if (settled) {
661
+ if (settled.ok) await assertUndoReadRights(input.sourceSeq, identity) // the settled result is a redelivery — same rights check
662
+ await auditSettled(UNDO_COMMAND, identity, rawInput, settled)
663
+ return settled.ok ? { ...settled, meta: responseMetaOf(undefined, identity) } : settled
664
+ }
665
+ } catch (rightsErr) {
666
+ return await refuse(UNDO_COMMAND, identity, rawInput, toGateError(rightsErr, 3, 'policy'))
667
+ }
668
+ }
669
+ return await refuse(UNDO_COMMAND, identity, rawInput, toGateError(err, 8, 'execute'))
670
+ }
671
+ }