@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/src/registry.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { GateError, type CommandDefinition, type ErrorCodeDefinition } from './types.js'
1
+ import { GateError, type CommandDefinition, type ErrorCodeDefinition, type EventUndoPolicy, type UndoHandler, 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'
5
+ import { commandRevisionOf, computeCatalogRevisions } from './catalog.js'
6
+ import { SEMVER_RE } from './releases.js'
5
7
 
6
8
  /**
7
9
  * Kernel registry — registers and looks up command definitions and transition tables (S-03).
@@ -73,13 +75,16 @@ export function catalogMeta() {
73
75
  scope: d.scope,
74
76
  hasTransition: !!d.transition,
75
77
  ...(d.deprecated ? { deprecated: d.deprecated } : {}),
76
- fields: Object.fromEntries(
77
- Object.entries(inputShapeOf(d.input))
78
- .map(([k, v]) => [k, describeOf(v)])
79
- .filter(([, v]) => !!v),
80
- ),
78
+ // EVERY field is listed (null when undocumented) — a field without .describe() is still part of
79
+ // the contract shape and must not vanish from the catalog; the machine-readable shape (types,
80
+ // required-ness, checks, defaults) is published separately through command_contract
81
+ fields: Object.fromEntries(Object.entries(inputShapeOf(d.input)).map(([k, v]) => [k, describeOf(v) ?? null])),
81
82
  output: describeShape(d.output),
82
83
  errors: (d.errors ?? []).map((code) => ({ code, ...(errorCodeOf(code) ?? { description: '(unregistered code)', recovery: 'stop' as const }) })),
84
+ // Contract version (domain-declared) and content revision (kernel-computed at seal) — consumers
85
+ // detect drift without re-reading the whole catalog
86
+ ...(d.version ? { version: d.version } : {}),
87
+ revision: commandRevisionOf(d.name),
83
88
  }))
84
89
  }
85
90
 
@@ -153,6 +158,68 @@ export const errorCodeOf = (code: string): ErrorCodeDefinition | undefined => de
153
158
  export const allErrorCodes = (): Record<string, ErrorCodeDefinition> =>
154
159
  Object.fromEntries([...defaultKernelState.errorCodes.entries()])
155
160
 
161
+ /** Undo-policy registration — one policy per event type, both kinds explicit: 'supported' names the
162
+ * handler that plans the compensation, 'unavailable' carries a stable code and a concrete reason the
163
+ * catalog publishes as-is. The kernel never guesses a reversal from payload field names — what is not
164
+ * declared supported is unavailable. Handler references resolve at the seal (registration order free). */
165
+ export function registerUndoPolicies(policies: Record<string, EventUndoPolicy>): void {
166
+ assertOpenFor(defaultKernelState, 'registerUndoPolicies')
167
+ for (const [type, policy] of Object.entries(policies)) {
168
+ if (defaultKernelState.undoPolicies.has(type)) throw new Error(`Undo policy registered twice: ${type}`)
169
+ if (policy.kind === 'supported') {
170
+ if (!policy.handlerId) throw new Error(`A supported undo policy needs a handlerId: ${type}`)
171
+ } else if (policy.kind === 'unavailable') {
172
+ if (!policy.code?.trim() || !policy.reason?.trim())
173
+ throw new Error(`An unavailable undo policy needs a stable code and a concrete reason: ${type}`)
174
+ } else {
175
+ throw new Error(`Unknown undo policy kind for ${type}: ${String((policy as { kind?: string }).kind)}`)
176
+ }
177
+ defaultKernelState.undoPolicies.set(type, frozenCopyOf({ ...policy }) as EventUndoPolicy)
178
+ }
179
+ }
180
+
181
+ /** Undo-handler registration — the domain's compensation planner. plan() is read-only and runs inside
182
+ * one consistent read snapshot (preview) or inside the execution transaction (execute). */
183
+ export function registerUndoHandler(handler: UndoHandler): void {
184
+ assertOpenFor(defaultKernelState, `registerUndoHandler ${handler.id}`)
185
+ if (!handler.id?.trim() || !handler.version?.trim() || typeof handler.plan !== 'function')
186
+ throw new Error('An undo handler needs id, version and a plan function')
187
+ if (defaultKernelState.undoHandlers.has(handler.id)) throw new Error(`Undo handler registered twice: ${handler.id}`)
188
+ defaultKernelState.undoHandlers.set(handler.id, frozenCopyOf({ ...handler }) as UndoHandler)
189
+ }
190
+
191
+ export const undoPolicyOf = (type: string): EventUndoPolicy | undefined => defaultKernelState.undoPolicies.get(type)
192
+ export const undoHandlerOf = (id: string): UndoHandler | undefined => defaultKernelState.undoHandlers.get(id)
193
+ /** All registered undo policies — a fresh record, published by the catalog document */
194
+ export const allUndoPolicies = (): Record<string, EventUndoPolicy> => Object.fromEntries([...defaultKernelState.undoPolicies.entries()])
195
+
196
+ /** Event payload format versions — domain-managed, independent of command versions. Absent = 1.
197
+ * Recorded on the event envelope by engines with the operation-ledger capability. */
198
+ export function registerEventVersions(versions: Record<string, number>): void {
199
+ assertOpenFor(defaultKernelState, 'registerEventVersions')
200
+ for (const [type, version] of Object.entries(versions)) {
201
+ if (!Number.isInteger(version) || version < 1) throw new Error(`Event version must be a positive integer: ${type} → ${version}`)
202
+ if (defaultKernelState.eventVersions.has(type)) throw new Error(`Event version registered twice: ${type}`)
203
+ defaultKernelState.eventVersions.set(type, version)
204
+ }
205
+ }
206
+
207
+ export const eventVersionOf = (type: string): number | undefined => defaultKernelState.eventVersions.get(type)
208
+ /** All registered event versions — a fresh record (catalog fingerprint input) */
209
+ export const allEventVersions = (): Record<string, number> => Object.fromEntries([...defaultKernelState.eventVersions.entries()])
210
+
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
+ /** Registers the served catalog release declaration — the app-declared compatibility version plus the
215
+ * change list of this release (what catalogChanges serves and the release validator checks). */
216
+ export function registerCatalogRelease(release: CatalogRelease): void {
217
+ assertOpenFor(defaultKernelState, 'registerCatalogRelease')
218
+ if (!release.catalogVersion?.trim() || !SEMVER_RE.test(release.catalogVersion))
219
+ throw new Error(`catalogRelease.catalogVersion must be semver: ${String(release.catalogVersion)}`)
220
+ defaultKernelState.catalogRelease = frozenCopyOf({ ...release })
221
+ }
222
+
156
223
  /**
157
224
  * Catalog consistency check — called after app assembly to find contradictions between
158
225
  * transition tables (descriptions) and commands (execution permissions). A table's roles are
@@ -208,6 +275,52 @@ export function catalogConsistencyErrors(): string[] {
208
275
  if (scoped.length > 0)
209
276
  errors.push(`Commands with a scope require a registered app policy (registerAppPolicy): [${scoped.join(', ')}]`)
210
277
  }
278
+ // Undo declarations must resolve — both modes. What is declared must exist; the catalog must not lie.
279
+ for (const [type, policy] of s.undoPolicies) {
280
+ if (!s.eventContracts.has(type)) errors.push(`Undo policy references an unregistered event type: ${type}`)
281
+ if (policy.kind === 'supported' && !s.undoHandlers.has(policy.handlerId))
282
+ errors.push(`Undo policy references an unregistered handler: ${type} → '${policy.handlerId}'`)
283
+ if (policy.kind === 'unavailable' && !s.errorCodes.has(policy.code))
284
+ errors.push(`Unavailable undo policy references an unregistered error code: ${type} → '${policy.code}'`)
285
+ }
286
+ for (const id of s.undoHandlers.keys())
287
+ if (![...s.undoPolicies.values()].some((p) => p.kind === 'supported' && p.handlerId === id))
288
+ errors.push(`Undo handler is referenced by no policy: ${id} — a dead registration is a defect`)
289
+ for (const type of s.eventVersions.keys())
290
+ if (!s.eventContracts.has(type)) errors.push(`Event version references an unregistered event type: ${type}`)
291
+ // the contract regime — undo coverage, declared versions, storage capability. Failing here
292
+ // fails the boot (completeAssembly) — never a partial feature that quietly does less.
293
+ {
294
+ const missingPolicies = [...s.eventContracts.keys()].filter((t) => !s.undoPolicies.has(t))
295
+ if (missingPolicies.length > 0)
296
+ errors.push(`an undo policy is required for every registered event type — missing: [${missingPolicies.join(', ')}]`)
297
+ const badVersions = [...s.commands.values()].filter((d) => d.version !== undefined && !SEMVER_RE.test(d.version)).map((d) => d.name)
298
+ if (badVersions.length > 0) errors.push(`valid semver command versions are required: [${badVersions.join(', ')}]`)
299
+ const versionless = [...s.commands.values()].filter((d) => d.version === undefined).map((d) => d.name)
300
+ if (versionless.length > 0)
301
+ errors.push(`a declared version is required on every command — missing: [${versionless.join(', ')}]`)
302
+ const versionlessQueries = [...s.queries.values()].filter((q) => q.version === undefined).map((q) => q.name)
303
+ if (versionlessQueries.length > 0)
304
+ errors.push(`a declared version is required on every query — missing: [${versionlessQueries.join(', ')}]`)
305
+ const badQueryVersions = [...s.queries.values()].filter((q) => q.version !== undefined && !SEMVER_RE.test(q.version)).map((q) => q.name)
306
+ if (badQueryVersions.length > 0)
307
+ errors.push(`valid semver query versions are required: [${badQueryVersions.join(', ')}]`)
308
+ // (the release catalogVersion is semver-checked at registration time, in every mode — no strict duplicate here)
309
+ const hookless = [...s.undoHandlers.values()].filter((h) => typeof h.mayPreview !== 'function').map((h) => h.id)
310
+ if (hookless.length > 0)
311
+ errors.push(
312
+ `a mayPreview hook is required on every undo handler — history-read rights are a declared decision, never a default allow — missing: [${hookless.join(', ')}]`,
313
+ )
314
+ // 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
316
+ const readless = [...s.undoPolicies.entries()].filter(([, p]) => typeof p.mayRead !== 'function').map(([t]) => t)
317
+ if (readless.length > 0)
318
+ errors.push(
319
+ `a mayRead hook is required on every undo policy — origin-read rights are a declared decision, never a default allow — missing: [${readless.join(', ')}]`,
320
+ )
321
+ if (!s.storage?.operationLedger)
322
+ errors.push('the registered storage engine does not provide the operation-ledger capability — the kernel requires it')
323
+ }
211
324
  return errors
212
325
  }
213
326
 
@@ -222,6 +335,9 @@ export function completeAssembly(): void {
222
335
  const errors = catalogConsistencyErrors()
223
336
  if (errors.length > 0)
224
337
  throw new Error(`Catalog inconsistencies — assembly defect, execution refused: ${errors.join(' / ')}`)
338
+ // Content revisions are computed once, over the sealed content — registration order no longer matters
339
+ // here, and the same content yields the same revision on every boot (nothing time- or path-derived).
340
+ defaultKernelState.revisions = computeCatalogRevisions()
225
341
  sealFor(defaultKernelState)
226
342
  }
227
343