@sudoke/kernel 0.3.1 → 0.5.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,224 @@
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 single assembly regime, 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
+ registerUndoPolicies, registerUndoHandler, registerCatalogRelease,
21
+ catalogConsistencyErrors, sealRegistries,
22
+ } from '@sudoke/kernel'
23
+
24
+ registerStorage(engine) // physical layer first (e.g. sqliteStorage)
25
+ registerRoles([...]) // the app's role vocabulary
26
+ registerEventContracts({...}) // payload contracts — writes check against them
27
+ registerUndoPolicies({...}) // per event type: supported(handlerId) | unavailable(code, reason)
28
+ registerUndoHandler({...}) // the domain's compensation planner
29
+ registerCommand({...}) // name·schema·output·roles·hooks·version
30
+ registerQuery({...}) // read contracts version too
31
+ catalogConsistencyErrors() // empty = consistent (boot may fail the assembly here)
32
+ sealRegistries()
33
+ ```
34
+
35
+ The seal is automatic at the first execution (`completeAssembly`) — there is no path that seals without
36
+ the consistency check.
37
+
38
+ ## The contract regime (one mode)
39
+
40
+ There is a single assembly regime — the historical compat/strict split was removed in 0.5.0. The
41
+ consistency check demands, at seal time:
42
+
43
+ - an undo policy for every registered event type (declaring support or `{ kind: 'unavailable' }` —
44
+ the answer is declared, silence is a defect), each with a `mayRead` hook (origin-read rights are a
45
+ declared decision, never a default allow), and every undo handler a `mayPreview` hook;
46
+ - a declared semver version on every command and query;
47
+ - a storage engine providing the operation-ledger capability.
48
+
49
+ An assembly lacking any of these fails the boot — never a partial feature that quietly does less.
50
+
51
+
52
+ ## Command versions, revisions and the single manifest
53
+
54
+ | Field | Meaning | Managed by |
55
+ |---|---|---|
56
+ | `protocolVersion` (`PROTOCOL_VERSION`) | the kernel's own catalog·request/response·undo contract format | kernel semver |
57
+ | `catalogVersion` | the app's whole-contract compatibility version (`registerCatalogRelease`) | domain release |
58
+ | `catalogRevision` | content fingerprint of the sealed catalog | kernel (deterministic) |
59
+ | `commands[].version` / `queries[].version` | that contract's compatibility version (domain-declared semver) | domain release |
60
+ | `commands[].revision` / `queries[].revision` | that contract's content fingerprint (schema details, description, referenced error codes, transition rules, behaviorRevision) | kernel (deterministic) |
61
+ | `viewRevision` | fingerprint of what THIS identity may see (role ∩ delegation); the identity itself is not hashed | kernel (deterministic) |
62
+ | `eventVersion` | event payload format version (`registerEventVersions`), independent of command versions | domain |
63
+
64
+ Revisions are content-derived: the same content yields the same revision regardless of registration
65
+ order or boot count; a revision change MEANS a content change. What a fingerprint cannot capture —
66
+ functional refine bodies, business semantics — is declared through `behaviorRevision` (folded into the
67
+ revision). The kernel never claims the hash discovers meaning changes by itself.
68
+
69
+ APIs (transport-independent; surfaces own paths and polling):
70
+
71
+ - `buildCatalogDocument(identity)` — the single manifest every transport derives from (REST endpoint,
72
+ MCP catalog tool). Adds `protocolVersion`·revisions·`undoPolicies` to the historical content; the
73
+ per-command `fields` map lists EVERY input field (`null` when undocumented — a field never vanishes
74
+ from the catalog for lacking a `.describe()`). The MACHINE-READABLE contract (types·required-ness·
75
+ checks·defaults) is published per command through the `command_contract` MCP tool and the
76
+ `commandContractShape` export — the same canonical shape the revision fingerprint is computed from,
77
+ so the published contract and the fingerprint can never drift apart.
78
+ - `catalogStatus(identity)` — the cheap reconnect comparison (the view covers role, delegation scopes
79
+ AND the caller's assignment scopes — a scope change moves viewRevision).
80
+ - `catalogChanges({ since }, identity)` — `upToDate` | a permission-filtered change list | `fullRefreshRequired`
81
+ (a diff is an optimization; the full catalog is always the source of truth; hidden commands are never
82
+ confirmed through the change list).
83
+ - `validateReleaseManifest(prev, curr)` (+ `npm run validate:releases` in this package) — fails a release
84
+ whose contracts changed without a change record, or whose structurally identifiable breaks lack a
85
+ MAJOR bump; semantic compatibility stays the release author's explicit classification.
86
+
87
+ ### Writes carry a contract
88
+
89
+ ```
90
+ { ...businessInput, contract: { commandVersion, commandRevision, protocolVersion } }
91
+ ```
92
+
93
+ The contract rides beside the business input (stripped before the schema), is refused before execution
94
+ when stale (`gate.contract_changed`) or absent (`gate.contract_required`), and joins the idempotency
95
+ hash — the same key with a new contract is an input conflict, never a replay. A stored success replays
96
+ even when the current schema or contract would refuse the resent input (the replay probe precedes the
97
+ checks — in EVERY transport: the MCP tool schema DESCRIBES the contract for clients but never judges or
98
+ normalizes, so the raw request reaches the gate byte-for-byte as sent). A replay hit is a fresh READ:
99
+ the RECORDED rights material (role, scope, normalized target, preserved with every idempotency row —
100
+ per item for batches) is re-proven against the current identity, delegation range and app policy; a
101
+ row without material is unprovable and refused, never read as "no restriction". Batch items each carry
102
+ a contract, judged BEFORE the business schema (the same order as single commands); one stale item
103
+ refuses the whole batch before execution. Success responses carry `meta` — the CURRENT revisions,
104
+ including the caller's `viewRevision`. A replayed
105
+ success additionally carries `producedBy` — the contract that PRODUCED the stored result (commandName·
106
+ versions·protocolVersion·the role that executed); rows older than producer tracking answer
107
+ `{ unknown: true }`. Redeliveries re-check the current rights first — undo redeliveries re-derive the
108
+ permission view structurally (the verdict never depends on error-code spelling), and a removed
109
+ command's stored result returns only while the account is valid AND the recorded rights still hold:
110
+ the producer's role AND, for scoped commands, the app policy's verdict on the RECORDED normalized
111
+ target (stamped beside every result and on every event envelope as `policyTarget` at write time —
112
+ the verdict never guesses targets from aggregate ids). A moved role, a denied target, a revoked
113
+ history right or an unprovable row gets a clear refusal — never the result, never a re-run.
114
+
115
+ ## Undo (restore)
116
+
117
+ Undo is a NEW WRITE, never a rewrite: the original ledger rows stay untouched; the compensation is one
118
+ registered command re-entering the full gate; compensation events carry the undo linkage on their
119
+ envelope (`undoOfOperationId`·`undoSourceSeq`·`undoHandlerVersion`).
120
+
121
+ ```ts
122
+ const status = await undoStatus({ sourceSeqs: [seq] }, identity) // per-seq support·processing state
123
+ const preview = await previewUndo({ sourceSeq: seq }, identity)
124
+ // preview.status: available | warning | blocked | unavailable | already_undone
125
+ // preview.changes (before = current value, after = the value execution will set), losses, blockers, planHash
126
+ const done = await executeUndo(
127
+ { sourceSeq: seq, expectedPlanHash: preview.planHash, acceptLosses: true, requestKey: 'retry-key' },
128
+ identity,
129
+ )
130
+ ```
131
+
132
+ Contract highlights:
133
+
134
+ - **The unit is the operation** — one atomic command run (batch items are separate operations under one
135
+ batchId). Selecting any event row of the operation resolves to the whole operation; partial undo does
136
+ not exist. `undoStatus` and `previewUndo` share ONE per-operation judgment — every event row of one
137
+ operation answers the same read verdict and the same undo consensus (a single unavailable event type
138
+ makes the whole operation unavailable; multiple handlers answer `undo.operation_mixed_policies`),
139
+ while the response keeps the requested seq as the anchor.
140
+ - **The planner is domain-owned** (`registerUndoHandler`): `plan(source, identity)` is read-only and
141
+ returns exactly one registered compensation command, `dependsOn` state tokens, `changes`·`preserved`·
142
+ `losses`·`blockers`. The plan is machine-consumed, so the kernel validates its shape completely
143
+ (required `changes` array, string `preserved` entries, JSON-representable `before`/`after`,
144
+ non-negative integer loss counts) — a malformed plan answers `undo.plan_invalid` and never reaches
145
+ the hash, the preview or the execution.
146
+ - **Origin-read rights live on the POLICY** (`mayRead` on every `registerUndoPolicies` entry) — REQUIRED
147
+ in strict mode: it runs before ANY branch (supported·unavailable·mixed·legacy·already-undone) answers
148
+ anything about an operation, and a refusal carries no operation facts (no id, no processing state, no
149
+ policy reason). Supported handlers refine further with `mayPreview` (equally required). An
150
+ optional `roles` on the policy scopes its CATALOG exposure; exposure and the read verdict are
151
+ independent decisions.
152
+ - **The preview judges the compensation through the SAME static+dynamic checks a direct call would
153
+ face** (schema·delegation·role·app-policy target·preconditions·invariants·transitions) — 'available'
154
+ means a call NOW would pass stages 1~7; a denied target blocks and leaks nothing (status answers
155
+ carry a 'denied' state too).
156
+ - **Conflicts are sequence-based, never value-based** — the planner decides with ledger facts; a later
157
+ same-field change blocks even when the value round-tripped. Hard conflicts are never forceable; the
158
+ confirmation pair is `acceptLosses` + `expectedPlanHash` (`undo.confirmation_required`,
159
+ `undo.plan_changed`).
160
+ - **A successful compensation must write events** — the one-compensation guard and undo status read the
161
+ ledger linkage on compensation events; a zero-event compensation would be an unprovable, repeatable
162
+ success, so it is refused whole (`undo.plan_invalid`) and nothing commits.
163
+ - **Previews mask secrets by both rules** — the shared key rule (`password`-named keys) and, for
164
+ normalized change entries, the field-name rule: a change whose `field` is named like a secret has its
165
+ `before`/`after` masked. Domains remain responsible for never planning secret restorations at all.
166
+ - **Execution re-derives everything inside one write-lock transaction**: current identity, the plan, the
167
+ hash, the loss confirmation, and the one-compensation-per-source guard — then the compensation runs
168
+ through the shared gate pipeline (no bypass lane, no nested transaction), and events·linkage·
169
+ idempotency·audit commit or roll back together.
170
+ - **Undoing an undo** compensates the compensation — it is a normal operation with its own policy. Undo
171
+ handler versions are catalog content: a handler bump moves catalogRevision (and the published policy
172
+ carries `handlerVersion`); per-command revisions stay stable — which command compensates an event is a
173
+ plan-time decision, so catalogRevision·catalogStatus is the discovery surface for policy changes.
174
+ - **Legacy rows** (written before the envelope) are addressed by exact seq; unprovable grouping answers
175
+ `undo.legacy_operation_unknown`, missing prior state `undo.snapshot_missing`.
176
+
177
+ Kernel-common error codes involved: `gate.contract_required`, `gate.contract_changed`,
178
+ `undo.source_not_found`, `undo.unavailable`, `undo.storage_capability_missing`, `undo.already_undone`,
179
+ `undo.plan_changed`, `undo.confirmation_required`, `undo.legacy_operation_unknown`,
180
+ `undo.snapshot_missing`, `undo.operation_mixed_policies`, `undo.plan_invalid` — none are forceable.
181
+
182
+ ## Storage port extension (engine authors)
183
+
184
+ `StoragePort` gains the OPTIONAL `operationLedger` capability (the `close?()` precedent). Engines
185
+ without it cannot boot (the kernel requires the capability — undo is part of the contract)
186
+ to boot). Implementing it requires:
187
+
188
+ - persisting the kernel-written envelope (`EventOperationMeta`) beside the payload — a nullable JSON
189
+ column; legacy rows stay NULL (non-destructive migration),
190
+ - the event format version column set from `meta.eventVersion` (default 1) — replay AND the undo
191
+ planner read it with the same precedence: envelope first, then the row's version column, so both
192
+ paths always agree on which format version a row carries,
193
+ - indexes serving `eventsOfOperation` / `compensationsOf` (SQLite: expression indexes on `json_extract`),
194
+ - joining the same serialized write lane as every other writer.
195
+
196
+ The full method set: `appendDomainRowWithMeta`, `domainRowBySeq`, `eventsOfOperation`,
197
+ `compensationsOf`, `readSnapshot` (a consistent read snapshot wrapping preview composition). The
198
+ kernel's own tests ship a reference implementation (`test/sqlite-operation-storage.ts`).
199
+
200
+ ## Guarantees and non-guarantees
201
+
202
+ Guaranteed: 9-stage gating with first-class refusals, append-only ledger, idempotent retries, replay
203
+ determinism, audit completeness, contract-passed writes, catalog consistency at boot, undo atomicity·
204
+ single-compensation, deterministic content revisions, contract refusal before execution.
205
+
206
+ Not guaranteed: cross-process catalog-change push (each process seals its own view — reconnect and
207
+ compare `catalogStatus`; `tools/list_changed` and server push are NOT prerequisites), automatic
208
+ detection of semantic (non-structural) contract changes (declare them — `behaviorRevision`, release
209
+ manifests), and any judgement over business data (roles, scopes, history rights belong to the app).
210
+
211
+ ## Development
212
+
213
+ ```bash
214
+ npm run typecheck # tsc --noEmit
215
+ npm test # node --import tsx --test test/*.test.ts (temp DBs under the OS tmpdir)
216
+ npm run validate:releases <previous.json|null> <current.json> # release manifest check
217
+ ```
218
+
219
+ `validate:releases` is a REPOSITORY check command — `scripts/` is deliberately outside the published
220
+ `files` list; installed consumers validate manifests through `validateReleaseManifest` (exported).
221
+
222
+ ## Upgrading from 0.3.x
223
+
224
+ See [the upgrade guide](https://github.com/lancemoon/sudoke/blob/main/docs/agents/dev/kernel-upgrade-guide.md) (Korean) — dependency bumps, the 0.4→0.5 check items (`catalogVersion` rename, full `fields` listing, new MCP common tools, replay rights re-proof) and the now-mandatory contract regime.
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.5.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",
@@ -26,6 +27,7 @@
26
27
  },
27
28
  "devDependencies": {
28
29
  "@types/node": "^22.10.2",
30
+ "tsx": "^4.19.2",
29
31
  "typescript": "^5.7.2"
30
32
  }
31
33
  }
@@ -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
+ }