@sudoke/kernel 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,221 @@
1
+ # @sudoke/kernel
2
+
3
+ The SUDOKE kernel — the 9-stage command gate, append-only ledger, registries and the async storage port
4
+ behind every sudoke app. Surfaces (REST·MCP·UI) and domains (commands, policies, projections) are app
5
+ content; this package owns the execution guarantees every write passes through.
6
+
7
+ This README documents the public API, the **undo (restore) contract**, the **command version/revision
8
+ contract**, the compat/strict assembly modes, and the storage-port extension requirements. All kernel
9
+ source (comments, refusal sentences) is English; app packages are the app authors' language.
10
+
11
+ ## Assembly
12
+
13
+ One kernel per process. Boot order (every `register*` refuses after the seal):
14
+
15
+ ```ts
16
+ import {
17
+ registerStorage, registerRoles, registerEventContracts, registerEventVersions,
18
+ registerErrorCodes, registerAppPolicy, registerAppProjector, registerAppProtocol,
19
+ registerCommand, registerQuery, registerTransitionMachine,
20
+ configureKernel, registerUndoPolicies, registerUndoHandler, registerCatalogRelease,
21
+ catalogConsistencyErrors, sealRegistries,
22
+ } from '@sudoke/kernel'
23
+
24
+ registerStorage(engine) // physical layer first (e.g. sqliteStorage)
25
+ configureKernel({ mode: 'compat' }) // or 'strict' — see below
26
+ registerRoles([...]) // the app's role vocabulary
27
+ registerEventContracts({...}) // payload contracts — writes check against them
28
+ registerUndoPolicies({...}) // per event type: supported(handlerId) | unavailable(code, reason)
29
+ registerUndoHandler({...}) // the domain's compensation planner
30
+ registerCommand({...}) // name·schema·output·roles·hooks·version
31
+ registerQuery({...}) // read contracts version too
32
+ catalogConsistencyErrors() // empty = consistent (boot may fail the assembly here)
33
+ sealRegistries()
34
+ ```
35
+
36
+ The seal is automatic at the first execution (`completeAssembly`) — there is no path that seals without
37
+ the consistency check.
38
+
39
+ ## Compat and strict
40
+
41
+ - **compat (default)** — the historical contract stands: registrations without undo policies or versions
42
+ work, writes need no contract, and the new APIs answer clearly when their prerequisites are absent
43
+ (undo: `undo.storage_capability_missing`; unregistered event policies read as unavailable).
44
+ - **strict** — the full regime. The consistency check additionally demands: an undo policy for every
45
+ registered event type, a declared semver `version` on every command and query, a `mayRead` hook on
46
+ every undo policy and a `mayPreview` hook on every handler (read rights are declared, never
47
+ defaulted), and the operation-ledger storage capability. Writes must carry a contract (below). A
48
+ strict assembly that lacks any of these fails the boot — never a partial feature that quietly does
49
+ less.
50
+
51
+ `configureKernel` is sealed with the registries; changing the mode at runtime is a defect.
52
+
53
+ ## Command versions, revisions and the single manifest
54
+
55
+ | Field | Meaning | Managed by |
56
+ |---|---|---|
57
+ | `protocolVersion` (`PROTOCOL_VERSION`) | the kernel's own catalog·request/response·undo contract format | kernel semver |
58
+ | `catalogVersion` | the app's whole-contract compatibility version (`registerCatalogRelease`) | domain release |
59
+ | `catalogRevision` | content fingerprint of the sealed catalog | kernel (deterministic) |
60
+ | `commands[].version` / `queries[].version` | that contract's compatibility version (domain-declared semver) | domain release |
61
+ | `commands[].revision` / `queries[].revision` | that contract's content fingerprint (schema details, description, referenced error codes, transition rules, behaviorRevision) | kernel (deterministic) |
62
+ | `viewRevision` | fingerprint of what THIS identity may see (role ∩ delegation); the identity itself is not hashed | kernel (deterministic) |
63
+ | `eventVersion` | event payload format version (`registerEventVersions`), independent of command versions | domain |
64
+
65
+ Revisions are content-derived: the same content yields the same revision regardless of registration
66
+ order or boot count; a revision change MEANS a content change. What a fingerprint cannot capture —
67
+ functional refine bodies, business semantics — is declared through `behaviorRevision` (folded into the
68
+ revision). The kernel never claims the hash discovers meaning changes by itself.
69
+
70
+ APIs (transport-independent; surfaces own paths and polling):
71
+
72
+ - `buildCatalogDocument(identity)` — the single manifest every transport derives from (REST endpoint,
73
+ MCP catalog tool). Adds `protocolVersion`·revisions·`undoPolicies` to the historical content; the
74
+ per-command `fields` map lists EVERY input field (`null` when undocumented — a field never vanishes
75
+ from the catalog for lacking a `.describe()`). The MACHINE-READABLE contract (types·required-ness·
76
+ checks·defaults) is published per command through the `command_contract` MCP tool and the
77
+ `commandContractShape` export — the same canonical shape the revision fingerprint is computed from,
78
+ so the published contract and the fingerprint can never drift apart.
79
+ - `catalogStatus(identity)` — the cheap reconnect comparison (the view covers role, delegation scopes
80
+ AND the caller's assignment scopes — a scope change moves viewRevision).
81
+ - `catalogChanges({ since }, identity)` — `upToDate` | a permission-filtered change list | `fullRefreshRequired`
82
+ (a diff is an optimization; the full catalog is always the source of truth; hidden commands are never
83
+ confirmed through the change list).
84
+ - `validateReleaseManifest(prev, curr)` (+ `npm run validate:releases` in this package) — fails a release
85
+ whose contracts changed without a change record, or whose structurally identifiable breaks lack a
86
+ MAJOR bump; semantic compatibility stays the release author's explicit classification.
87
+
88
+ ### Strict-mode writes carry a contract
89
+
90
+ ```
91
+ { ...businessInput, contract: { commandVersion, commandRevision, protocolVersion } }
92
+ ```
93
+
94
+ The contract rides beside the business input (stripped before the schema), is refused before execution
95
+ when stale (`gate.contract_changed`) or absent (`gate.contract_required`), and joins the idempotency
96
+ hash — the same key with a new contract is an input conflict, never a replay. A stored success replays
97
+ even when the current schema or contract would refuse the resent input (the replay probe precedes the
98
+ checks — in EVERY transport: the MCP tool schema DESCRIBES the contract for clients but never judges or
99
+ normalizes, so the raw request reaches the gate byte-for-byte as sent). A replay hit is a fresh READ:
100
+ the RECORDED rights material (role, scope, normalized target, preserved with every idempotency row —
101
+ per item for batches) is re-proven against the current identity, delegation range and app policy; a
102
+ row without material is unprovable and refused, never read as "no restriction". Batch items each carry
103
+ a contract, judged BEFORE the business schema (the same order as single commands); one stale item
104
+ refuses the whole batch before execution. Success responses carry `meta` — the CURRENT revisions,
105
+ including the caller's `viewRevision`. A replayed
106
+ success additionally carries `producedBy` — the contract that PRODUCED the stored result (commandName·
107
+ versions·protocolVersion·the role that executed); rows older than producer tracking answer
108
+ `{ unknown: true }`. Redeliveries re-check the current rights first — undo redeliveries re-derive the
109
+ permission view structurally (the verdict never depends on error-code spelling), and a removed
110
+ command's stored result returns only while the account is valid AND the recorded rights still hold:
111
+ the producer's role AND, for scoped commands, the app policy's verdict on the RECORDED normalized
112
+ target (stamped beside every result and on every event envelope as `policyTarget` at write time —
113
+ the verdict never guesses targets from aggregate ids). A moved role, a denied target, a revoked
114
+ history right or an unprovable row gets a clear refusal — never the result, never a re-run.
115
+
116
+ ## Undo (restore)
117
+
118
+ Undo is a NEW WRITE, never a rewrite: the original ledger rows stay untouched; the compensation is one
119
+ registered command re-entering the full gate; compensation events carry the undo linkage on their
120
+ envelope (`undoOfOperationId`·`undoSourceSeq`·`undoHandlerVersion`).
121
+
122
+ ```ts
123
+ const status = await undoStatus({ sourceSeqs: [seq] }, identity) // per-seq support·processing state
124
+ const preview = await previewUndo({ sourceSeq: seq }, identity)
125
+ // preview.status: available | warning | blocked | unavailable | already_undone
126
+ // preview.changes (before = current value, after = the value execution will set), losses, blockers, planHash
127
+ const done = await executeUndo(
128
+ { sourceSeq: seq, expectedPlanHash: preview.planHash, acceptLosses: true, requestKey: 'retry-key' },
129
+ identity,
130
+ )
131
+ ```
132
+
133
+ Contract highlights:
134
+
135
+ - **The unit is the operation** — one atomic command run (batch items are separate operations under one
136
+ batchId). Selecting any event row of the operation resolves to the whole operation; partial undo does
137
+ not exist. `undoStatus` and `previewUndo` share ONE per-operation judgment — every event row of one
138
+ operation answers the same read verdict and the same undo consensus (a single unavailable event type
139
+ makes the whole operation unavailable; multiple handlers answer `undo.operation_mixed_policies`),
140
+ while the response keeps the requested seq as the anchor.
141
+ - **The planner is domain-owned** (`registerUndoHandler`): `plan(source, identity)` is read-only and
142
+ returns exactly one registered compensation command, `dependsOn` state tokens, `changes`·`preserved`·
143
+ `losses`·`blockers`. The plan is machine-consumed, so the kernel validates its shape completely
144
+ (required `changes` array, string `preserved` entries, JSON-representable `before`/`after`,
145
+ non-negative integer loss counts) — a malformed plan answers `undo.plan_invalid` and never reaches
146
+ the hash, the preview or the execution.
147
+ - **Origin-read rights live on the POLICY** (`mayRead` on every `registerUndoPolicies` entry) — REQUIRED
148
+ in strict mode: it runs before ANY branch (supported·unavailable·mixed·legacy·already-undone) answers
149
+ anything about an operation, and a refusal carries no operation facts (no id, no processing state, no
150
+ policy reason). Supported handlers refine further with `mayPreview` (also required in strict). An
151
+ optional `roles` on the policy scopes its CATALOG exposure; exposure and the read verdict are
152
+ independent decisions.
153
+ - **The preview judges the compensation through the SAME static+dynamic checks a direct call would
154
+ face** (schema·delegation·role·app-policy target·preconditions·invariants·transitions) — 'available'
155
+ means a call NOW would pass stages 1~7; a denied target blocks and leaks nothing (status answers
156
+ carry a 'denied' state too).
157
+ - **Conflicts are sequence-based, never value-based** — the planner decides with ledger facts; a later
158
+ same-field change blocks even when the value round-tripped. Hard conflicts are never forceable; the
159
+ confirmation pair is `acceptLosses` + `expectedPlanHash` (`undo.confirmation_required`,
160
+ `undo.plan_changed`).
161
+ - **A successful compensation must write events** — the one-compensation guard and undo status read the
162
+ ledger linkage on compensation events; a zero-event compensation would be an unprovable, repeatable
163
+ success, so it is refused whole (`undo.plan_invalid`) and nothing commits.
164
+ - **Previews mask secrets by both rules** — the shared key rule (`password`-named keys) and, for
165
+ normalized change entries, the field-name rule: a change whose `field` is named like a secret has its
166
+ `before`/`after` masked. Domains remain responsible for never planning secret restorations at all.
167
+ - **Execution re-derives everything inside one write-lock transaction**: current identity, the plan, the
168
+ hash, the loss confirmation, and the one-compensation-per-source guard — then the compensation runs
169
+ through the shared gate pipeline (no bypass lane, no nested transaction), and events·linkage·
170
+ idempotency·audit commit or roll back together.
171
+ - **Undoing an undo** compensates the compensation — it is a normal operation with its own policy. Undo
172
+ handler versions are catalog content: a handler bump moves catalogRevision (and the published policy
173
+ carries `handlerVersion`); per-command revisions stay stable — which command compensates an event is a
174
+ plan-time decision, so catalogRevision·catalogStatus is the discovery surface for policy changes.
175
+ - **Legacy rows** (written before the envelope) are addressed by exact seq; unprovable grouping answers
176
+ `undo.legacy_operation_unknown`, missing prior state `undo.snapshot_missing`.
177
+
178
+ Kernel-common error codes involved: `gate.contract_required`, `gate.contract_changed`,
179
+ `undo.source_not_found`, `undo.unavailable`, `undo.storage_capability_missing`, `undo.already_undone`,
180
+ `undo.plan_changed`, `undo.confirmation_required`, `undo.legacy_operation_unknown`,
181
+ `undo.snapshot_missing`, `undo.operation_mixed_policies`, `undo.plan_invalid` — none are forceable.
182
+
183
+ ## Storage port extension (engine authors)
184
+
185
+ `StoragePort` gains the OPTIONAL `operationLedger` capability (the `close?()` precedent). Engines
186
+ without it keep working in compat mode (undo answers `undo.storage_capability_missing`; strict refuses
187
+ to boot). Implementing it requires:
188
+
189
+ - persisting the kernel-written envelope (`EventOperationMeta`) beside the payload — a nullable JSON
190
+ column; legacy rows stay NULL (non-destructive migration),
191
+ - the event format version column set from `meta.eventVersion` (default 1) — replay AND the undo
192
+ planner read it with the same precedence: envelope first, then the row's version column, so both
193
+ paths always agree on which format version a row carries,
194
+ - indexes serving `eventsOfOperation` / `compensationsOf` (SQLite: expression indexes on `json_extract`),
195
+ - joining the same serialized write lane as every other writer.
196
+
197
+ The full method set: `appendDomainRowWithMeta`, `domainRowBySeq`, `eventsOfOperation`,
198
+ `compensationsOf`, `readSnapshot` (a consistent read snapshot wrapping preview composition). The
199
+ kernel's own tests ship a reference implementation (`test/sqlite-operation-storage.ts`).
200
+
201
+ ## Guarantees and non-guarantees
202
+
203
+ Guaranteed: 9-stage gating with first-class refusals, append-only ledger, idempotent retries, replay
204
+ determinism, audit completeness, contract-passed writes, catalog consistency at boot, undo atomicity·
205
+ single-compensation, deterministic content revisions, strict contract refusal before execution.
206
+
207
+ Not guaranteed: cross-process catalog-change push (each process seals its own view — reconnect and
208
+ compare `catalogStatus`; `tools/list_changed` and server push are NOT prerequisites), automatic
209
+ detection of semantic (non-structural) contract changes (declare them — `behaviorRevision`, release
210
+ manifests), and any judgement over business data (roles, scopes, history rights belong to the app).
211
+
212
+ ## Development
213
+
214
+ ```bash
215
+ npm run typecheck # tsc --noEmit
216
+ npm test # node --import tsx --test test/*.test.ts (temp DBs under the OS tmpdir)
217
+ npm run validate:releases <previous.json|null> <current.json> # release manifest check
218
+ ```
219
+
220
+ `validate:releases` is a REPOSITORY check command — `scripts/` is deliberately outside the published
221
+ `files` list; installed consumers validate manifests through `validateReleaseManifest` (exported).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sudoke/kernel",
3
- "version": "0.3.1",
4
- "description": "SUDOKE kernel \u2014 the 9-stage command gate, ledger, registries and async storage port behind every sudoke app",
3
+ "version": "0.4.0",
4
+ "description": "SUDOKE kernel — the 9-stage command gate, ledger, registries and async storage port behind every sudoke app",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "src"
@@ -16,8 +16,9 @@
16
16
  }
