@sudoke/kernel 0.4.0 → 0.5.1
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 +21 -18
- package/package.json +2 -1
- package/src/gate.ts +31 -23
- package/src/index.ts +2 -2
- package/src/mcp.ts +1 -1
- package/src/operation-meta.ts +29 -0
- package/src/projections.ts +2 -11
- package/src/protocol.ts +1 -1
- package/src/queries.ts +1 -1
- package/src/registry.ts +12 -20
- package/src/state.ts +5 -8
- package/src/storage.ts +1 -1
- package/src/types.ts +0 -8
- package/src/undo.ts +5 -16
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ behind every sudoke app. Surfaces (REST·MCP·UI) and domains (commands, policie
|
|
|
5
5
|
content; this package owns the execution guarantees every write passes through.
|
|
6
6
|
|
|
7
7
|
This README documents the public API, the **undo (restore) contract**, the **command version/revision
|
|
8
|
-
contract**, the
|
|
8
|
+
contract**, the single assembly regime, and the storage-port extension requirements. All kernel
|
|
9
9
|
source (comments, refusal sentences) is English; app packages are the app authors' language.
|
|
10
10
|
|
|
11
11
|
## Assembly
|
|
@@ -17,12 +17,11 @@ import {
|
|
|
17
17
|
registerStorage, registerRoles, registerEventContracts, registerEventVersions,
|
|
18
18
|
registerErrorCodes, registerAppPolicy, registerAppProjector, registerAppProtocol,
|
|
19
19
|
registerCommand, registerQuery, registerTransitionMachine,
|
|
20
|
-
|
|
20
|
+
registerUndoPolicies, registerUndoHandler, registerCatalogRelease,
|
|
21
21
|
catalogConsistencyErrors, sealRegistries,
|
|
22
22
|
} from '@sudoke/kernel'
|
|
23
23
|
|
|
24
24
|
registerStorage(engine) // physical layer first (e.g. sqliteStorage)
|
|
25
|
-
configureKernel({ mode: 'compat' }) // or 'strict' — see below
|
|
26
25
|
registerRoles([...]) // the app's role vocabulary
|
|
27
26
|
registerEventContracts({...}) // payload contracts — writes check against them
|
|
28
27
|
registerUndoPolicies({...}) // per event type: supported(handlerId) | unavailable(code, reason)
|
|
@@ -36,19 +35,19 @@ sealRegistries()
|
|
|
36
35
|
The seal is automatic at the first execution (`completeAssembly`) — there is no path that seals without
|
|
37
36
|
the consistency check.
|
|
38
37
|
|
|
39
|
-
##
|
|
38
|
+
## The contract regime (one mode)
|
|
40
39
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
50
|
|
|
51
|
-
`configureKernel` is sealed with the registries; changing the mode at runtime is a defect.
|
|
52
51
|
|
|
53
52
|
## Command versions, revisions and the single manifest
|
|
54
53
|
|
|
@@ -85,7 +84,7 @@ APIs (transport-independent; surfaces own paths and polling):
|
|
|
85
84
|
whose contracts changed without a change record, or whose structurally identifiable breaks lack a
|
|
86
85
|
MAJOR bump; semantic compatibility stays the release author's explicit classification.
|
|
87
86
|
|
|
88
|
-
###
|
|
87
|
+
### Writes carry a contract
|
|
89
88
|
|
|
90
89
|
```
|
|
91
90
|
{ ...businessInput, contract: { commandVersion, commandRevision, protocolVersion } }
|
|
@@ -147,7 +146,7 @@ Contract highlights:
|
|
|
147
146
|
- **Origin-read rights live on the POLICY** (`mayRead` on every `registerUndoPolicies` entry) — REQUIRED
|
|
148
147
|
in strict mode: it runs before ANY branch (supported·unavailable·mixed·legacy·already-undone) answers
|
|
149
148
|
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` (
|
|
149
|
+
policy reason). Supported handlers refine further with `mayPreview` (equally required). An
|
|
151
150
|
optional `roles` on the policy scopes its CATALOG exposure; exposure and the read verdict are
|
|
152
151
|
independent decisions.
|
|
153
152
|
- **The preview judges the compensation through the SAME static+dynamic checks a direct call would
|
|
@@ -183,7 +182,7 @@ Kernel-common error codes involved: `gate.contract_required`, `gate.contract_cha
|
|
|
183
182
|
## Storage port extension (engine authors)
|
|
184
183
|
|
|
185
184
|
`StoragePort` gains the OPTIONAL `operationLedger` capability (the `close?()` precedent). Engines
|
|
186
|
-
without it
|
|
185
|
+
without it cannot boot (the kernel requires the capability — undo is part of the contract)
|
|
187
186
|
to boot). Implementing it requires:
|
|
188
187
|
|
|
189
188
|
- persisting the kernel-written envelope (`EventOperationMeta`) beside the payload — a nullable JSON
|
|
@@ -202,7 +201,7 @@ kernel's own tests ship a reference implementation (`test/sqlite-operation-stora
|
|
|
202
201
|
|
|
203
202
|
Guaranteed: 9-stage gating with first-class refusals, append-only ledger, idempotent retries, replay
|
|
204
203
|
determinism, audit completeness, contract-passed writes, catalog consistency at boot, undo atomicity·
|
|
205
|
-
single-compensation, deterministic content revisions,
|
|
204
|
+
single-compensation, deterministic content revisions, contract refusal before execution.
|
|
206
205
|
|
|
207
206
|
Not guaranteed: cross-process catalog-change push (each process seals its own view — reconnect and
|
|
208
207
|
compare `catalogStatus`; `tools/list_changed` and server push are NOT prerequisites), automatic
|
|
@@ -219,3 +218,7 @@ npm run validate:releases <previous.json|null> <current.json> # release manife
|
|
|
219
218
|
|
|
220
219
|
`validate:releases` is a REPOSITORY check command — `scripts/` is deliberately outside the published
|
|
221
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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sudoke/kernel",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
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": [
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/node": "^22.10.2",
|
|
30
|
+
"tsx": "^4.19.2",
|
|
30
31
|
"typescript": "^5.7.2"
|
|
31
32
|
}
|
|
32
33
|
}
|
package/src/gate.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { ZodError } from 'zod'
|
|
|
15
15
|
import { randomUUID } from 'node:crypto'
|
|
16
16
|
import { storageOf } from './storage.js'
|
|
17
17
|
import { appPolicy } from './policy.js'
|
|
18
|
-
import { completeAssembly,
|
|
18
|
+
import { completeAssembly, lookupCommand, transitionRulesOf } from './registry.js'
|
|
19
19
|
import { commandRevisionOf, PROTOCOL_VERSION, responseMetaOf } from './catalog.js'
|
|
20
20
|
import { roleAllowsCommand } from './visibility.js'
|
|
21
21
|
import { GateError, type CommandDefinition, type ContractMeta, type Identity } from './types.js'
|
|
@@ -212,7 +212,7 @@ export async function validateDynamic(def: CommandDefinition<any>, input: any, i
|
|
|
212
212
|
}
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
-
/** Permission precheck without schema parsing — the
|
|
215
|
+
/** Permission precheck without schema parsing — the replay-first path uses it where the resent
|
|
216
216
|
* input may no longer parse under the current schema. Role needs no input; delegation target extraction
|
|
217
217
|
* reads the raw body (a plain field read in practice). The app-policy scope check (parsed-input
|
|
218
218
|
* dependent) is not repeated for a redelivery — there is no new effect to authorize. */
|
|
@@ -230,7 +230,7 @@ export async function quickPermissionCheck(def: CommandDefinition<any>, name: st
|
|
|
230
230
|
)
|
|
231
231
|
}
|
|
232
232
|
|
|
233
|
-
/**
|
|
233
|
+
/** The contract check — the write is refused before execution when the caller's contract view is
|
|
234
234
|
* stale. The revision match is exact: within one MAJOR, description·warning·behavior changes must be
|
|
235
235
|
* re-confirmed too. Only THIS command's revision matters — other commands changing never refuses here
|
|
236
236
|
* (their revisions did not move). */
|
|
@@ -239,7 +239,7 @@ export function checkContract(def: CommandDefinition<any>, contract: ContractMet
|
|
|
239
239
|
throw new GateError(
|
|
240
240
|
4,
|
|
241
241
|
'schema',
|
|
242
|
-
'This kernel
|
|
242
|
+
'This kernel requires the command contract — send contract:{commandVersion,commandRevision,protocolVersion} beside the business input (read them from the catalog)',
|
|
243
243
|
{ code: 'gate.contract_required' },
|
|
244
244
|
)
|
|
245
245
|
const diffs: string[] = []
|
|
@@ -256,7 +256,7 @@ export function checkContract(def: CommandDefinition<any>, contract: ContractMet
|
|
|
256
256
|
)
|
|
257
257
|
}
|
|
258
258
|
|
|
259
|
-
/** Re-proves each item's recorded rights for a stored batch result — the
|
|
259
|
+
/** Re-proves each item's recorded rights for a stored batch result — the replay probe and the
|
|
260
260
|
* concurrent-retry settlement share this (a batch redelivery is a fresh READ of every item). Returns
|
|
261
261
|
* the refusal response, or null when the whole batch is still provable. */
|
|
262
262
|
async function batchRightsRefusal(items: { name: string }[], identity: Identity, producedBy: unknown): Promise<ExecutionResult | null> {
|
|
@@ -345,7 +345,7 @@ async function assertReplayRights(name: string, identity: Identity, producedBy:
|
|
|
345
345
|
await verifyReplayRights(name, current, producedBy)
|
|
346
346
|
}
|
|
347
347
|
|
|
348
|
-
/** Replay probe for a command the registry no longer knows
|
|
348
|
+
/** Replay probe for a command the registry no longer knows — a resend for a removed command:
|
|
349
349
|
* when the stored provenance (same subject, same requestKey, same hashed request) says this caller
|
|
350
350
|
* already succeeded, the stored result MAY be returned. The account must be valid NOW, and the
|
|
351
351
|
* rights must still be provable (verifyReplayRights). Null when nothing is stored for this
|
|
@@ -362,14 +362,14 @@ export async function replayStoredCommand(identity: Identity, name: string, rawI
|
|
|
362
362
|
}
|
|
363
363
|
|
|
364
364
|
async function executeCommandInner(name: string, rawInput: unknown, identity: Identity): Promise<ExecutionResult> {
|
|
365
|
-
const strict = kernelOptions().mode === 'strict'
|
|
366
365
|
const def = lookupCommand(name)
|
|
367
366
|
if (!def) {
|
|
368
|
-
|
|
367
|
+
{
|
|
369
368
|
try {
|
|
370
369
|
const replayed = await replayStoredCommand(identity, name, rawInput)
|
|
371
370
|
if (replayed) {
|
|
372
|
-
await
|
|
371
|
+
if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
|
|
372
|
+
await tryRecordOutsideTx('replay', name, identity, rawInput)
|
|
373
373
|
return replayed.ok ? { ...replayed, meta: responseMetaOf(undefined, identity) } : replayed
|
|
374
374
|
}
|
|
375
375
|
} catch (err) {
|
|
@@ -382,7 +382,7 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
|
|
|
382
382
|
const { requestKey, dryRun, contract, contractMalformed, body } = splitProtocolOptions(rawInput)
|
|
383
383
|
const hashValue = hashBodyOf(body, contract)
|
|
384
384
|
try {
|
|
385
|
-
//
|
|
385
|
+
// the replay probe precedes the schema·contract checks: a stored success is returned even
|
|
386
386
|
// when today's schema or contract would refuse the resent input (the result already exists;
|
|
387
387
|
// re-validating it against today's contract adds false negatives, never safety). The stored row is
|
|
388
388
|
// found FIRST — judging the resent raw input through TODAY'S targetOf would refuse legitimate
|
|
@@ -390,7 +390,7 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
|
|
|
390
390
|
// re-extraction from the past input). A HIT is a fresh READ: the recorded rights are re-proven
|
|
391
391
|
// (role·delegation·policy target·current scopes), so a redelivery never widens permissions. A MISS
|
|
392
392
|
// is a NEW request — the current definition judges everything from here.
|
|
393
|
-
if (
|
|
393
|
+
if (requestKey && !dryRun && contract) {
|
|
394
394
|
const replayed = await replayOrReject(identity, name, requestKey, hashValue)
|
|
395
395
|
if (replayed) {
|
|
396
396
|
if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
|
|
@@ -400,10 +400,10 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
|
|
|
400
400
|
await quickPermissionCheck(def, name, body, identity)
|
|
401
401
|
}
|
|
402
402
|
|
|
403
|
-
//
|
|
403
|
+
// the contract the call was built against must be declared and current BEFORE the business
|
|
404
404
|
// schema judges the input: a caller working from a stale contract is told to re-learn the contract,
|
|
405
405
|
// not lectured on schema details of fields they have never seen
|
|
406
|
-
|
|
406
|
+
checkContract(def, contract, contractMalformed)
|
|
407
407
|
|
|
408
408
|
const input = await validateStatic(def, name, body, identity)
|
|
409
409
|
|
|
@@ -412,6 +412,10 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
|
|
|
412
412
|
if (requestKey && !dryRun) {
|
|
413
413
|
const replayed = await replayOrReject(identity, name, requestKey, hashValue)
|
|
414
414
|
if (replayed) {
|
|
415
|
+
// the FIRST probe missed and a concurrent request may have stored this key while the static
|
|
416
|
+
// checks were awaiting — a hit HERE is still a redelivery: the current rights are re-proved
|
|
417
|
+
// exactly as on the first probe (review F1)
|
|
418
|
+
if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
|
|
415
419
|
await tryRecordOutsideTx('replay', name, identity, rawInput)
|
|
416
420
|
return replayed.ok ? { ...replayed, meta: responseMetaOf(name, identity) } : replayed
|
|
417
421
|
}
|
|
@@ -452,8 +456,8 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
|
|
|
452
456
|
if (requestKey) {
|
|
453
457
|
const settled = await settleConcurrentRetry(identity, name, requestKey, hashValue)
|
|
454
458
|
if (settled) {
|
|
455
|
-
// a settled success is a redelivery too —
|
|
456
|
-
if (settled.ok
|
|
459
|
+
// a settled success is a redelivery too — the recorded rights are re-proved
|
|
460
|
+
if (settled.ok) await assertReplayRights(name, identity, (settled as { producedBy?: unknown }).producedBy)
|
|
457
461
|
await auditSettled(name, identity, rawInput, settled)
|
|
458
462
|
return settled.ok ? { ...settled, meta: responseMetaOf(name, identity) } : settled
|
|
459
463
|
}
|
|
@@ -508,15 +512,13 @@ async function executeBatchInner(
|
|
|
508
512
|
if (!Array.isArray(items) || items.length === 0 || items.length > 20)
|
|
509
513
|
return await refuse('batch', identity, items, new GateError(4, 'schema', 'commands must be an array of 1 to 20 items', { code: 'gate.schema_invalid' }))
|
|
510
514
|
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
// strict — the batch replay probe precedes the per-item checks, on the same principle as the single
|
|
515
|
+
// the batch replay probe precedes the per-item checks, on the same principle as the single
|
|
514
516
|
// command: a stored batch success is returned even when today's item schemas/contracts would refuse.
|
|
515
517
|
// The stored row is found FIRST (today's targetOf never re-extracts targets from resent raw items —
|
|
516
518
|
// the recorded per-item material is the verdict); a HIT re-proves every item's recorded rights,
|
|
517
519
|
// including items whose command has since been removed. A MISS falls through to the current
|
|
518
520
|
// definitions' full checks below.
|
|
519
|
-
if (
|
|
521
|
+
if (batchRequestKey) {
|
|
520
522
|
let replayed: ExecutionResult | null = null
|
|
521
523
|
try {
|
|
522
524
|
replayed = await replayOrReject(identity, 'batch', batchRequestKey, items)
|
|
@@ -557,7 +559,7 @@ async function executeBatchInner(
|
|
|
557
559
|
prefix: `#${i} ${it.name}: `,
|
|
558
560
|
})
|
|
559
561
|
// Protocol options are batch-level, not item-level — an item carrying one is a clear refusal, never
|
|
560
|
-
// silent execution. (contract is the exception:
|
|
562
|
+
// silent execution. (contract is the exception: every item CARRIES a contract — it is
|
|
561
563
|
// checked per item below; the batch requestKey hash covers the items as sent, contract included.)
|
|
562
564
|
const { requestKey: itemKey, dryRun: itemDry, contract: itemContract, contractMalformed: itemMalformed, body: itemBody } = splitProtocolOptions(it.input ?? {})
|
|
563
565
|
if (itemKey || itemDry)
|
|
@@ -577,7 +579,7 @@ async function executeBatchInner(
|
|
|
577
579
|
// the caller's contract view is judged before the business schema — the same order as single
|
|
578
580
|
// commands (a stale-contract caller is told to re-learn the contract, not lectured on fields
|
|
579
581
|
// they have never seen)
|
|
580
|
-
|
|
582
|
+
checkContract(def, itemContract, itemMalformed)
|
|
581
583
|
const input = await validateStatic(def, it.name, itemBody, identity)
|
|
582
584
|
validated.push({ def, name: it.name, input, rawInput: it.input })
|
|
583
585
|
} catch (err) {
|
|
@@ -593,6 +595,12 @@ async function executeBatchInner(
|
|
|
593
595
|
return await refuse('batch', identity, items, toGateError(err, 6, 'invariant'))
|
|
594
596
|
}
|
|
595
597
|
if (replayed) {
|
|
598
|
+
// concurrent batch stored this key while the per-item validation was awaiting — the hit is a
|
|
599
|
+
// redelivery and every item's recorded rights are re-proved, exactly as on the first probe
|
|
600
|
+
if (replayed.ok) {
|
|
601
|
+
const refused = await batchRightsRefusal(items, identity, (replayed as { producedBy?: unknown }).producedBy)
|
|
602
|
+
if (refused) return refused
|
|
603
|
+
}
|
|
596
604
|
await tryRecordOutsideTx('replay', 'batch', identity, items)
|
|
597
605
|
return replayed.ok
|
|
598
606
|
? { ...replayed, meta: responseMetaOf(undefined, identity), results: (replayed.result as any)?.results }
|
|
@@ -639,8 +647,8 @@ async function executeBatchInner(
|
|
|
639
647
|
if (batchRequestKey) {
|
|
640
648
|
const settled = await settleConcurrentRetry(identity, 'batch', batchRequestKey, items)
|
|
641
649
|
if (settled) {
|
|
642
|
-
// a settled success is a redelivery too —
|
|
643
|
-
if (settled.ok
|
|
650
|
+
// a settled success is a redelivery too — every item's recorded rights are re-proved
|
|
651
|
+
if (settled.ok) {
|
|
644
652
|
const refused = await batchRightsRefusal(items, identity, (settled as { producedBy?: unknown }).producedBy)
|
|
645
653
|
if (refused) return refused
|
|
646
654
|
}
|
package/src/index.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* per process; tests reset it in place with resetKernelForTests. */
|
|
6
6
|
export { GateError, STAGE_NAMES } from './types.js'
|
|
7
7
|
export type { CommandDefinition, DomainEvent, ErrorCodeDefinition, Identity, RecoveryAction, RecoveryHint, Role } from './types.js'
|
|
8
|
-
export type { EventOperationMeta, ContractMeta, ContractResponseMeta, EventUndoPolicy, SourceEvent, SourceOperation, UndoPlan, UndoPlanChange, UndoPlanLoss, UndoPlanBlocker, UndoHandler, UndoPreview,
|
|
8
|
+
export type { EventOperationMeta, ContractMeta, ContractResponseMeta, EventUndoPolicy, SourceEvent, SourceOperation, UndoPlan, UndoPlanChange, UndoPlanLoss, UndoPlanBlocker, UndoHandler, UndoPreview, CatalogChangeRecord, CatalogRelease, CatalogRevisions } from './types.js'
|
|
9
9
|
export { hashPassword, verifyPassword, issueUserToken, issueDelegationToken, login, unauthenticated, loadIdentity, currentIdentityOf, identityFromToken, ensureUser } from './auth.js'
|
|
10
10
|
export { executeCommand, executeBatch } from './gate.js'
|
|
11
11
|
export type { ExecutionRefusal, ExecutionResult, ExecutionSuccess } from './gate.js'
|
|
@@ -19,7 +19,7 @@ export { registerAppProtocol, protocolPreamble, PROTOCOL_BATCH, PROTOCOL_DELEGAT
|
|
|
19
19
|
export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape, queryAccessOf } from './queries.js'
|
|
20
20
|
export type { QueryDefinition, QueryOutcome, QueryRefusal } from './queries.js'
|
|
21
21
|
export { registerRoles, registerCommand, lookupCommand, allCommands, inputShapeOf, catalogMeta, registerTransitionMachine, transitionRulesOf, allTransitionMachines, registerEventContracts, eventContractOf, allEventContractTypes, registerErrorCodes, errorCodeOf, allErrorCodes, catalogConsistencyErrors, completeAssembly, sealRegistries } from './registry.js'
|
|
22
|
-
export { registerUndoHandler, registerUndoPolicies, undoPolicyOf, undoHandlerOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions,
|
|
22
|
+
export { registerUndoHandler, registerUndoPolicies, undoPolicyOf, undoHandlerOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions, registerCatalogRelease } from './registry.js'
|
|
23
23
|
export type { TransitionRule } from './registry.js'
|
|
24
24
|
export { buildCatalogDocument, catalogStatus, catalogChanges, catalogRevisionOf, commandRevisionOf, queryRevisionOf, viewRevisionOf, commandContractShape, queryContractShape, computeCatalogRevisions, responseMetaOf, PROTOCOL_VERSION } from './catalog.js'
|
|
25
25
|
export { validateReleaseManifest, structuralBreakingChanges } from './releases.js'
|
package/src/mcp.ts
CHANGED
|
@@ -95,7 +95,7 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
|
|
|
95
95
|
protocolVersion: z.string(),
|
|
96
96
|
})
|
|
97
97
|
.optional()
|
|
98
|
-
.describe('
|
|
98
|
+
.describe('the command contract this call was built against (commandVersion·commandRevision from the catalog, protocolVersion from catalog status) — required on every write'),
|
|
99
99
|
}),
|
|
100
100
|
},
|
|
101
101
|
async (args: Record<string, unknown>) => {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single reader of a ledger row's operation envelope — the undo planner, the redelivery
|
|
3
|
+
* rights checks and the rebuilding projection all parse `row.meta` through here, so the
|
|
4
|
+
* envelope-vs-row precedence can never drift between two readers.
|
|
5
|
+
*
|
|
6
|
+
* eventVersion precedence (the kernel contract): the envelope's value wins; the row's own version
|
|
7
|
+
* column is the fallback. Rows carrying neither are legacy and answer undefined — callers resolve
|
|
8
|
+
* that as format version 1.
|
|
9
|
+
*/
|
|
10
|
+
import type { EventOperationMeta } from './types.js'
|
|
11
|
+
import type { LedgerRow } from './storage.js'
|
|
12
|
+
|
|
13
|
+
/** The operation envelope a row carries — undefined when absent or non-JSON (a hand-edited row);
|
|
14
|
+
* the read never fails. */
|
|
15
|
+
export type OperationMeta = Partial<EventOperationMeta>
|
|
16
|
+
|
|
17
|
+
export function operationMetaOf(row: LedgerRow): OperationMeta | undefined {
|
|
18
|
+
if (!row.meta) return undefined
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(row.meta) as OperationMeta
|
|
21
|
+
} catch {
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The event format version a stored row carries — envelope first, then the row's version column. */
|
|
27
|
+
export function ledgerEventVersionOf(row: LedgerRow): number | undefined {
|
|
28
|
+
return operationMetaOf(row)?.eventVersion ?? row.version
|
|
29
|
+
}
|
package/src/projections.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ledgerEventVersionOf } from './operation-meta.js'
|
|
1
2
|
import { storageOf } from './storage.js'
|
|
2
3
|
import { assertOpenFor, defaultKernelState, type RegisteredProjector } from './state.js'
|
|
3
4
|
import type { DomainEvent } from './types.js'
|
|
@@ -102,17 +103,7 @@ export async function rebuildProjections(): Promise<void> {
|
|
|
102
103
|
proj.initTables,
|
|
103
104
|
async () => {
|
|
104
105
|
for (const r of await storageOf().domainRows()) {
|
|
105
|
-
|
|
106
|
-
// version column; rows carrying neither are version 1 by definition
|
|
107
|
-
let eventVersion: number | undefined = r.version
|
|
108
|
-
if (r.meta) {
|
|
109
|
-
try {
|
|
110
|
-
const parsed = JSON.parse(r.meta) as { eventVersion?: number }
|
|
111
|
-
if (parsed.eventVersion !== undefined) eventVersion = parsed.eventVersion
|
|
112
|
-
} catch {
|
|
113
|
-
// a non-JSON envelope on a hand-edited row falls back to the version column — the read never fails
|
|
114
|
-
}
|
|
115
|
-
}
|
|
106
|
+
const eventVersion = ledgerEventVersionOf(r)
|
|
116
107
|
await applyDomainEvent(
|
|
117
108
|
{
|
|
118
109
|
type: r.type,
|
package/src/protocol.ts
CHANGED
|
@@ -20,7 +20,7 @@ const baseProtocol: readonly string[] = [
|
|
|
20
20
|
'Transition tables for stateful collections are in catalog.transitions — check which commands are legal from the current status (from) before executing.',
|
|
21
21
|
'Success responses carry meta — the CURRENT contract revisions (protocolVersion·catalogRevision·viewRevision, and commandVersion·commandRevision for the command). A revision is a content fingerprint: it changes only when contract content changes. viewRevision is your personal view — it also moves when your permissions change. A replayed result keeps its old payload while meta states what is true now.',
|
|
22
22
|
'Discover changes by comparing revisions, then reading the change list — a diff is an optimization; the full catalog is always the source of truth, and an unknown revision means refresh in full.',
|
|
23
|
-
'
|
|
23
|
+
'Every write carries contract:{commandVersion,commandRevision,protocolVersion} beside the business input (from the catalog). A missing contract is refused (gate.contract_required); an outdated one is refused before execution (gate.contract_changed). After gate.contract_changed: read the status, read what changed, re-learn the fields — resending with the revision bumped but nothing re-read is not safe. Only the called command\'s revision matters: other commands changing never refuses yours.',
|
|
24
24
|
'Undo (restore) is forward compensation — a new write, never a rewrite. Preview first (undo preview), confirm reported losses with acceptLosses and the whole plan with expectedPlanHash (the plan hash), then execute. Execution re-derives the plan under the write lock and refuses with undo.plan_changed when anything moved — preview again. Hard conflicts are never forceable; to go back again, undo the compensation itself.',
|
|
25
25
|
]
|
|
26
26
|
|
package/src/queries.ts
CHANGED
|
@@ -29,7 +29,7 @@ export interface QueryDefinition {
|
|
|
29
29
|
output: z.ZodTypeAny
|
|
30
30
|
handler: (params: Record<string, string>, identity?: Identity) => Promise<unknown>
|
|
31
31
|
/** Query contract version (semver) — the read contract versions too, so surfaces detect read drift.
|
|
32
|
-
* Required
|
|
32
|
+
* Required (semver-checked at seal) */
|
|
33
33
|
version?: string
|
|
34
34
|
/** Explicit revision for meaning changes no fingerprint can derive — bumped by the domain */
|
|
35
35
|
behaviorRevision?: string
|
package/src/registry.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GateError, type CommandDefinition, type ErrorCodeDefinition, type EventUndoPolicy, type UndoHandler, type
|
|
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'
|
|
@@ -211,14 +211,6 @@ export const allEventVersions = (): Record<string, number> => Object.fromEntries
|
|
|
211
211
|
/** Kernel assembly options — compat (default) keeps the historical contract; strict additionally
|
|
212
212
|
* demands undo coverage, declared versions, the operation-ledger capability and per-write contracts.
|
|
213
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
214
|
/** Registers the served catalog release declaration — the app-declared compatibility version plus the
|
|
223
215
|
* change list of this release (what catalogChanges serves and the release validator checks). */
|
|
224
216
|
export function registerCatalogRelease(release: CatalogRelease): void {
|
|
@@ -296,38 +288,38 @@ export function catalogConsistencyErrors(): string[] {
|
|
|
296
288
|
errors.push(`Undo handler is referenced by no policy: ${id} — a dead registration is a defect`)
|
|
297
289
|
for (const type of s.eventVersions.keys())
|
|
298
290
|
if (!s.eventContracts.has(type)) errors.push(`Event version references an unregistered event type: ${type}`)
|
|
299
|
-
//
|
|
300
|
-
//
|
|
301
|
-
|
|
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
|
+
{
|
|
302
294
|
const missingPolicies = [...s.eventContracts.keys()].filter((t) => !s.undoPolicies.has(t))
|
|
303
295
|
if (missingPolicies.length > 0)
|
|
304
|
-
errors.push(`
|
|
296
|
+
errors.push(`an undo policy is required for every registered event type — missing: [${missingPolicies.join(', ')}]`)
|
|
305
297
|
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(`
|
|
298
|
+
if (badVersions.length > 0) errors.push(`valid semver command versions are required: [${badVersions.join(', ')}]`)
|
|
307
299
|
const versionless = [...s.commands.values()].filter((d) => d.version === undefined).map((d) => d.name)
|
|
308
300
|
if (versionless.length > 0)
|
|
309
|
-
errors.push(`
|
|
301
|
+
errors.push(`a declared version is required on every command — missing: [${versionless.join(', ')}]`)
|
|
310
302
|
const versionlessQueries = [...s.queries.values()].filter((q) => q.version === undefined).map((q) => q.name)
|
|
311
303
|
if (versionlessQueries.length > 0)
|
|
312
|
-
errors.push(`
|
|
304
|
+
errors.push(`a declared version is required on every query — missing: [${versionlessQueries.join(', ')}]`)
|
|
313
305
|
const badQueryVersions = [...s.queries.values()].filter((q) => q.version !== undefined && !SEMVER_RE.test(q.version)).map((q) => q.name)
|
|
314
306
|
if (badQueryVersions.length > 0)
|
|
315
|
-
errors.push(`
|
|
307
|
+
errors.push(`valid semver query versions are required: [${badQueryVersions.join(', ')}]`)
|
|
316
308
|
// (the release catalogVersion is semver-checked at registration time, in every mode — no strict duplicate here)
|
|
317
309
|
const hookless = [...s.undoHandlers.values()].filter((h) => typeof h.mayPreview !== 'function').map((h) => h.id)
|
|
318
310
|
if (hookless.length > 0)
|
|
319
311
|
errors.push(
|
|
320
|
-
`
|
|
312
|
+
`a mayPreview hook is required on every undo handler — history-read rights are a declared decision, never a default allow — missing: [${hookless.join(', ')}]`,
|
|
321
313
|
)
|
|
322
314
|
// the OPERATION-level read gate is a declared decision too — unavailable and mixed branches answer
|
|
323
315
|
// operation facts, so every policy (not only supported handlers) must state who may read them
|
|
324
316
|
const readless = [...s.undoPolicies.entries()].filter(([, p]) => typeof p.mayRead !== 'function').map(([t]) => t)
|
|
325
317
|
if (readless.length > 0)
|
|
326
318
|
errors.push(
|
|
327
|
-
`
|
|
319
|
+
`a mayRead hook is required on every undo policy — origin-read rights are a declared decision, never a default allow — missing: [${readless.join(', ')}]`,
|
|
328
320
|
)
|
|
329
321
|
if (!s.storage?.operationLedger)
|
|
330
|
-
errors.push('
|
|
322
|
+
errors.push('the registered storage engine does not provide the operation-ledger capability — the kernel requires it')
|
|
331
323
|
}
|
|
332
324
|
return errors
|
|
333
325
|
}
|
package/src/state.ts
CHANGED
|
@@ -23,7 +23,7 @@ import type { ProjectionHandler } from './projections.js'
|
|
|
23
23
|
import type { QueryDefinition } from './queries.js'
|
|
24
24
|
import type { TransitionRule } from './registry.js'
|
|
25
25
|
import type { StoragePort } from './storage.js'
|
|
26
|
-
import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy,
|
|
26
|
+
import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy, CatalogRelease, CatalogRevisions, UndoHandler } from './types.js'
|
|
27
27
|
|
|
28
28
|
/** Registered projector — the app contract (AppProjector) collected into handler maps */
|
|
29
29
|
export interface RegisteredProjector {
|
|
@@ -44,14 +44,12 @@ export interface KernelState {
|
|
|
44
44
|
queries: Map<string, QueryDefinition>
|
|
45
45
|
storage: StoragePort | null
|
|
46
46
|
sealed: boolean
|
|
47
|
-
/** Undo policy per event type (registerUndoPolicies) —
|
|
47
|
+
/** Undo policy per event type (registerUndoPolicies) — the kernel requires full coverage */
|
|
48
48
|
undoPolicies: Map<string, EventUndoPolicy>
|
|
49
49
|
/** Undo handlers by id (registerUndoHandler) — domain-owned compensation planners */
|
|
50
50
|
undoHandlers: Map<string, UndoHandler>
|
|
51
51
|
/** Event payload format versions per type (registerEventVersions) — absent = 1 */
|
|
52
52
|
eventVersions: Map<string, number>
|
|
53
|
-
/** Assembly options (configureKernel) — sealed with the registries; null = compat */
|
|
54
|
-
options: KernelOptions | null
|
|
55
53
|
/** The served catalog release declaration (registerCatalogRelease) — null when the app declares none */
|
|
56
54
|
catalogRelease: CatalogRelease | null
|
|
57
55
|
/** Content fingerprints computed once at seal (completeAssembly fills this) */
|
|
@@ -83,8 +81,8 @@ const KERNEL_COMMON_ERROR_CODES: Record<string, ErrorCodeDefinition> = {
|
|
|
83
81
|
'query.role_denied': { description: 'Query role not allowed (stage 3 policy)', recovery: 'stop' },
|
|
84
82
|
'query.params_invalid': { description: 'Query params violate the query contract', recovery: 'fix_input' },
|
|
85
83
|
'query.execution_failed': { description: 'Query handler error (often transient — safe to retry)', recovery: 'retry' },
|
|
86
|
-
// Contract-versioning refusals
|
|
87
|
-
'gate.contract_required': { description: 'Write without a contract —
|
|
84
|
+
// Contract-versioning refusals — no canForce: a stale contract is never a warning to override
|
|
85
|
+
'gate.contract_required': { description: 'Write without a contract — every write carries contract:{commandVersion,commandRevision,protocolVersion} beside the business input', recovery: 'fix_input' },
|
|
88
86
|
'gate.contract_changed': { description: 'Write sent with an outdated command contract — read the catalog status and changes, re-learn the fields, then resend with the current contract', recovery: 'refresh' },
|
|
89
87
|
// Undo (restore) refusals — none are forceable: hard conflicts and plan movement are never warnings
|
|
90
88
|
'undo.source_not_found': { description: 'No domain event at that sequence (or the row is an audit record — audit rows are never undo targets)', recovery: 'stop' },
|
|
@@ -137,8 +135,7 @@ export function freshKernelState(): KernelState {
|
|
|
137
135
|
undoPolicies: new Map(),
|
|
138
136
|
undoHandlers: new Map(),
|
|
139
137
|
eventVersions: new Map(),
|
|
140
|
-
|
|
141
|
-
catalogRelease: null,
|
|
138
|
+
catalogRelease: null,
|
|
142
139
|
revisions: null,
|
|
143
140
|
}
|
|
144
141
|
}
|
package/src/storage.ts
CHANGED
|
@@ -131,7 +131,7 @@ export interface StoragePort {
|
|
|
131
131
|
/** Operation-ledger extension (optional capability — the close?() precedent). Engines that implement
|
|
132
132
|
* it persist the kernel's event envelope (EventOperationMeta) beside the payload and serve the exact
|
|
133
133
|
* lookups the undo contract needs. Engines without it keep working unchanged: the kernel runs in
|
|
134
|
-
*
|
|
134
|
+
* an assembly without it refuses to boot — the undo APIs answer undo.storage_capability_missing only
|
|
135
135
|
* to boot without it. Write methods here join the same serialized write lane as every other writer.
|
|
136
136
|
*
|
|
137
137
|
* Implementation requirements for engine authors (SQLite shape; other engines equivalently):
|
package/src/types.ts
CHANGED
|
@@ -236,14 +236,6 @@ export interface ContractResponseMeta {
|
|
|
236
236
|
commandRevision?: string
|
|
237
237
|
}
|
|
238
238
|
|
|
239
|
-
/** Kernel assembly options — 'compat' (the default) keeps the historical registration·execution
|
|
240
|
-
* contract untouched; 'strict' additionally requires undo policies for every event type, declared
|
|
241
|
-
* command/query versions, the operation-ledger storage capability, and a contract on every write.
|
|
242
|
-
* Sealed with the registries — runtime changes are a defect. */
|
|
243
|
-
export interface KernelOptions {
|
|
244
|
-
mode: 'compat' | 'strict'
|
|
245
|
-
}
|
|
246
|
-
|
|
247
239
|
/** One entry of a catalog release's change list — what changed relative to the previous release */
|
|
248
240
|
export interface CatalogChangeRecord {
|
|
249
241
|
kind?: 'command' | 'query' | 'errorCodes' | 'transitions' | 'protocol' | 'other'
|
package/src/undo.ts
CHANGED
|
@@ -32,6 +32,7 @@ import { appPolicy } from './policy.js'
|
|
|
32
32
|
import { completeAssembly, lookupCommand, undoHandlerOf, undoPolicyOf } from './registry.js'
|
|
33
33
|
import { commandRevisionOf, responseMetaOf } from './catalog.js'
|
|
34
34
|
import { canonicalJson } from './canonical.js'
|
|
35
|
+
import { ledgerEventVersionOf, operationMetaOf } from './operation-meta.js'
|
|
35
36
|
import {
|
|
36
37
|
assertLiveRoleAllows,
|
|
37
38
|
assertRecordedDelegationCovers,
|
|
@@ -65,21 +66,12 @@ function capability(): OperationLedgerCapability {
|
|
|
65
66
|
return cap
|
|
66
67
|
}
|
|
67
68
|
|
|
68
|
-
const parseMeta = (row: LedgerRow): { operationId?: string; commandName?: string; commandVersion?: string; commandRevision?: string; eventVersion?: number; policyTarget?: string } | undefined => {
|
|
69
|
-
if (!row.meta) return undefined
|
|
70
|
-
try {
|
|
71
|
-
return JSON.parse(row.meta)
|
|
72
|
-
} catch {
|
|
73
|
-
return undefined
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
69
|
/** Resolves the exact source operation behind a sequence — the whole operation, never a substitute row */
|
|
78
70
|
async function resolveSource(cap: OperationLedgerCapability, sourceSeq: number): Promise<{ source: SourceOperation; operationId: string }> {
|
|
79
71
|
const row = await cap.domainRowBySeq(sourceSeq)
|
|
80
72
|
if (!row || row.kind !== 'domain')
|
|
81
73
|
throw new GateError(0, 'registry', `No domain event at seq ${sourceSeq} (audit rows are never undo targets)`, { code: 'undo.source_not_found' })
|
|
82
|
-
const meta =
|
|
74
|
+
const meta = operationMetaOf(row)
|
|
83
75
|
if (meta?.operationId) {
|
|
84
76
|
const rows = await cap.eventsOfOperation(meta.operationId)
|
|
85
77
|
return { source: buildSource(rows.length > 0 ? rows : [row], sourceSeq, false), operationId: meta.operationId }
|
|
@@ -89,7 +81,7 @@ async function resolveSource(cap: OperationLedgerCapability, sourceSeq: number):
|
|
|
89
81
|
}
|
|
90
82
|
|
|
91
83
|
function buildSource(rows: LedgerRow[], sourceSeq: number, legacy: boolean): SourceOperation {
|
|
92
|
-
const first =
|
|
84
|
+
const first = operationMetaOf(rows[0])
|
|
93
85
|
return {
|
|
94
86
|
operationId: legacy ? `legacy:${sourceSeq}` : first?.operationId ?? `legacy:${sourceSeq}`,
|
|
95
87
|
sourceSeq,
|
|
@@ -98,10 +90,7 @@ function buildSource(rows: LedgerRow[], sourceSeq: number, legacy: boolean): Sou
|
|
|
98
90
|
...(first?.commandVersion ? { commandVersion: first.commandVersion } : {}),
|
|
99
91
|
...(first?.commandRevision ? { commandRevision: first.commandRevision } : {}),
|
|
100
92
|
events: rows.map((r) => {
|
|
101
|
-
const
|
|
102
|
-
// envelope first, then the row's version column — the SAME precedence replay uses, so the
|
|
103
|
-
// planner and a rebuilding projection never disagree about which format version a row carries
|
|
104
|
-
const eventVersion = meta?.eventVersion !== undefined ? meta.eventVersion : r.version
|
|
93
|
+
const eventVersion = ledgerEventVersionOf(r)
|
|
105
94
|
return {
|
|
106
95
|
seq: r.seq,
|
|
107
96
|
type: r.type,
|
|
@@ -414,7 +403,7 @@ async function assertUndoReadRights(sourceSeq: number, identity: Identity): Prom
|
|
|
414
403
|
const cap = capability()
|
|
415
404
|
const compSeq = (await cap.compensationsOf(computed.operationId))[0]
|
|
416
405
|
const row = compSeq !== undefined ? await cap.domainRowBySeq(compSeq) : undefined
|
|
417
|
-
const meta = row ?
|
|
406
|
+
const meta = row ? operationMetaOf(row) : undefined
|
|
418
407
|
const def = meta?.commandName ? lookupCommand(meta.commandName) : undefined
|
|
419
408
|
if (!def || !row)
|
|
420
409
|
throw new GateError(
|