@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/storage.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { DomainEvent } from './types.js'
1
+ import type { DomainEvent, EventOperationMeta } from './types.js'
2
2
  import { assertOpenFor, defaultKernelState } from './state.js'
3
3
 
4
4
  /**
@@ -78,6 +78,10 @@ export interface LedgerRow {
78
78
  aggregate_type: string | null
79
79
  aggregate_id: string | null
80
80
  payload: string
81
+ /** Event format version (defaults to 1; legacy rows carry none) — engines with the operation-ledger capability persist it */
82
+ version?: number
83
+ /** Event envelope (EventOperationMeta as JSON) — present only on engines with the operation-ledger capability */
84
+ meta?: string
81
85
  }
82
86
  export interface IdempotencyHit {
83
87
  inputHash: string
@@ -123,6 +127,34 @@ export interface StoragePort {
123
127
  rebuild<T>(clearTables: readonly string[], fn: () => Promise<T>): Promise<T>
124
128
  /** Release the physical connection (optional) — file removal, e.g. test cleanup, requires it on platforms that lock open files */
125
129
  close?(): void
130
+
131
+ /** Operation-ledger extension (optional capability — the close?() precedent). Engines that implement
132
+ * it persist the kernel's event envelope (EventOperationMeta) beside the payload and serve the exact
133
+ * lookups the undo contract needs. Engines without it keep working unchanged: the kernel runs in
134
+ * an assembly without it refuses to boot — the undo APIs answer undo.storage_capability_missing only
135
+ * to boot without it. Write methods here join the same serialized write lane as every other writer.
136
+ *
137
+ * Implementation requirements for engine authors (SQLite shape; other engines equivalently):
138
+ * - a nullable metadata column beside the payload (JSON of EventOperationMeta) — legacy rows stay NULL
139
+ * - the event format version column set from meta.eventVersion (default 1)
140
+ * - indexes serving eventsOfOperation and compensationsOf (SQLite: expression indexes on json_extract)
141
+ * - a non-destructive migration adding the column to existing databases */
142
+ operationLedger?: OperationLedgerCapability
143
+ }
144
+
145
+ /** The operation-ledger capability — exact operation lookups for the undo contract */
146
+ export interface OperationLedgerCapability {
147
+ /** Physical append carrying the envelope (format validation stays kernel-side in the gate) — returns the sequence */
148
+ appendDomainRowWithMeta(e: DomainEvent, ts: string, meta: EventOperationMeta): Promise<number>
149
+ /** The exact row at a sequence — domain rows only; meta carries the parsed envelope when present */
150
+ domainRowBySeq(seq: number): Promise<LedgerRow | undefined>
151
+ /** Every domain row of one operation, in sequence order (the atomic grouping the gate wrote) */
152
+ eventsOfOperation(operationId: string): Promise<LedgerRow[]>
153
+ /** Sequences of committed compensation events linked to a source operation — the duplicate-compensation guard */
154
+ compensationsOf(sourceOperationId: string): Promise<number[]>
155
+ /** Consistent read snapshot — one point-in-time view for the whole closure (preview composition);
156
+ * joins the read lane so it never observes a half-written operation */
157
+ readSnapshot<T>(fn: () => Promise<T>): Promise<T>
126
158
  }
127
159
 
128
160
  /** Register the physical layer — the assembly layer (or a physical package factory like sqliteStorage) calls it before anything else */
@@ -183,6 +215,8 @@ export interface LedgerReadRow {
183
215
  aggregate_type: string | null
184
216
  aggregate_id: string | null
185
217
  payload: unknown
218
+ /** Event envelope, parsed when the row carries one (engines with the operation-ledger capability) */
219
+ meta?: EventOperationMeta
186
220
  }
187
221
 
188
222
  /** Ledger payloads are kernel-written JSON; a non-JSON payload (hand-edited row) passes through raw rather than failing the read */
@@ -204,5 +238,13 @@ const parsePayload = (raw: string): unknown => {
204
238
  */
205
239
  export async function readLedger(opts: { after?: number; limit?: number; ascending?: boolean } = {}): Promise<LedgerReadRow[]> {
206
240
  const rows = await storageOf().ledgerRows(opts.after ?? 0, opts.limit ?? 50, opts.ascending ?? true)
207
- return rows.map((r) => ({ ...r, payload: maskSecrets(parsePayload(r.payload)) }))
241
+ return rows.map(({ meta: rawMeta, ...rest }) => {
242
+ let meta: EventOperationMeta | undefined
243
+ try {
244
+ meta = rawMeta ? (JSON.parse(rawMeta) as EventOperationMeta) : undefined
245
+ } catch {
246
+ meta = undefined
247
+ }
248
+ return { ...rest, payload: maskSecrets(parsePayload(rest.payload)), ...(meta ? { meta } : {}) }
249
+ })
208
250
  }
package/src/types.ts CHANGED
@@ -82,6 +82,193 @@ export interface CommandDefinition<I = any, O = any> {
82
82
  /** Pure by design: never mutate state directly, only return events. The kernel applies projections.
83
83
  * result is checked against the output contract */
84
84
  execute: (input: I, identity: Identity) => Promise<{ events: DomainEvent[]; result: O }>
85
+ /** Command contract version (semver) — the domain declares it for the whole contract
86
+ * (input·output·refusal·permission·transition semantics). Required in strict mode; the catalog
87
+ * publishes it and strict-mode writes carry it back (ContractMeta) */
88
+ version?: string
89
+ /** Explicit revision for meaning changes no fingerprint can derive (functional refine bodies,
90
+ * business-logic semantics). Bumped by the domain; folded into the command revision */
91
+ behaviorRevision?: string
92
+ }
93
+
94
+ /** Event envelope (operation metadata) — kernel-written, persisted beside the payload by engines that
95
+ * implement the operation-ledger storage capability. Deliberately separate from the business payload:
96
+ * undo linkage and contract provenance are kernel concerns, not domain data. Legacy rows (written
97
+ * before this field existed) carry none — undo answers them through the legacy codes. */
98
+ export interface EventOperationMeta {
99
+ /** One atomic command run — every event of one execution shares it. Batch items are separate operations, grouped by batchId */
100
+ operationId: string
101
+ batchId?: string
102
+ commandName: string
103
+ commandVersion?: string
104
+ commandRevision?: string
105
+ /** Event payload format version (domain-managed via registerEventVersions, independent of the command version) */
106
+ eventVersion?: number
107
+ /** Present on compensation events — which source operation this undo compensates */
108
+ undoOfOperationId?: string
109
+ /** The anchor sequence the undo request selected */
110
+ undoSourceSeq?: number
111
+ undoHandlerVersion?: string
112
+ /** The normalized policy target this execution was authorized against (scope ≠ 'none') — the
113
+ * RIGHTS MATERIAL a later redelivery is judged on, recorded at write time so the verdict never
114
+ * guesses the target from aggregate ids or input field names */
115
+ policyTarget?: string
116
+ }
117
+
118
+ /** The contract identity a strict-mode write carries beside the business input — the caller's view of
119
+ * the command contract. Refused before execution when it no longer matches (gate.contract_changed /
120
+ * gate.contract_required). Riding splitProtocolOptions, it never reaches the business schema. */
121
+ export interface ContractMeta {
122
+ commandVersion: string
123
+ commandRevision: string
124
+ protocolVersion: string
125
+ }
126
+
127
+ /** Origin-read hook — may this identity learn ANYTHING about an operation of this event type
128
+ * (existence, processing state, undo policy metadata)? Runs before every undo answer, whatever the
129
+ * policy kind — supported, unavailable or mixed. Refuse by throwing a GateError (stage 1~3);
130
+ * a refusal answers with no operation facts at all. Independent of mayPreview (the handler's
131
+ * plan-specific gate): reading history and planning a compensation are different questions. */
132
+ export type UndoMayRead = (source: SourceOperation, identity: Identity) => Promise<void>
133
+
134
+ /** Undo policy per event type — supported (a handler plans the compensation) or explicitly unavailable
135
+ * (a stable code + a concrete reason). Both kinds are declared; strict mode requires a policy for every
136
+ * registered event type AND a mayRead hook on every policy — origin-read rights are a declared
137
+ * decision, never a default allow. `roles` limits the policy's CATALOG exposure (absent = every
138
+ * authenticated identity sees the policy entry; it never affects the mayRead verdict).
139
+ * Audit rows are never undo targets. */
140
+ export type EventUndoPolicy =
141
+ | { kind: 'supported'; handlerId: string; mayRead?: UndoMayRead; roles?: readonly Role[] }
142
+ | { kind: 'unavailable'; code: string; reason: string; mayRead?: UndoMayRead; roles?: readonly Role[] }
143
+
144
+ /** One event of a source operation, as the undo planner sees it */
145
+ export interface SourceEvent {
146
+ seq: number
147
+ type: string
148
+ aggregateType: string
149
+ aggregateId: string
150
+ payload: unknown
151
+ eventVersion?: number
152
+ }
153
+
154
+ /** The exact ledger facts of one atomic command run — the unit an undo compensates. Selecting any event
155
+ * row of the operation resolves to the whole operation (partial undo does not exist); sourceSeq is the
156
+ * anchor the caller picked — never "the latest event of the same kind". */
157
+ export interface SourceOperation {
158
+ operationId: string
159
+ sourceSeq: number
160
+ /** Written before operation metadata existed — the grouping is whatever the ledger can still prove */
161
+ legacy: boolean
162
+ commandName?: string
163
+ commandVersion?: string
164
+ commandRevision?: string
165
+ events: SourceEvent[]
166
+ }
167
+
168
+ export interface UndoPlanChange {
169
+ target: string
170
+ field?: string
171
+ before: unknown
172
+ after: unknown
173
+ }
174
+ export interface UndoPlanLoss {
175
+ code: string
176
+ reason: string
177
+ count?: number
178
+ }
179
+ export interface UndoPlanBlocker {
180
+ code: string
181
+ reason: string
182
+ }
183
+
184
+ /** The compensation plan — read-only by contract: the kernel validates the shape, hashes it, re-derives
185
+ * it inside the execution transaction, and publishes only the preview projection. The compensation is
186
+ * exactly one registered command; its events re-enter the gate like any write (no bypass lane). */
187
+ export interface UndoPlan {
188
+ command: string
189
+ input: Record<string, unknown>
190
+ /** Domain dependency-state tokens — recomputed at execution; a difference refuses as undo.plan_changed */
191
+ dependsOn?: Record<string, string>
192
+ changes: UndoPlanChange[]
193
+ preserved?: string[]
194
+ losses?: UndoPlanLoss[]
195
+ blockers?: UndoPlanBlocker[]
196
+ }
197
+
198
+ /** Undo handler — owned by the domain. plan() is read-only (no business writes, no ledger appends, no
199
+ * idempotency storage, no external effects) and runs inside one consistent read snapshot. */
200
+ export interface UndoHandler {
201
+ id: string
202
+ version: string
203
+ plan: (source: SourceOperation, identity: Identity) => Promise<UndoPlan>
204
+ /** Optional per-source read permission (history-reading rights are business interpretation).
205
+ * Absent = any identity that may run the compensation command may preview. Throw GateError to refuse. */
206
+ mayPreview?: (source: SourceOperation, identity: Identity) => Promise<void>
207
+ }
208
+
209
+ /** Preview of one undo, judged for the current user against the current state — static "a handler
210
+ * exists" and "this call can run now" are different questions (status answers the latter). */
211
+ export interface UndoPreview {
212
+ status: 'available' | 'warning' | 'blocked' | 'unavailable' | 'already_undone'
213
+ sourceSeq: number
214
+ operationId?: string
215
+ handlerId?: string
216
+ command?: { name: string; version: string; revision: string }
217
+ changes: UndoPlanChange[]
218
+ preserved: string[]
219
+ losses: UndoPlanLoss[]
220
+ blockers: UndoPlanBlocker[]
221
+ /** Server-keyed digest of the whole plan (source identity, handler·command contract, compensation
222
+ * input, dependency tokens, changes·preserved·losses·blockers) — execution demands the same hash */
223
+ planHash?: string
224
+ }
225
+
226
+ /** Contract metadata on every success response — the CURRENT revisions, distinguished from the result
227
+ * itself: a replayed result was produced by an older contract, and the meta says what is true now. */
228
+ export interface ContractResponseMeta {
229
+ protocolVersion: string
230
+ catalogVersion?: string
231
+ catalogRevision: string
232
+ /** The caller's personal view revision — present on responses built with an identity; it moves when
233
+ * their permissions move (the common protocol documents it on every success response) */
234
+ viewRevision?: string
235
+ commandVersion?: string
236
+ commandRevision?: string
237
+ }
238
+
239
+ /** One entry of a catalog release's change list — what changed relative to the previous release */
240
+ export interface CatalogChangeRecord {
241
+ kind?: 'command' | 'query' | 'errorCodes' | 'transitions' | 'protocol' | 'other'
242
+ name?: string
243
+ fromVersion?: string
244
+ toVersion?: string
245
+ compatibility?: 'breaking' | 'compatible'
246
+ summary?: string
247
+ migration?: string
248
+ replacement?: string | null
249
+ /** Roles allowed to read this record — absent = every authenticated identity */
250
+ roles?: readonly string[]
251
+ }
252
+
253
+ /** The release declaration of the served catalog — registered at boot (registerCatalogRelease).
254
+ * catalogVersion is the app-declared compatibility semver; changes describe what this release altered
255
+ * relative to the previous one (the release-manifest validator checks them against the contract diff). */
256
+ export interface CatalogRelease {
257
+ catalogVersion: string
258
+ releasedAt?: string
259
+ /** Revisions this release can serve a change list FROM — a diff is an optimization; anything else
260
+ * answers fullRefreshRequired (the full catalog is always the source of truth) */
261
+ previousRevisions?: readonly string[]
262
+ changes?: readonly CatalogChangeRecord[]
263
+ }
264
+
265
+ /** Revision index computed once at seal — content fingerprints of the sealed contracts. Content-derived
266
+ * and canonical: the same content yields the same revision no matter the registration order or how many
267
+ * times the process boots; nothing here is a timestamp or a path. */
268
+ export interface CatalogRevisions {
269
+ catalog: string
270
+ commands: Record<string, string>
271
+ queries: Record<string, string>
85
272
  }
86
273
 
87
274
  /** Stage names of the 9-stage gate — a fixed, published contract. GateError derives stageName from the