@sudoke/kernel 0.3.0 → 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/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 KernelOptions, 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,76 @@ 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
+ export function configureKernel(options: KernelOptions): void {
215
+ assertOpenFor(defaultKernelState, 'configureKernel')
216
+ if (options.mode !== 'compat' && options.mode !== 'strict') throw new Error(`Unknown kernel mode: ${String((options as { mode?: string }).mode)}`)
217
+ defaultKernelState.options = frozenCopyOf({ ...options })
218
+ }
219
+
220
+ export const kernelOptions = (): KernelOptions => defaultKernelState.options ?? { mode: 'compat' }
221
+
222
+ /** Registers the served catalog release declaration — the app-declared compatibility version plus the
223
+ * change list of this release (what catalogChanges serves and the release validator checks). */
224
+ export function registerCatalogRelease(release: CatalogRelease): void {
225
+ assertOpenFor(defaultKernelState, 'registerCatalogRelease')
226
+ if (!release.catalogVersion?.trim() || !SEMVER_RE.test(release.catalogVersion))
227
+ throw new Error(`catalogRelease.catalogVersion must be semver: ${String(release.catalogVersion)}`)
228
+ defaultKernelState.catalogRelease = frozenCopyOf({ ...release })
229
+ }
230
+
156
231
  /**
157
232
  * Catalog consistency check — called after app assembly to find contradictions between
158
233
  * transition tables (descriptions) and commands (execution permissions). A table's roles are
@@ -208,6 +283,52 @@ export function catalogConsistencyErrors(): string[] {
208
283
  if (scoped.length > 0)
209
284
  errors.push(`Commands with a scope require a registered app policy (registerAppPolicy): [${scoped.join(', ')}]`)
210
285
  }
286
+ // Undo declarations must resolve — both modes. What is declared must exist; the catalog must not lie.
287
+ for (const [type, policy] of s.undoPolicies) {
288
+ if (!s.eventContracts.has(type)) errors.push(`Undo policy references an unregistered event type: ${type}`)
289
+ if (policy.kind === 'supported' && !s.undoHandlers.has(policy.handlerId))
290
+ errors.push(`Undo policy references an unregistered handler: ${type} → '${policy.handlerId}'`)
291
+ if (policy.kind === 'unavailable' && !s.errorCodes.has(policy.code))
292
+ errors.push(`Unavailable undo policy references an unregistered error code: ${type} → '${policy.code}'`)
293
+ }
294
+ for (const id of s.undoHandlers.keys())
295
+ if (![...s.undoPolicies.values()].some((p) => p.kind === 'supported' && p.handlerId === id))
296
+ errors.push(`Undo handler is referenced by no policy: ${id} — a dead registration is a defect`)
297
+ for (const type of s.eventVersions.keys())
298
+ if (!s.eventContracts.has(type)) errors.push(`Event version references an unregistered event type: ${type}`)
299
+ // strict mode — the full contract regime: undo coverage, declared versions, storage capability.
300
+ // Failing here fails the boot (completeAssembly) — never a partial feature that quietly does less.
301
+ if ((s.options?.mode ?? 'compat') === 'strict') {
302
+ const missingPolicies = [...s.eventContracts.keys()].filter((t) => !s.undoPolicies.has(t))
303
+ if (missingPolicies.length > 0)
304
+ errors.push(`strict mode requires an undo policy for every registered event type — missing: [${missingPolicies.join(', ')}]`)
305
+ const badVersions = [...s.commands.values()].filter((d) => d.version !== undefined && !SEMVER_RE.test(d.version)).map((d) => d.name)
306
+ if (badVersions.length > 0) errors.push(`strict mode requires valid semver command versions: [${badVersions.join(', ')}]`)
307
+ const versionless = [...s.commands.values()].filter((d) => d.version === undefined).map((d) => d.name)
308
+ if (versionless.length > 0)
309
+ errors.push(`strict mode requires a declared version on every command — missing: [${versionless.join(', ')}]`)
310
+ const versionlessQueries = [...s.queries.values()].filter((q) => q.version === undefined).map((q) => q.name)
311
+ if (versionlessQueries.length > 0)
312
+ errors.push(`strict mode requires a declared version on every query — missing: [${versionlessQueries.join(', ')}]`)
313
+ const badQueryVersions = [...s.queries.values()].filter((q) => q.version !== undefined && !SEMVER_RE.test(q.version)).map((q) => q.name)
314
+ if (badQueryVersions.length > 0)
315
+ errors.push(`strict mode requires valid semver query versions: [${badQueryVersions.join(', ')}]`)
316
+ // (the release catalogVersion is semver-checked at registration time, in every mode — no strict duplicate here)
317
+ const hookless = [...s.undoHandlers.values()].filter((h) => typeof h.mayPreview !== 'function').map((h) => h.id)
318
+ if (hookless.length > 0)
319
+ errors.push(
320
+ `strict mode requires a mayPreview hook on every undo handler — history-read rights are a declared decision, never a default allow — missing: [${hookless.join(', ')}]`,
321
+ )
322
+ // the OPERATION-level read gate is a declared decision too — unavailable and mixed branches answer
323
+ // operation facts, so every policy (not only supported handlers) must state who may read them
324
+ const readless = [...s.undoPolicies.entries()].filter(([, p]) => typeof p.mayRead !== 'function').map(([t]) => t)
325
+ if (readless.length > 0)
326
+ errors.push(
327
+ `strict mode requires a mayRead hook on every undo policy — origin-read rights are a declared decision, never a default allow — missing: [${readless.join(', ')}]`,
328
+ )
329
+ if (!s.storage?.operationLedger)
330
+ errors.push('strict mode requires the operation-ledger storage capability — the registered engine does not provide it')
331
+ }
211
332
  return errors
212
333
  }
213
334
 
@@ -222,6 +343,9 @@ export function completeAssembly(): void {
222
343
  const errors = catalogConsistencyErrors()
223
344
  if (errors.length > 0)
224
345
  throw new Error(`Catalog inconsistencies — assembly defect, execution refused: ${errors.join(' / ')}`)
346
+ // Content revisions are computed once, over the sealed content — registration order no longer matters
347
+ // here, and the same content yields the same revision on every boot (nothing time- or path-derived).
348
+ defaultKernelState.revisions = computeCatalogRevisions()
225
349
  sealFor(defaultKernelState)
226
350
  }
227
351