@sudoke/kernel 0.5.1 → 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 +46 -24
- package/package.json +1 -1
- package/src/catalog.ts +14 -7
- package/src/index.ts +3 -2
- package/src/mcp.ts +3 -3
- package/src/registry.ts +32 -15
- package/src/state.ts +5 -1
- package/src/storage.ts +6 -5
- package/src/types.ts +25 -13
- package/src/undo.ts +146 -117
- package/src/visibility.ts +44 -7
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
|
|
45
|
-
|
|
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)
|
|
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
|
|
138
|
-
makes the whole operation unavailable; multiple handlers
|
|
139
|
-
while the response keeps the requested seq as the anchor.
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
`
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
|
155
|
-
|
|
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
|
|
172
|
-
carries `handlerVersion`); per-command
|
|
173
|
-
|
|
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
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.
|
|
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
|
|
117
|
-
* contract (what it plans, how it judges conflicts) is
|
|
118
|
-
* the
|
|
119
|
-
*
|
|
120
|
-
*
|
|
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
|
-
? {
|
|
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(
|
|
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 }) => {
|
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.
|
|
182
|
-
* one
|
|
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
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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
|
|
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
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
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
|
|
87
|
-
* publishes it and
|
|
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
|
|
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;
|
|
136
|
-
* registered event type AND
|
|
137
|
-
*
|
|
138
|
-
*
|
|
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.
|
|
199
|
-
*
|
|
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
|
|
205
|
-
*
|
|
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,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 {
|
|
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
|
|
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
|
-
|
|
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
|
|
205
|
-
* the judgment-only answers (unavailable·blocked·already_undone) carry the
|
|
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
|
|
219
|
-
*
|
|
220
|
-
* status is a per-OPERATION lookup; the seq the caller picked is only the anchor).
|
|
221
|
-
*
|
|
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
|
-
|
|
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
|
|
263
|
-
// answers a fact about the operation
|
|
264
|
-
//
|
|
265
|
-
//
|
|
266
|
-
//
|
|
267
|
-
//
|
|
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
|
|
304
|
-
// judged
|
|
305
|
-
// static gate checks a direct call would face (delegation·
|
|
306
|
-
// read-only dynamic checks (preconditions·invariants·transitions) — so 'available' means a call
|
|
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)
|
|
325
|
-
//
|
|
326
|
-
// kind withholds a stored result
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
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
|
-
|
|
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
|
|
373
|
-
* no operation id, no processing state, no policy metadata.
|
|
374
|
-
*
|
|
375
|
-
*
|
|
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: '
|
|
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
|
-
* -
|
|
387
|
-
*
|
|
388
|
-
*
|
|
389
|
-
* stored
|
|
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
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
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
|
|
435
|
-
*
|
|
436
|
-
*
|
|
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
|
-
|
|
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).
|
|
456
|
-
*
|
|
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:
|
|
481
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
58
|
-
if (
|
|
59
|
-
if (
|
|
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:
|
|
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) */
|