17
17
  },
18
18
  "scripts": {
19
- "typecheck": "tsc --noEmit",
20
- "test": "node --import tsx --test test/*.test.ts"
19
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json",
20
+ "test": "node --import tsx --test test/*.test.ts",
21
+ "validate:releases": "node --import tsx scripts/validate-release-manifest.mjs"
21
22
  },
22
23
  "dependencies": {
23
24
  "@modelcontextprotocol/sdk": "^1.32.1",
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Canonical JSON — the kernel's one serialization rule for hashing and comparison: object keys are
3
+ * sorted at every depth, so the same content yields the same bytes no matter the field order
4
+ * (agents rebuild JSON on retries; only array order is meaningfully part of a contract or request).
5
+ *
6
+ * The digest users (catalog revisions, the idempotency input hash, the undo plan hash) all hash the
7
+ * canonical form — never the raw object — which is what makes revisions boot-stable and request
8
+ * hashes retry-stable. Internal module: not exported through index.ts.
9
+ */
10
+ export function canonicalJson(v: unknown): string {
11
+ if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`
12
+ if (v && typeof v === 'object') {
13
+ const entries = Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
14
+ return `{${entries.map(([k, val]) => `${JSON.stringify(k)}:${canonicalJson(val)}`).join(',')}}`
15
+ }
16
+ if (typeof v === 'function') return '"[fn]"' // functional parts are declared through behaviorRevision, never captured
17
+ return JSON.stringify(v) ?? 'null'
18
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Catalog contracts — versions, revisions and the single manifest.
3
+ *
4
+ * A revision is a content fingerprint: a deterministic digest of the sealed contract content.
5
+ * The same content yields the same revision no matter the registration order or how many times the
6
+ * process boots (no timestamps, no paths, no runtime identity inside the hashed material — canonical
7
+ * serialization sorts object keys at every depth and preserves only meaningful array order). A revision
8
+ * change therefore MEANS a content change; it never proves compatibility — semver correctness stays a
9
+ * human declaration the release-manifest validator checks (releases.ts).
10
+ *
11
+ * Fields the kernel derives (catalogRevision·command·query revisions·viewRevision) are unkeyed digests
12
+ * (stable and comparable across restarts); the undo plan hash in undo.ts is the one keyed digest — it
13
+ * may embed business values, so it is HMAC'd with the deployment's server key, like the idempotency hash.
14
+ *
15
+ * viewRevision is the caller's personal view (visible contracts + permission perspective). The identity
16
+ * itself is never hashed — two users with the same view get the same viewRevision, so consumers may
17
+ * cache by viewRevision while role·delegation changes naturally move it.
18
+ */
19
+ import { createHash } from 'node:crypto'
20
+ import type { CommandDefinition, CatalogChangeRecord, CatalogRevisions, ContractResponseMeta, Identity } from './types.js'
21
+ import { defaultKernelState } from './state.js'
22
+ import { allCommands, allErrorCodes, allEventVersions, allTransitionMachines, allUndoPolicies, errorCodeOf, lookupCommand, undoHandlerOf } from './registry.js'
23
+ import { allQueries, describeShape, lookupQuery } from './queries.js'
24
+ import { commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
25
+ import { protocolPreamble } from './protocol.js'
26
+ import { canonicalJson } from './canonical.js'
27
+ import { fingerprintShape } from './contract-shape.js'
28
+
29
+ const revisionOf = (v: unknown) => 'r1:' + createHash('sha256').update(canonicalJson(v)).digest('hex')
30
+
31
+ /** The kernel protocol format version — the shape of catalog·common request/response·undo contracts
32
+ * this kernel speaks. Managed by kernel semver releases, independent of the npm package version and of
33
+ * any app's catalogVersion. */
34
+ export const PROTOCOL_VERSION = '1.0.0'
35
+
36
+ /** The full contract content of one command — hashed into its revision and embeddable into release
37
+ * manifests (the validator's structural breaking detection diffs these trees). Shared error-code
38
+ * definitions and referencing transition rules fold in, so a dictionary or table change moves every
39
+ * command it touches. */
40
+ export function commandContractShape(def: CommandDefinition<any>): unknown {
41
+ const errors = [...(def.errors ?? [])]
42
+ .sort()
43
+ .map((code) => {
44
+ const e = errorCodeOf(code)
45
+ return [code, e ? { description: e.description, recovery: e.recovery, ...(e.canForce ? { canForce: true } : {}) } : null]
46
+ })
47
+ const transitions: unknown[] = []
48
+ for (const [machine, rules] of Object.entries(allTransitionMachines()))
49
+ for (const r of rules)
50
+ if (r.command === def.name) transitions.push({ machine, from: r.from, to: r.to, roles: [...r.roles] })
51
+ transitions.sort((a, b) => (canonicalJson(a) < canonicalJson(b) ? -1 : 1))
52
+ return {
53
+ kind: 'command',
54
+ name: def.name,
55
+ version: def.version ?? null,
56
+ behaviorRevision: def.behaviorRevision ?? null,
57
+ description: def.description,
58
+ example: def.example ?? null,
59
+ deprecated: def.deprecated ?? null,
60
+ allowedRoles: [...def.allowedRoles],
61
+ scope: def.scope,
62
+ input: fingerprintShape(def.input),
63
+ output: fingerprintShape(def.output),
64
+ errors,
65
+ transitions,
66
+ }
67
+ }
68
+
69
+ /** The full contract content of one query — read contracts version too, so surfaces can detect read drift */
70
+ export function queryContractShape(def: import('./queries.js').QueryDefinition): unknown {
71
+ return {
72
+ kind: 'query',
73
+ name: def.name,
74
+ version: def.version ?? null,
75
+ behaviorRevision: def.behaviorRevision ?? null,
76
+ description: def.description,
77
+ clientScoped: def.clientScoped,
78
+ public: def.public ?? null,
79
+ allowedRoles: def.allowedRoles ? [...def.allowedRoles] : null,
80
+ params: Object.entries(def.params ?? {})
81
+ .sort(([a], [b]) => (a < b ? -1 : 1))
82
+ .map(([k, v]) => [k, fingerprintShape(v)]),
83
+ output: fingerprintShape(def.output),
84
+ }
85
+ }
86
+
87
+ /** Computes the revision index of the sealed assembly — called by completeAssembly right before the
88
+ * seal. Everything hashed here is registry content; nothing depends on time or boot count. */
89
+ export function computeCatalogRevisions(): CatalogRevisions {
90
+ const commands: Record<string, string> = {}
91
+ for (const def of allCommands()) commands[def.name] = revisionOf(commandContractShape(def))
92
+ const queries: Record<string, string> = {}
93
+ for (const def of allQueries()) queries[def.name] = revisionOf(queryContractShape(def))
94
+ const sorted = (o: Record<string, string>) => Object.keys(o).sort().map((n) => [n, o[n]])
95
+ const catalog = revisionOf({
96
+ kind: 'catalog',
97
+ protocolVersion: PROTOCOL_VERSION,
98
+ commands: sorted(commands),
99
+ queries: sorted(queries),
100
+ errorCodes: Object.entries(allErrorCodes())
101
+ .sort(([a], [b]) => (a < b ? -1 : 1))
102
+ .map(([code, def]) => [code, { description: def.description, recovery: def.recovery, ...(def.canForce ? { canForce: true } : {}) }]),
103
+ transitions: Object.entries(allTransitionMachines())
104
+ .sort(([a], [b]) => (a < b ? -1 : 1))
105
+ .map(([machine, rules]) => [machine, rules.map((r) => ({ from: r.from, to: r.to, command: r.command, roles: [...r.roles] }))]),
106
+ undoPolicies: Object.entries(allUndoPolicies())
107
+ .sort(([a], [b]) => (a < b ? -1 : 1))
108
+ .map(([type, p]) => [type, publishedUndoPolicy(p)]),
109
+ eventVersions: Object.entries(allEventVersions())
110
+ .sort(([a], [b]) => (a < b ? -1 : 1)),
111
+ protocol: protocolPreamble(),
112
+ })
113
+ return { catalog, commands, queries }
114
+ }
115
+
116
+ /** The published form of an undo policy — supported entries carry the HANDLER's version: the handler
117
+ * contract (what it plans, how it judges conflicts) is part of the undo surface, so its version moves
118
+ * the catalog revision and shows in the catalog document. (Event-scoped policies cannot be folded into
119
+ * per-command revisions statically — which command compensates for an event is a plan-time decision.
120
+ * catalogRevision·catalogStatus is the discovery surface for policy and handler changes.) */
121
+ export function publishedUndoPolicy(p: import('./types.js').EventUndoPolicy) {
122
+ // the mayRead hook is enforcement, not published contract (functions never serialize); `roles` IS
123
+ // published — it scopes this entry's catalog exposure and moves the catalog revision when it changes
124
+ return p.kind === 'supported'
125
+ ? { kind: p.kind, handlerId: p.handlerId, handlerVersion: undoHandlerOf(p.handlerId)?.version ?? null, ...(p.roles ? { roles: [...p.roles] } : {}) }
126
+ : { kind: p.kind, code: p.code, reason: p.reason, ...(p.roles ? { roles: [...p.roles] } : {}) }
127
+ }
128
+
129
+ /** Catalog exposure of undo policies — an entry scoped with `roles` shows only to those roles; an
130
+ * unscoped entry shows to every AUTHENTICATED identity. Exposure never mirrors the mayRead verdict
131
+ * (reading a policy entry and reading an operation are different questions). */
132
+ function visibleUndoPoliciesFor(identity: Identity | null) {
133
+ return Object.fromEntries(
134
+ Object.entries(allUndoPolicies())
135
+ .sort(([a], [b]) => (a < b ? -1 : 1))
136
+ .filter(([, p]) => identity !== null && (!p.roles || p.roles.includes(identity.role)))
137
+ .map(([type, p]) => [type, publishedUndoPolicy(p)]),
138
+ )
139
+ }
140
+
141
+ function requireRevisions(): CatalogRevisions {
142
+ const revisions = defaultKernelState.revisions
143
+ if (!revisions) throw new Error('Catalog revisions are computed at seal — the assembly is not sealed yet (completeAssembly)')
144
+ return revisions
145
+ }
146
+
147
+ /** The sealed content revision of one command — stable until its contract content changes */
148
+ export function commandRevisionOf(name: string): string | undefined {
149
+ return defaultKernelState.revisions?.commands[name]
150
+ }
151
+
152
+ /** The sealed content revision of one query */
153
+ export function queryRevisionOf(name: string): string | undefined {
154
+ return defaultKernelState.revisions?.queries[name]
155
+ }
156
+
157
+ /** The sealed revision of the whole catalog (all contracts, regardless of visibility) */
158
+ export function catalogRevisionOf(): string {
159
+ return requireRevisions().catalog
160
+ }
161
+
162
+ /** The revision of what THIS identity may see — the identity itself is not hashed; the permission
163
+ * perspective is: role, delegation scope shape, the assignment (business) scopes, and per-command
164
+ * restrictions. Assignment scopes join because a scope change re-decides every target-policy command
165
+ * for this caller — the view genuinely moved. Raw sorted scope strings only (no secrets, no user id). */
166
+ export function viewRevisionOf(identity: Identity | null): string {
167
+ const revisions = requireRevisions()
168
+ const commands = visibleCatalogMeta(identity)
169
+ .map((c: any) => [c.name, revisions.commands[c.name] ?? null, c.restriction ?? null])
170
+ .sort(([a], [b]) => (a[0] < b[0] ? -1 : 1))
171
+ const queries = visibleQueriesFor(identity)
172
+ .map((q) => [q.name, revisions.queries[q.name] ?? null])
173
+ .sort(([a], [b]) => (a[0] < b[0] ? -1 : 1))
174
+ return revisionOf({
175
+ kind: 'view',
176
+ catalog: revisions.catalog,
177
+ role: identity?.role ?? null,
178
+ delegation: identity?.delegation ? { scopes: [...identity.delegation.scopes].sort() } : null,
179
+ assignment: identity ? [...(identity.scopes ?? [])].sort() : null,
180
+ commands,
181
+ queries,
182
+ transitions: visibleTransitionMachinesFor(identity),
183
+ })
184
+ }
185
+
186
+ /** The single catalog manifest — one builder behind every transport (REST catalog endpoint, MCP catalog
187
+ * tool). Transport-specific dressing (tool names, endpoint paths) is added by the surface, never here. */
188
+ export function buildCatalogDocument(identity: Identity | null) {
189
+ const revisions = requireRevisions()
190
+ return {
191
+ protocolVersion: PROTOCOL_VERSION,
192
+ ...(defaultKernelState.catalogRelease ? { catalogVersion: defaultKernelState.catalogRelease.catalogVersion } : {}),
193
+ catalogRevision: revisions.catalog,
194
+ viewRevision: viewRevisionOf(identity),
195
+ protocol: protocolPreamble(),
196
+ transitions: visibleTransitionMachinesFor(identity),
197
+ errorCodes: allErrorCodes(),
198
+ undoPolicies: visibleUndoPoliciesFor(identity),
199
+ identity,
200
+ commands: visibleCatalogMeta(identity),
201
+ queries: visibleQueriesFor(identity).map((q) => ({
202
+ name: q.name,
203
+ description: q.description,
204
+ clientScoped: q.clientScoped,
205
+ public: q.public ?? false,
206
+ ...(q.allowedRoles ? { allowedRoles: q.allowedRoles } : {}),
207
+ params: Object.fromEntries(Object.entries(q.params ?? {}).map(([k, v]) => [k, describeShape(v)])),
208
+ output: describeShape(q.output),
209
+ ...(q.version ? { version: q.version } : {}),
210
+ revision: revisions.queries[q.name],
211
+ })),
212
+ }
213
+ }
214
+
215
+ /** Contract status for a caller — compare on reconnect; a difference means read the catalog again */
216
+ export function catalogStatus(identity: Identity | null) {
217
+ const revisions = requireRevisions()
218
+ return {
219
+ protocolVersion: PROTOCOL_VERSION,
220
+ ...(defaultKernelState.catalogRelease ? { catalogVersion: defaultKernelState.catalogRelease.catalogVersion } : {}),
221
+ catalogRevision: revisions.catalog,
222
+ viewRevision: viewRevisionOf(identity),
223
+ }
224
+ }
225
+
226
+ /** What changed since a revision the caller last learned. A diff is an optimization — the full catalog
227
+ * is always the source of truth, and a since the server cannot diff from answers fullRefreshRequired.
228
+ * Change records never confirm the existence of commands hidden to the caller. */
229
+ export function catalogChanges(
230
+ input: { since: string },
231
+ identity: Identity | null,
232
+ ):
233
+ | { upToDate: true; catalogRevision: string; viewRevision: string }
234
+ | { fullRefreshRequired: true; catalogRevision: string; viewRevision: string }
235
+ | { catalogVersion: string; catalogRevision: string; viewRevision: string; changes: CatalogChangeRecord[] } {
236
+ const revisions = requireRevisions()
237
+ if (input.since === revisions.catalog)
238
+ return { upToDate: true, catalogRevision: revisions.catalog, viewRevision: viewRevisionOf(identity) }
239
+ const release = defaultKernelState.catalogRelease
240
+ if (!release || !release.previousRevisions?.includes(input.since))
241
+ return { fullRefreshRequired: true, catalogRevision: revisions.catalog, viewRevision: viewRevisionOf(identity) }
242
+ return {
243
+ catalogVersion: release.catalogVersion,
244
+ catalogRevision: revisions.catalog,
245
+ viewRevision: viewRevisionOf(identity),
246
+ changes: (release.changes ?? []).filter((c) => mayReadChange(c, identity)),
247
+ }
248
+ }
249
+
250
+ /** A change record is readable when the declared roles allow it and it names no live contract the
251
+ * identity cannot see — a hidden command's existence is not confirmed through the change list either */
252
+ function mayReadChange(c: CatalogChangeRecord, identity: Identity | null): boolean {
253
+ if (!identity) return false
254
+ if (c.roles && !c.roles.includes(identity.role)) return false
255
+ if (c.name) {
256
+ const def = lookupCommand(c.name)
257
+ if (def) return commandAccessOf(def, identity).visible
258
+ const q = lookupQuery(c.name)
259
+ if (q && q.allowedRoles && !q.allowedRoles.includes(identity.role)) return false
260
+ }
261
+ return true
262
+ }
263
+
264
+ /** Current-contract meta for responses — attached to successes and replays alike (gate.ts, undo.ts).
265
+ * The revisions are CURRENT, never the stored producer's: a replayed result keeps its old payload
266
+ * while the meta says what is true now. */
267
+ export function responseMetaOf(commandName?: string, identity?: Identity): ContractResponseMeta {
268
+ const revisions = requireRevisions()
269
+ const def = commandName ? lookupCommand(commandName) : undefined
270
+ const q = !def && commandName ? lookupQuery(commandName) : undefined
271
+ const commandRevision = def ? revisions.commands[def.name] : q ? revisions.queries[q.name] : undefined
272
+ return {
273
+ protocolVersion: PROTOCOL_VERSION,
274
+ ...(defaultKernelState.catalogRelease ? { catalogVersion: defaultKernelState.catalogRelease.catalogVersion } : {}),
275
+ catalogRevision: revisions.catalog,
276
+ // the caller's PERSONAL view revision — it also moves when their permissions move, so a client
277
+ // can detect a visibility change without re-reading the catalog (protocol: success meta carries it)
278
+ ...(identity ? { viewRevision: viewRevisionOf(identity) } : {}),
279
+ ...(def?.version ? { commandVersion: def.version } : {}),
280
+ ...(commandRevision ? { commandRevision } : {}),
281
+ }
282
+ }