@sudoke/kernel 0.5.1 → 0.6.2

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 CHANGED
@@ -29,7 +29,7 @@ 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
35
  import { ledgerEventVersionOf, operationMetaOf } from './operation-meta.js'
@@ -41,7 +41,7 @@ import {
41
41
  policyRefusalGateError,
42
42
  unprovableRefusal,
43
43
  } from './permissions.js'
44
- import { commandAccessOf, roleAllowsCommand } from './visibility.js'
44
+ import { commandAccessRefusalOf } from './visibility.js'
45
45
  import { reauthorize, validateDynamic, validateStatic } from './gate.js'
46
46
  import { refusalShapeOf, toGateError } from './gate-results.js'
47
47
  import type { ExecutionRefusal, ExecutionResult, ExecutionSuccess } from './gate-results.js'
@@ -54,13 +54,21 @@ import type { Identity, SourceOperation, UndoHandler, UndoPlan, UndoPlanChange,
54
54
  /** The pseudo-command undo attempts are recorded under (audit·idempotency) */
55
55
  const UNDO_COMMAND = 'undo'
56
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
+
57
61
  function capability(): OperationLedgerCapability {
58
62
  const cap = storageOf().operationLedger
59
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.
60
68
  throw new GateError(
61
69
  0,
62
70
  'registry',
63
- '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',
64
72
  { code: 'undo.storage_capability_missing' },
65
73
  )
66
74
  return cap
@@ -124,14 +132,17 @@ const jsonValueOf = (v: unknown): boolean => {
124
132
  * off-shape plan is a loud defect, never a best-effort interpretation. The same completeness a
125
133
  * command's output contract enforces: a malformed plan never reaches the hash, the preview or the
126
134
  * execution. A blocked plan (blockers present) needs no compensation command — there is nothing to
127
- * execute. */
128
- 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 {
129
138
  const invalid = (why: string) =>
130
139
  new GateError(8, 'execute', `The undo handler returned an invalid plan — ${why}`, { code: 'undo.plan_invalid' })
131
140
  if (!plan || typeof plan !== 'object') throw invalid('not an object')
132
141
  const hasBlockers = Array.isArray(plan.blockers) && plan.blockers.length > 0
133
142
  if (!hasBlockers) {
134
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}'`)
135
146
  if (!plan.input || typeof plan.input !== 'object' || Array.isArray(plan.input)) throw invalid('input must be a plain object')
136
147
  if (!lookupCommand(plan.command)) throw invalid(`the compensation command is not registered: ${plan.command}`)
137
148
  }
@@ -201,8 +212,10 @@ function planHashOf(
201
212
  }
202
213
 
203
214
  /** Everything a preview computes — the public projection plus the internals execution re-checks.
204
- * plan·handler are present only when a compensation is actually planned (status available|warning);
205
- * 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.
206
219
  * permissionRefusal is set when a PERMISSION·GATE check refused (origin-read hook, role, delegation,
207
220
  * app-policy target — stages 1~3): the redelivery rights check throws on this flag, so the verdict
208
221
  * never depends on error-code spelling (codes are domain vocabulary). Business judgments (a later
@@ -211,14 +224,18 @@ interface ComputedPlan {
211
224
  preview: UndoPreview
212
225
  plan?: UndoPlan
213
226
  handler?: UndoHandler
227
+ parsedInput?: unknown
214
228
  operationId: string
215
229
  permissionRefusal?: GateError
216
230
  }
217
231
 
218
- /** The operation-level read gate + undo consensus, judged over EVERY event type of the operation —
219
- * shared by preview and status so ANY event row of one operation answers the SAME conclusion (the
220
- * status is a per-OPERATION lookup; the seq the caller picked is only the anchor). Read refusals
221
- * 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
222
239
  * unavailable type makes the whole operation unavailable, supported types must agree on ONE handler. */
223
240
  async function readGateAndConsensus(
224
241
  source: SourceOperation,
@@ -235,7 +252,8 @@ async function readGateAndConsensus(
235
252
  > {
236
253
  const types = [...new Set(source.events.map((e) => e.type))]
237
254
  for (const type of types) {
238
- 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()
239
257
  if (readHook) {
240
258
  try {
241
259
  await readHook(source, identity)
@@ -245,6 +263,9 @@ async function readGateAndConsensus(
245
263
  }
246
264
  }
247
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())
248
269
  if (policies.some((x) => !x.policy))
249
270
  return { consensus: { kind: 'unavailable', code: 'undo.unavailable', reason: 'No undo policy registered for this event type' } }
250
271
  const unsupported = policies.find((x) => x.policy?.kind === 'unavailable')
@@ -252,6 +273,29 @@ async function readGateAndConsensus(
252
273
  return { consensus: { kind: 'unavailable', code: unsupported.policy.code, reason: unsupported.policy.reason } }
253
274
  const handlerIds = [...new Set(policies.map((x) => (x.policy as unknown as { handlerId: string }).handlerId))]
254
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
+ }
255
299
  return { consensus: { kind: 'supported', handlerId: handlerIds[0] } }
256
300
  }
257
301
 
@@ -259,12 +303,13 @@ async function computePreview(sourceSeq: number, identity: Identity): Promise<Co
259
303
  const cap = capability()
260
304
  const { source, operationId } = await resolveSource(cap, sourceSeq)
261
305
 
262
- // Origin-read rights FIRST — before ANY branch (unavailable·missing·mixed·supported·already_undone)
263
- // answers a fact about the operation: the POLICY's mayRead hook decides whether this identity may
264
- // learn anything at all, whatever the undo answer would have been. The same shared judgment answers
265
- // undoStatus — one operation, one conclusion, whatever row was selected. Supported handlers
266
- // additionally gate through their own mayPreview (plan-specific rights); this hook is the
267
- // 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.
268
313
  const gated = await readGateAndConsensus(source, identity)
269
314
  if (gated.readRefusal) return permissionRefusalOf(sourceSeq, gated.readRefusal, operationId)
270
315
 
@@ -275,23 +320,12 @@ async function computePreview(sourceSeq: number, identity: Identity): Promise<Co
275
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')
276
321
  const handler = undoHandlerOf(gated.consensus.handlerId)!
277
322
 
278
- // Plan-specific read permission (the handler's hook) — still before any state judgment: an identity
279
- // without history rights learns nothing, not even whether a compensation exists. Strict assemblies
280
- // require the hook on every handler. ANY refusal here is a permission refusal — whatever its code says.
281
- if (handler.mayPreview) {
282
- try {
283
- await handler.mayPreview(source, identity)
284
- } catch (err) {
285
- return permissionRefusalOf(sourceSeq, toGateError(err, 3, 'policy'), operationId)
286
- }
287
- }
288
-
289
323
  // One successful compensation per source operation — checked again inside the execution lock
290
324
  if ((await cap.compensationsOf(operationId)).length > 0)
291
325
  return { operationId, preview: { status: 'already_undone', sourceSeq, operationId, changes: [], preserved: [], losses: [], blockers: [] } }
292
326
 
293
327
  const plan = await handler.plan(source, identity)
294
- validateUndoPlan(plan)
328
+ validateUndoPlan(plan, handler)
295
329
 
296
330
  // A blocked plan answers as blocked — no compensation command to resolve or permit
297
331
  if ((plan.blockers ?? []).length > 0)
@@ -300,46 +334,37 @@ async function computePreview(sourceSeq: number, identity: Identity): Promise<Co
300
334
  preview: { status: 'blocked', sourceSeq, operationId, handlerId: handler.id, changes: [], preserved: [], losses: [], blockers: plan.blockers! },
301
335
  }
302
336
 
303
- // Compensation-execution permission — the CURRENT identity must be allowed to run the compensation,
304
- // judged on the planner's ACTUAL input: catalog visibility alone never means executable. The same
305
- // static gate checks a direct call would face (delegation·role·app-policy target·schema), then the
306
- // read-only dynamic checks (preconditions·invariants·transitions) — so 'available' means a call NOW
307
- // 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.
308
342
  const def = lookupCommand(plan.command)!
309
- const access = commandAccessOf(def, identity)
310
- if (!access.visible)
311
- return permissionRefusalOf(
312
- sourceSeq,
313
- new GateError(3, 'policy', `The compensation command '${plan.command}' is not allowed for the current identity`, {
314
- code: 'gate.role_denied',
315
- }),
316
- operationId,
317
- )
318
343
  let parsedInput: unknown
319
344
  try {
320
345
  parsedInput = await validateStatic(def, plan.command, plan.input, identity)
321
346
  await validateDynamic(def, parsedInput, identity)
322
347
  } catch (err) {
323
348
  const refusal = toGateError(err, 3, 'policy')
324
- // stages 1~3 are permission·policy refusals (whatever the code spells); stage 4 is a planner
325
- // output defect, stages 5~7 are business judgments against the current state — only the first
326
- // kind withholds a stored result from its owner
327
- const computed: ComputedPlan = {
328
- ...judgmentOnly('blocked', sourceSeq, operationId, refusal.code ?? 'policy.denied', refusal.message),
329
- ...(refusal.stage <= 3 ? { permissionRefusal: refusal } : {}),
330
- }
331
- 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)
332
355
  }
333
356
 
334
357
  const commandVersion = def.version ?? ''
335
358
  const commandRevision = commandRevisionOf(def.name) ?? ''
336
359
  const blockers = plan.blockers ?? []
337
360
  const losses = plan.losses ?? []
338
- 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'
339
363
  return {
340
364
  operationId,
341
365
  handler,
342
366
  plan,
367
+ parsedInput,
343
368
  preview: {
344
369
  status,
345
370
  sourceSeq,
@@ -369,13 +394,15 @@ const judgmentOnly = (
369
394
  preview: { status, sourceSeq, operationId, changes: [], preserved: [], losses: [], blockers: [{ code, reason }] },
370
395
  })
371
396
 
372
- /** A PERMISSION refusal — the identity learns that it may not read this operation, and nothing else:
373
- * no operation id, no processing state, no policy metadata. Whatever the hook's code spells, the
374
- * redelivery rights check refuses on this shape (the flag, not the spelling). The operationId stays
375
- * 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. */
376
403
  const permissionRefusalOf = (sourceSeq: number, refusal: GateError, operationId: string): ComputedPlan => ({
377
404
  operationId,
378
- 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 }] },
379
406
  permissionRefusal: refusal,
380
407
  })
381
408
 
@@ -383,10 +410,11 @@ const permissionRefusalOf = (sourceSeq: number, refusal: GateError, operationId:
383
410
  * The account must be valid NOW, and the permission view must still hold. Two shapes:
384
411
  * - not yet compensated: the preview pipeline is re-derived read-only and its PERMISSION refusal
385
412
  * (the internal flag, independent of error-code spelling) refuses the redelivery;
386
- * - already compensated (no live plan exists): the STORED compensation's envelope decides — its
387
- * commandName and target aggregate are re-checked against the current role·delegation·policy.
388
- * When the compensation command itself was removed, no material can re-prove the rights — the
389
- * 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.
390
418
  * Business blockers (a later change, an unavailable policy, plan defects) never hide a result the
391
419
  * caller already owns. Never re-runs the original business schemas; the stored hash already pins
392
420
  * the request identity. */
@@ -399,10 +427,13 @@ async function assertUndoReadRights(sourceSeq: number, identity: Identity): Prom
399
427
  const computed = await computePreview(sourceSeq, judged)
400
428
  if (computed.permissionRefusal) throw computed.permissionRefusal
401
429
 
402
- if (computed.preview.status === 'already_undone') {
403
- const cap = capability()
404
- const compSeq = (await cap.compensationsOf(computed.operationId))[0]
405
- const row = compSeq !== undefined ? await cap.domainRowBySeq(compSeq) : 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)
406
437
  const meta = row ? operationMetaOf(row) : undefined
407
438
  const def = meta?.commandName ? lookupCommand(meta.commandName) : undefined
408
439
  if (!def || !row)
@@ -431,12 +462,11 @@ async function assertUndoReadRights(sourceSeq: number, identity: Identity): Prom
431
462
  }
432
463
  }
433
464
 
434
- /** Wraps a computation in the engine's consistent read snapshot when it provides one — a preview is one
435
- * point-in-time view, never a collage of reads from different moments. Engines without the capability
436
- * (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). */
437
468
  async function withReadSnapshot<T>(fn: () => Promise<T>): Promise<T> {
438
- const cap = storageOf().operationLedger
439
- return cap ? cap.readSnapshot(fn) : fn()
469
+ return capability().readSnapshot(fn)
440
470
  }
441
471
 
442
472
  /** Preview one undo — a read-only judgment for the current identity; never a promise that a later
@@ -451,49 +481,51 @@ export async function previewUndo(input: { sourceSeq: number }, identity: Identi
451
481
  }
452
482
  }
453
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
+
454
497
  /** Per-seq support·processing state — the list-view companion (buttons are not execution guarantees;
455
- * what really runs is decided by preview and execution). Origin-read rights gate the ANSWER: a denied
456
- * 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. */
457
502
  export async function undoStatus(
458
503
  input: { sourceSeqs: number[] },
459
504
  identity: Identity | null,
460
- ): Promise<
461
- | {
462
- ok: true
463
- results: Array<{
464
- sourceSeq: number
465
- status: 'supported' | 'unavailable' | 'blocked' | 'already_undone' | 'not_found' | 'denied'
466
- operationId?: string
467
- legacy?: boolean
468
- handlerId?: string
469
- code?: string
470
- reason?: string
471
- }>
472
- }
473
- | ExecutionRefusal
474
- > {
505
+ ): Promise<{ ok: true; results: UndoStatusRow[] } | ExecutionRefusal> {
475
506
  completeAssembly()
476
507
  if (!identity) return unauthenticated('Login required — undo status is not public')
477
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
+ )
478
518
  const cap = capability()
479
519
  const results = await withReadSnapshot(async () => {
480
- const out: Array<{
481
- sourceSeq: number
482
- status: 'supported' | 'unavailable' | 'blocked' | 'already_undone' | 'not_found' | 'denied'
483
- operationId?: string
484
- legacy?: boolean
485
- handlerId?: string
486
- code?: string
487
- reason?: string
488
- }> = []
489
- for (const seq of (input.sourceSeqs ?? []).slice(0, 100)) {
520
+ const out: UndoStatusRow[] = []
521
+ for (const seq of input.sourceSeqs ?? []) {
490
522
  const row = await cap.domainRowBySeq(seq)
491
523
  if (!row || row.kind !== 'domain') {
492
524
  out.push({ sourceSeq: seq, status: 'not_found' })
493
525
  continue
494
526
  }
495
527
  // the seq is only the ANCHOR — the OPERATION behind it is judged as a whole (the same shared
496
- // 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
497
529
  // conclusion. The response keeps the requested seq.
498
530
  const { source, operationId } = await resolveSource(cap, seq)
499
531
  const gated = await readGateAndConsensus(source, identity)
@@ -501,20 +533,6 @@ export async function undoStatus(
501
533
  out.push({ sourceSeq: seq, status: 'denied', code: gated.readRefusal.code ?? 'policy.denied' })
502
534
  continue
503
535
  }
504
- // the supported handler's mayPreview (the plan-specific read right) — a refusal answers
505
- // 'denied' with no operation facts, exactly like the operation-level gate
506
- if (gated.consensus.kind === 'supported') {
507
- const handler = undoHandlerOf(gated.consensus.handlerId)
508
- if (handler?.mayPreview) {
509
- try {
510
- await handler.mayPreview(source, identity)
511
- } catch (err) {
512
- const refusal = toGateError(err, 3, 'policy')
513
- out.push({ sourceSeq: seq, status: 'denied', code: refusal.code ?? 'policy.denied' })
514
- continue
515
- }
516
- }
517
- }
518
536
  const undone = (await cap.compensationsOf(operationId)).length > 0
519
537
  out.push({
520
538
  sourceSeq: seq,
@@ -584,7 +602,11 @@ export async function executeUndo(
584
602
  throw new GateError(3, 'policy', 'Identity invalid at execution time — log in again', { code: 'auth.relogin_required' })
585
603
 
586
604
  const computed = await computePreview(input.sourceSeq, current)
587
- 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
588
610
  if (preview.status === 'already_undone')
589
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' })
590
612
  if (preview.status === 'unavailable' || preview.status === 'blocked') {
@@ -604,12 +626,19 @@ export async function executeUndo(
604
626
  { code: 'undo.confirmation_required' },
605
627
  )
606
628
  // Past the guards a compensation exists — narrow the optional internals for the pipeline below
607
- 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' })
608
631
 
609
632
  // The compensation passes the FULL gate pipeline, inside this transaction — same checks as any
610
- // 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.
611
641
  const def = lookupCommand(plan.command)!
612
- const parsedInput = await validateStatic(def, plan.command, plan.input, current)
613
642
  const reauthed = await reauthorize(def, plan.command, parsedInput, current)
614
643
  await validateDynamic(def, parsedInput, reauthed)
615
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) */