@sudoke/kernel 0.3.1 → 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/README.md +221 -0
- package/package.json +5 -4
- package/src/canonical.ts +18 -0
- package/src/catalog.ts +282 -0
- package/src/contract-shape.ts +531 -0
- package/src/execution-core.ts +115 -0
- package/src/gate-audit.ts +131 -0
- package/src/gate-results.ts +93 -0
- package/src/gate.ts +333 -386
- package/src/idempotency.ts +133 -0
- package/src/index.ts +7 -1
- package/src/mcp.ts +183 -29
- package/src/permissions.ts +92 -0
- package/src/projections.ts +16 -2
- package/src/protocol.ts +7 -1
- package/src/queries.ts +5 -0
- package/src/registry.ts +130 -6
- package/src/releases.ts +527 -0
- package/src/state.ts +33 -1
- package/src/storage.ts +44 -2
- package/src/types.ts +195 -0
- package/src/undo.ts +671 -0
package/src/releases.ts
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Release manifest validation — the pure checker that keeps version declarations honest.
|
|
3
|
+
*
|
|
4
|
+
* A release manifest pairs the declared semver (catalogVersion·per-command versions) with the change
|
|
5
|
+
* records and contract shapes of that release. The validator compares the previous release against the
|
|
6
|
+
* current one and fails when:
|
|
7
|
+
* - a contract changed (revision or shape difference) but no change record names it,
|
|
8
|
+
* - a structurally identifiable breaking change lacks a MAJOR bump,
|
|
9
|
+
* - a declared breaking change lacks a MAJOR bump or a migration note,
|
|
10
|
+
* - the catalog version did not move forward.
|
|
11
|
+
*
|
|
12
|
+
* What it deliberately does NOT do: prove semantic or permission compatibility. Meaning changes invisible
|
|
13
|
+
* to structure are the release author's explicit classification (compatibility field) — the validator
|
|
14
|
+
* holds them to their word (breaking ⇒ MAJOR + migration), never guesses in their place.
|
|
15
|
+
*
|
|
16
|
+
* Kernel tests exercise this directly; the repository check command (scripts/validate-release-manifest.mjs)
|
|
17
|
+
* runs it over real manifest files.
|
|
18
|
+
*/
|
|
19
|
+
import type { CatalogChangeRecord } from './types.js'
|
|
20
|
+
import { canonicalJson } from './canonical.js'
|
|
21
|
+
import { isRecognizableShape, NODE_KEYS, type CommandContractWrapper, type ContractField, type ContractNode, type QueryContractWrapper, type WalkableContract } from './contract-shape.js'
|
|
22
|
+
|
|
23
|
+
/** One command/query entry of a release manifest — version, content revision and (optionally) the
|
|
24
|
+
* contract shape (commandContractShape/queryContractShape output) enabling structural diffing */
|
|
25
|
+
export interface ReleaseManifestContract {
|
|
26
|
+
name: string
|
|
27
|
+
version?: string
|
|
28
|
+
revision?: string
|
|
29
|
+
shape?: unknown
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A catalog release as recorded beside the source — the previous and the current release feed the validator */
|
|
33
|
+
export interface CatalogReleaseManifest {
|
|
34
|
+
catalogVersion: string
|
|
35
|
+
releasedAt?: string
|
|
36
|
+
changes?: readonly CatalogChangeRecord[]
|
|
37
|
+
commands?: readonly ReleaseManifestContract[]
|
|
38
|
+
queries?: readonly ReleaseManifestContract[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** semver shape — the one pattern the kernel checks versions against (registry validation and the
|
|
42
|
+
* release validator share it; build metadata is shape-legal but never ordered) */
|
|
43
|
+
export const SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/
|
|
44
|
+
|
|
45
|
+
/** semver parse for ordering — build metadata is ignored (two versions differing only in build metadata
|
|
46
|
+
* are the same release; change detection must never depend on build-metadata ordering) */
|
|
47
|
+
function semverOf(v: string): { major: number; minor: number; patch: number } | null {
|
|
48
|
+
if (!SEMVER_RE.test(v)) return null
|
|
49
|
+
const [core] = v.split('+')
|
|
50
|
+
const [major, minor, patch] = core.split('-')[0].split('.').map(Number)
|
|
51
|
+
return { major, minor, patch }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const compareSemver = (a: string, b: string): number => {
|
|
55
|
+
const pa = semverOf(a)
|
|
56
|
+
const pb = semverOf(b)
|
|
57
|
+
if (!pa || !pb) return 0
|
|
58
|
+
if (pa.major !== pb.major) return pa.major - pb.major
|
|
59
|
+
if (pa.minor !== pb.minor) return pa.minor - pb.minor
|
|
60
|
+
return pa.patch - pb.patch
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Structural breaking detection over two contract shape trees (the fingerprint trees of catalog.ts —
|
|
65
|
+
* plain JSON, no zod needed here, so the validator stays pure and usable from scripts).
|
|
66
|
+
* Contract wrappers (commandContractShape·queryContractShape output) are unwrapped and each side walks
|
|
67
|
+
* with its own compatibility rule — loosening an INPUT is compatible, loosening an OUTPUT breaks
|
|
68
|
+
* consumers:
|
|
69
|
+
* - a field disappears → breaking on both sides
|
|
70
|
+
* - input: optional→required, strip→strict → breaking; required→optional, strict→strip → compatible
|
|
71
|
+
* - output: required→optional (the field may vanish from results) → breaking; optional→required → compatible
|
|
72
|
+
* - a type tag change, enum narrowing, tightened bounds → breaking on both sides
|
|
73
|
+
* Standalone trees (no wrapper, hand-built) are judged conservatively: BOTH requiredness directions break.
|
|
74
|
+
* Conservatism rule: an unknown node kind on either side is reported as breaking — a shape the classifier
|
|
75
|
+
* does not understand must never pass as provably compatible.
|
|
76
|
+
*/
|
|
77
|
+
type Side = 'input' | 'output' | 'standalone'
|
|
78
|
+
|
|
79
|
+
export function structuralBreakingChanges(prev: unknown, curr: unknown, path = ''): string[] {
|
|
80
|
+
// the input boundary: externally supplied trees are RECOGNIZED, never cast into a walk — an
|
|
81
|
+
// unrecognizable shape is reported as breaking (compatibility is never guessed for a tree the
|
|
82
|
+
// walker cannot read; valid trees, including hand-built partial ones, pass through typed)
|
|
83
|
+
if (!isRecognizableShape(prev) || !isRecognizableShape(curr))
|
|
84
|
+
return [`${path || '(root)'}: not a recognizable contract shape — compatibility is never guessed`]
|
|
85
|
+
return walkShape(prev as WalkableContract, curr as WalkableContract, path, 'standalone')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function walkShape(prev: WalkableContract, curr: WalkableContract, path: string, side: Side): string[] {
|
|
89
|
+
const breaking: string[] = []
|
|
90
|
+
const at = (p: string) => p || '(root)'
|
|
91
|
+
// contract wrappers — descend per side; the wrapper's own scalar fields (version·description·roles)
|
|
92
|
+
// are revision material, not structural breaks: the records and versions speak for them
|
|
93
|
+
if (isCommandWrapper(prev) && isCommandWrapper(curr)) {
|
|
94
|
+
breaking.push(...walkShape(prev['input'] as WalkableContract, curr['input'] as WalkableContract, 'input', 'input'))
|
|
95
|
+
breaking.push(...walkShape(prev['output'] as WalkableContract, curr['output'] as WalkableContract, 'output', 'output'))
|
|
96
|
+
return breaking
|
|
97
|
+
}
|
|
98
|
+
if (isQueryWrapper(prev) && isQueryWrapper(curr)) {
|
|
99
|
+
breaking.push(...walkRecord(paramsOf(prev), paramsOf(curr), 'params', 'input'))
|
|
100
|
+
breaking.push(...walkShape(prev['output'] as WalkableContract, curr['output'] as WalkableContract, 'output', 'output'))
|
|
101
|
+
return breaking
|
|
102
|
+
}
|
|
103
|
+
if (isNode(prev) && isNode(curr)) {
|
|
104
|
+
const prevKind = shapeKind(prev)
|
|
105
|
+
const currKind = shapeKind(curr)
|
|
106
|
+
if (prevKind !== currKind) {
|
|
107
|
+
breaking.push(`${at(path)}: type changed (${prevKind} → ${currKind})`)
|
|
108
|
+
return breaking
|
|
109
|
+
}
|
|
110
|
+
if (prevKind === 'object') {
|
|
111
|
+
const pf = fieldsOf(prev)
|
|
112
|
+
const cf = fieldsOf(curr)
|
|
113
|
+
for (const key of Object.keys(pf))
|
|
114
|
+
if (!(key in cf)) breaking.push(`${at(path)}.${key}: field removed`)
|
|
115
|
+
// a NEW field demanded of callers is breaking on the input side (old requests lack it);
|
|
116
|
+
// a new optional field, or any new result field (consumers may ignore extras), is compatible
|
|
117
|
+
for (const key of Object.keys(cf))
|
|
118
|
+
if (!(key in pf) && (cf[key] as { required?: boolean })?.required === true && side !== 'output')
|
|
119
|
+
breaking.push(`${at(path)}.${key}: required field added`)
|
|
120
|
+
for (const key of Object.keys(pf).filter((k) => k in cf)) {
|
|
121
|
+
const pd = pf[key]
|
|
122
|
+
const cd = cf[key]
|
|
123
|
+
const child = `${path}.${key}`
|
|
124
|
+
const wasRequired = pd.required === true
|
|
125
|
+
const nowRequired = cd.required === true
|
|
126
|
+
if (wasRequired && !nowRequired && side !== 'input')
|
|
127
|
+
breaking.push(`${at(child)}: required → optional`) // a result field that may vanish breaks consumers; standalone stays conservative
|
|
128
|
+
if (!wasRequired && nowRequired && side !== 'output')
|
|
129
|
+
breaking.push(`${at(child)}: optional → required`) // a demand the old callers never had to meet
|
|
130
|
+
// the wrapper CHAIN is contract — order, multiplicity and values all change what `{}` parses
|
|
131
|
+
// to, so they all MOVE the revision (the fingerprint keeps the exact chain). Compatibility is
|
|
132
|
+
// a DIFFERENT question, judged side-aware: optionality is the required-flag rules' business
|
|
133
|
+
// above; for the remaining core wrappers (default·catch·readonly·effects, in order) the
|
|
134
|
+
// OUTPUT side breaks on any difference (the guaranteed result set moved), while the INPUT side
|
|
135
|
+
// breaks only where OLD inputs stop being accepted — a default/catch wrapper REMOVED (omitted
|
|
136
|
+
// or invalid values used to pass) or a refine wrapper ADDED (new rejections). Additions,
|
|
137
|
+
// value changes and reordering keep every old input accepted: content change, not a break.
|
|
138
|
+
const coreWrap = (w: unknown[]): string[] =>
|
|
139
|
+
(w.filter((e) => e !== 'optional') as Array<string | [string, unknown]>).map((e) => (Array.isArray(e) ? e[0] : e))
|
|
140
|
+
const pw = pd.wrap ?? []
|
|
141
|
+
const cw = cd.wrap ?? []
|
|
142
|
+
const pc = coreWrap(pw)
|
|
143
|
+
const cc = coreWrap(cw)
|
|
144
|
+
if (side !== 'input') {
|
|
145
|
+
// OUTPUT: the FULL chain (optional position included) is the guaranteed result set — any
|
|
146
|
+
// difference breaks
|
|
147
|
+
if (JSON.stringify(pw) !== JSON.stringify(cw))
|
|
148
|
+
breaking.push(`${at(child)}: wrapper chain changed (${JSON.stringify(pw)} → ${JSON.stringify(cw)})`)
|
|
149
|
+
} else if (JSON.stringify(pc) !== JSON.stringify(cc)) {
|
|
150
|
+
const tally = (xs: string[]) => xs.reduce<Map<string, number>>((m, k) => m.set(k, (m.get(k) ?? 0) + 1), new Map())
|
|
151
|
+
const before = tally(pc)
|
|
152
|
+
const after = tally(cc)
|
|
153
|
+
for (const kind of ['default', 'catch'])
|
|
154
|
+
if ((before.get(kind) ?? 0) > (after.get(kind) ?? 0))
|
|
155
|
+
breaking.push(`${at(child)}: ${kind} wrapper removed — inputs the old contract accepted (omitted or invalid) are now rejected`)
|
|
156
|
+
if ((before.get('effects') ?? 0) < (after.get('effects') ?? 0))
|
|
157
|
+
breaking.push(`${at(child)}: refine wrapper added — inputs the old contract accepted may now be rejected`)
|
|
158
|
+
}
|
|
159
|
+
// OMISSION itself is acceptance: `omits` is the STRUCTURAL answer to "does `{}` pass this
|
|
160
|
+
// field?" (catalog.ts staticAccepts — no domain code runs) and it can flip while every
|
|
161
|
+
// wrapper KIND stays balanced — optional/default reordered (omission admission moves to the
|
|
162
|
+
// inner chain) or a default value changed to one its own constraint rejects. Both silently
|
|
163
|
+
// shrink the accepted input set, so a DEFINITE omits true→false on the input side breaks;
|
|
164
|
+
// 'unknown' (function semantics involved) never claims a direction. The reverse grows the
|
|
165
|
+
// set (relaxation); output nodes carry no omits flag because omission is an input-side
|
|
166
|
+
// question.
|
|
167
|
+
if (side === 'input' && pd.omits === true && cd.omits === false)
|
|
168
|
+
breaking.push(`${at(child)}: omitted values no longer accepted (wrapper order or default value changed)`)
|
|
169
|
+
if (pd.shape !== undefined && cd.shape !== undefined) {
|
|
170
|
+
breaking.push(...walkShape(pd.shape, cd.shape, child, side))
|
|
171
|
+
} else {
|
|
172
|
+
breaking.push(...walkShape(pf[key], cf[key], child, side))
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const strictness = (n: ContractNode) => n.object?.unknownKeys ?? 'strip'
|
|
176
|
+
if (side !== 'output' && strictness(prev) === 'strip' && strictness(curr) === 'strict')
|
|
177
|
+
breaking.push(`${at(path)}: unknown keys strip → strict`)
|
|
178
|
+
// the catchall is a declared sub-schema (default: never) — recurse like a field
|
|
179
|
+
const pCatch = prev.object?.catchall
|
|
180
|
+
const cCatch = curr.object?.catchall
|
|
181
|
+
if (pCatch !== undefined && cCatch !== undefined) breaking.push(...walkShape(pCatch, cCatch, `${path}.catchall`, side))
|
|
182
|
+
return breaking
|
|
183
|
+
}
|
|
184
|
+
if (prevKind === 'enum' || prevKind === 'nativeEnum') {
|
|
185
|
+
const pv = enumValuesOf(prev)
|
|
186
|
+
const cv = enumValuesOf(curr)
|
|
187
|
+
if (side === 'output') {
|
|
188
|
+
// the OUTPUT is a guarantee: a changed result set breaks it in BOTH directions — a new value
|
|
189
|
+
// is a result the consumer never knew, a removed one stopped appearing
|
|
190
|
+
if (canonicalOf([...pv].sort()) !== canonicalOf([...cv].sort()))
|
|
191
|
+
breaking.push(`${at(path)}: guaranteed enum set changed ([${pv.join(',')}] → [${cv.join(',')}])`)
|
|
192
|
+
} else {
|
|
193
|
+
// the INPUT is an acceptance set: only REMOVED values refuse previously valid input
|
|
194
|
+
for (const v of pv) if (!cv.includes(v)) breaking.push(`${at(path)}: enum value removed (${v})`)
|
|
195
|
+
}
|
|
196
|
+
return breaking
|
|
197
|
+
}
|
|
198
|
+
// leaf kinds with constraints — the fingerprint's check summaries (kind·value·inclusive·pattern).
|
|
199
|
+
// SIDE decides the question: input asks "does it still ACCEPT every input the old contract
|
|
200
|
+
// accepted?" (narrowing breaks, loosening is compatible); output asks "does it still GUARANTEE
|
|
201
|
+
// every result the old contract guaranteed?" (ANY change to the guaranteed set breaks — a dropped
|
|
202
|
+
// bound stops being guaranteed, an added enum value is a result the consumer never knew).
|
|
203
|
+
// Constraints are compared as MULTI-SETS per kind (zod allows repeated kinds — two regexes are a
|
|
204
|
+
// conjunction), bounds read absent-as-unlimited, and 'length' is exact (any value change moves
|
|
205
|
+
// the accepted/guaranteed set).
|
|
206
|
+
{
|
|
207
|
+
const group = (list: ReturnType<typeof checksOf>) => {
|
|
208
|
+
const m = new Map<string, Array<(typeof list)[number]>>()
|
|
209
|
+
for (const c of list) m.set(c.kind, [...(m.get(c.kind) ?? []), c])
|
|
210
|
+
return m
|
|
211
|
+
}
|
|
212
|
+
const pm = group(checksOf(prev))
|
|
213
|
+
const cm = group(checksOf(curr))
|
|
214
|
+
if (side === 'output') {
|
|
215
|
+
const kinds = new Set([...pm.keys(), ...cm.keys()])
|
|
216
|
+
for (const kind of kinds) {
|
|
217
|
+
if (kind === 'regex') {
|
|
218
|
+
const oldSet = [...(pm.get(kind) ?? [])].map((c) => canonicalOf(c.regex)).sort()
|
|
219
|
+
const newSet = [...(cm.get(kind) ?? [])].map((c) => canonicalOf(c.regex)).sort()
|
|
220
|
+
if (canonicalOf(oldSet) !== canonicalOf(newSet)) breaking.push(`${at(path)}: guaranteed pattern set changed`)
|
|
221
|
+
continue
|
|
222
|
+
}
|
|
223
|
+
const oldSet = [...(pm.get(kind) ?? [])].map((c) => canonicalOf(c)).sort()
|
|
224
|
+
const newSet = [...(cm.get(kind) ?? [])].map((c) => canonicalOf(c)).sort()
|
|
225
|
+
if (canonicalOf(oldSet) !== canonicalOf(newSet)) breaking.push(`${at(path)}: guaranteed constraint set changed (${kind})`)
|
|
226
|
+
}
|
|
227
|
+
} else {
|
|
228
|
+
for (const kind of cm.keys()) if (!pm.has(kind)) breaking.push(`${at(path)}: constraint added (${kind})`)
|
|
229
|
+
for (const [kind, list] of pm) {
|
|
230
|
+
const twins = cm.get(kind) ?? []
|
|
231
|
+
if (twins.length === 0) continue // constraint removed — loosening, compatible
|
|
232
|
+
if (kind === 'regex') {
|
|
233
|
+
// a conjunction: the accepted set shrinks when an old pattern vanished or changed
|
|
234
|
+
const oldSet = new Set(list.map((c) => canonicalOf(c.regex)))
|
|
235
|
+
const newSet = new Set(twins.map((c) => canonicalOf(c.regex)))
|
|
236
|
+
for (const o of oldSet) if (!newSet.has(o)) breaking.push(`${at(path)}: pattern removed`)
|
|
237
|
+
continue
|
|
238
|
+
}
|
|
239
|
+
const c = list[0]!
|
|
240
|
+
const twin = twins[0]!
|
|
241
|
+
const a = c.value === null ? undefined : c.value
|
|
242
|
+
const b = twin.value === null ? undefined : twin.value
|
|
243
|
+
if (kind === 'length') {
|
|
244
|
+
// exact length: any value change moves the accepted set (both directions)
|
|
245
|
+
if (a !== b) breaking.push(`${at(path)}: exact length changed (${describeBound(c)} → ${describeBound(twin)})`)
|
|
246
|
+
} else if (kind === 'min') {
|
|
247
|
+
const prevBound = a === undefined ? Number.NEGATIVE_INFINITY : Number(a)
|
|
248
|
+
const currBound = b === undefined ? Number.NEGATIVE_INFINITY : Number(b)
|
|
249
|
+
if (currBound > prevBound) breaking.push(`${at(path)}: min tightened (${describeBound(c)} → ${describeBound(twin)})`)
|
|
250
|
+
else if (currBound === prevBound && c.inclusive === true && twin.inclusive === false)
|
|
251
|
+
breaking.push(`${at(path)}: min bound made exclusive (${describeBound(c)} → ${describeBound(twin)})`)
|
|
252
|
+
} else if (kind === 'max') {
|
|
253
|
+
const prevBound = a === undefined ? Number.POSITIVE_INFINITY : Number(a)
|
|
254
|
+
const currBound = b === undefined ? Number.POSITIVE_INFINITY : Number(b)
|
|
255
|
+
if (currBound < prevBound) breaking.push(`${at(path)}: max tightened (${describeBound(c)} → ${describeBound(twin)})`)
|
|
256
|
+
else if (currBound === prevBound && c.inclusive === true && twin.inclusive === false)
|
|
257
|
+
breaking.push(`${at(path)}: max bound made exclusive (${describeBound(c)} → ${describeBound(twin)})`)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
// coercion narrowing: dropping coerce refuses the string-typed inputs the old contract parsed
|
|
263
|
+
if (side !== 'output' && prev['coerce'] === true && curr['coerce'] !== true)
|
|
264
|
+
breaking.push(`${at(path)}: coercion removed — previously parsed inputs are now refused`)
|
|
265
|
+
// array bounds live beside the checks (fingerprintShape: array.min/max/exact) — null means
|
|
266
|
+
// unlimited, so a bound appearing where none existed is a tightening too
|
|
267
|
+
{
|
|
268
|
+
const pn = prev.array
|
|
269
|
+
const cn = curr.array
|
|
270
|
+
if (pn && cn) {
|
|
271
|
+
const prevMin = typeof pn.min === 'number' ? pn.min : Number.NEGATIVE_INFINITY
|
|
272
|
+
const currMin = typeof cn.min === 'number' ? cn.min : Number.NEGATIVE_INFINITY
|
|
273
|
+
if (currMin > prevMin) breaking.push(`${at(path)}: array min raised (${pn.min ?? 'none'} → ${cn.min ?? 'none'})`)
|
|
274
|
+
const prevMax = typeof pn.max === 'number' ? pn.max : Number.POSITIVE_INFINITY
|
|
275
|
+
const currMax = typeof cn.max === 'number' ? cn.max : Number.POSITIVE_INFINITY
|
|
276
|
+
if (currMax < prevMax) breaking.push(`${at(path)}: array max lowered (${pn.max ?? 'none'} → ${cn.max ?? 'none'})`)
|
|
277
|
+
// exact length: appearing (null → number), vanishing or changing all move the accepted set
|
|
278
|
+
if ((pn.exact ?? null) !== (cn.exact ?? null))
|
|
279
|
+
breaking.push(`${at(path)}: array exact length changed (${pn.exact ?? 'none'} → ${cn.exact ?? 'none'})`)
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
// literal type/value — {t, v} nodes
|
|
283
|
+
if (prevKind === 'literal' || currKind === 'literal') {
|
|
284
|
+
const pl = prev.literal
|
|
285
|
+
const cl = curr.literal
|
|
286
|
+
if (pl && cl && (pl.t !== cl.t || pl.v !== cl.v)) breaking.push(`${at(path)}: literal changed (${pl.t}:${pl.v} → ${cl.t}:${cl.v})`)
|
|
287
|
+
}
|
|
288
|
+
// inner-shape carriers — recurse into EVERY child position of the fingerprint tree, so a type
|
|
289
|
+
// change inside an array element, a nullable/default/readonly/catch/effects wrapper, a record's
|
|
290
|
+
// key/value, an intersection's halves, a tuple's items or a union option is judged exactly like a
|
|
291
|
+
// top-level field
|
|
292
|
+
for (const key of ['nullable', 'optional', 'lazy', 'readonly'] as const)
|
|
293
|
+
if (prev[key] !== undefined && curr[key] !== undefined)
|
|
294
|
+
breaking.push(...walkShape(prev[key], curr[key], `${path}.${key}`, side))
|
|
295
|
+
for (const holder of ['default', 'effects', 'array', 'catch'] as const) {
|
|
296
|
+
const pn = prev[holder]
|
|
297
|
+
const cn = curr[holder]
|
|
298
|
+
if (pn?.shape !== undefined && cn?.shape !== undefined)
|
|
299
|
+
breaking.push(...walkShape(pn.shape, cn.shape, `${path}.${holder}`, side))
|
|
300
|
+
}
|
|
301
|
+
{
|
|
302
|
+
const pn = prev.record
|
|
303
|
+
const cn = curr.record
|
|
304
|
+
if (pn && cn) {
|
|
305
|
+
if (pn.key !== undefined && cn.key !== undefined) breaking.push(...walkShape(pn.key, cn.key, `${path}.record.key`, side))
|
|
306
|
+
if (pn.value !== undefined && cn.value !== undefined) breaking.push(...walkShape(pn.value, cn.value, `${path}.record.value`, side))
|
|
307
|
+
}
|
|
308
|
+
const pi = prev.intersection
|
|
309
|
+
const ci = curr.intersection
|
|
310
|
+
if (pi && ci) {
|
|
311
|
+
breaking.push(...walkShape(pi.left, ci.left, `${path}.intersection.left`, side))
|
|
312
|
+
breaking.push(...walkShape(pi.right, ci.right, `${path}.intersection.right`, side))
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (Array.isArray(prev.union) && Array.isArray(curr.union)) {
|
|
316
|
+
const pu = prev.union
|
|
317
|
+
const cu = curr.union
|
|
318
|
+
for (let i = 0; i < Math.min(pu.length, cu.length); i++)
|
|
319
|
+
breaking.push(...walkShape(pu[i], cu[i], `${path}.union[${i}]`, side))
|
|
320
|
+
if (cu.length < pu.length) breaking.push(`${at(path)}: union option removed (${pu.length} → ${cu.length} options)`)
|
|
321
|
+
}
|
|
322
|
+
{
|
|
323
|
+
const pt = prev.tuple
|
|
324
|
+
const ct = curr.tuple
|
|
325
|
+
if (Array.isArray(pt?.items) && Array.isArray(ct?.items)) {
|
|
326
|
+
if (pt!.items!.length !== ct!.items!.length) breaking.push(`${at(path)}: tuple arity changed (${pt!.items!.length} → ${ct!.items!.length})`)
|
|
327
|
+
for (let i = 0; i < Math.min(pt!.items!.length, ct!.items!.length); i++)
|
|
328
|
+
breaking.push(...walkShape(pt!.items![i], ct!.items![i], `${path}.tuple[${i}]`, side))
|
|
329
|
+
}
|
|
330
|
+
// the rest schema decides longer inputs — appearing, vanishing or changing moves what parses
|
|
331
|
+
if (pt && ct && canonicalOf(pt['rest'] ?? null) !== canonicalOf(ct['rest'] ?? null))
|
|
332
|
+
breaking.push(`${at(path)}: tuple rest changed`)
|
|
333
|
+
}
|
|
334
|
+
// conservative fallback: a tree node this walker does not recognize must never pass as provably
|
|
335
|
+
// compatible — differing content is reported as a break
|
|
336
|
+
if (prevKind === 'unknown' && canonicalOf(prev) !== canonicalOf(curr))
|
|
337
|
+
breaking.push(`${at(path)}: unrecognized node changed`)
|
|
338
|
+
return breaking
|
|
339
|
+
}
|
|
340
|
+
if (JSON.stringify(prev) !== JSON.stringify(curr)) {
|
|
341
|
+
breaking.push(`${at(path)}: value changed`)
|
|
342
|
+
}
|
|
343
|
+
return breaking
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** A plain key→tree record comparison (query params serialize as sorted [key, shape] pairs) */
|
|
347
|
+
function walkRecord(prev: Record<string, unknown>, curr: Record<string, unknown>, path: string, side: Side): string[] {
|
|
348
|
+
const breaking: string[] = []
|
|
349
|
+
for (const key of Object.keys(prev))
|
|
350
|
+
if (!(key in curr)) breaking.push(`${path}.${key}: param removed`)
|
|
351
|
+
for (const key of Object.keys(curr))
|
|
352
|
+
if (!(key in prev)) breaking.push(`${path}.${key}: required param added`)
|
|
353
|
+
for (const key of Object.keys(prev).filter((k) => k in curr))
|
|
354
|
+
breaking.push(...walkShape(prev[key] as WalkableContract, curr[key] as WalkableContract, `${path}.${key}`, side))
|
|
355
|
+
return breaking
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** query params: the fingerprint stores sorted [key, shape] pairs — rebuild the plain record */
|
|
359
|
+
function paramsOf(n: QueryContractWrapper): Record<string, unknown> {
|
|
360
|
+
const pairs = n['params']
|
|
361
|
+
if (!Array.isArray(pairs)) return (pairs as Record<string, unknown>) ?? {}
|
|
362
|
+
return Object.fromEntries(pairs as [string, unknown][])
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** NOT canonicalJson, deliberately: the walker's set comparisons serialize check objects in their
|
|
366
|
+
* own key order, so a hand-built manifest tree whose keys sit in another order compares unequal —
|
|
367
|
+
* the conservative direction for rules that only decide "did the guaranteed set move" */
|
|
368
|
+
const canonicalOf = (v: unknown): string => JSON.stringify(v)
|
|
369
|
+
const describeBound = (c: { value?: unknown; inclusive?: boolean }): string =>
|
|
370
|
+
`${String(c.value)}${c.inclusive === undefined ? '' : c.inclusive ? ' (incl)' : ' (excl)'}`
|
|
371
|
+
|
|
372
|
+
/** The walk's node gate — a string input is an unsupported marker (never a node), exactly as before */
|
|
373
|
+
const isNode = (v: WalkableContract): v is ContractNode => !!v && typeof v === 'object'
|
|
374
|
+
/** Wrapper gates — command/query wrappers are objects carrying kind; children are trees (the input
|
|
375
|
+
* boundary already guaranteed that), so the descent casts are boundary-backed */
|
|
376
|
+
const isCommandWrapper = (v: WalkableContract): v is CommandContractWrapper =>
|
|
377
|
+
!!v && typeof v === 'object' && (v as { kind?: unknown }).kind === 'command'
|
|
378
|
+
const isQueryWrapper = (v: WalkableContract): v is QueryContractWrapper =>
|
|
379
|
+
!!v && typeof v === 'object' && (v as { kind?: unknown }).kind === 'query'
|
|
380
|
+
|
|
381
|
+
function shapeKind(n: ContractNode): string {
|
|
382
|
+
for (const k of NODE_KEYS)
|
|
383
|
+
if (k in n) return k
|
|
384
|
+
return 'unknown'
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function fieldsOf(n: ContractNode): Record<string, ContractField> {
|
|
388
|
+
return n.object?.fields ?? {}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
function enumValuesOf(n: ContractNode): string[] {
|
|
393
|
+
if (n.enum) return n.enum.map(String)
|
|
394
|
+
if (n.nativeEnum) return n.nativeEnum.map((pair) => String(pair[1]))
|
|
395
|
+
return []
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function checksOf(n: ContractNode): Array<{ kind: string; value?: number | string | boolean | null; inclusive?: boolean; regex?: { source: string; flags: string } }> {
|
|
399
|
+
for (const k of ['string', 'number', 'bigint', 'date', 'array'] as const) {
|
|
400
|
+
const node = n[k]
|
|
401
|
+
if (node && Array.isArray(node.checks))
|
|
402
|
+
return node.checks as Array<{ kind: string; value?: number | string | boolean | null; inclusive?: boolean; regex?: { source: string; flags: string } }>
|
|
403
|
+
}
|
|
404
|
+
return []
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* The validator — pure; returns the list of problems (empty = the release declaration is consistent).
|
|
409
|
+
* `prev` null means "first recorded release" (nothing to diff against; only record hygiene is checked).
|
|
410
|
+
* Commands AND queries are diffed with the same rules: changed contracts demand records, structural
|
|
411
|
+
* breaks demand MAJOR bumps (per contract AND on the whole catalog), and record versions must match
|
|
412
|
+
* the manifests they claim to describe.
|
|
413
|
+
*/
|
|
414
|
+
export function validateReleaseManifest(prev: CatalogReleaseManifest | null, curr: CatalogReleaseManifest): string[] {
|
|
415
|
+
const errors: string[] = []
|
|
416
|
+
if (!semverOf(curr.catalogVersion)) errors.push(`catalogVersion is not valid semver: '${curr.catalogVersion}'`)
|
|
417
|
+
if (prev) {
|
|
418
|
+
if (!semverOf(prev.catalogVersion)) errors.push(`previous catalogVersion is not valid semver: '${prev.catalogVersion}'`)
|
|
419
|
+
else if (compareSemver(curr.catalogVersion, prev.catalogVersion) <= 0)
|
|
420
|
+
errors.push(`catalogVersion did not move forward: ${prev.catalogVersion} → ${curr.catalogVersion}`)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const records = curr.changes ?? []
|
|
424
|
+
for (const [i, r] of records.entries()) {
|
|
425
|
+
if (!r.summary || !r.summary.trim()) errors.push(`changes[${i}]: summary is required — the change list explains itself`)
|
|
426
|
+
if (r.compatibility === 'breaking' && (!r.migration || !r.migration.trim()))
|
|
427
|
+
errors.push(`changes[${i}]${r.name ? ` (${r.name})` : ''}: a breaking change requires a migration note`)
|
|
428
|
+
if (r.compatibility === 'breaking' && r.fromVersion && r.toVersion) {
|
|
429
|
+
const from = semverOf(r.fromVersion)
|
|
430
|
+
const to = semverOf(r.toVersion)
|
|
431
|
+
if (from && to && to.major <= from.major)
|
|
432
|
+
errors.push(`changes[${i}]${r.name ? ` (${r.name})` : ''}: declared breaking but the version is not a MAJOR bump (${r.fromVersion} → ${r.toVersion})`)
|
|
433
|
+
}
|
|
434
|
+
if ((r.fromVersion && !semverOf(r.fromVersion)) || (r.toVersion && !semverOf(r.toVersion)))
|
|
435
|
+
errors.push(`changes[${i}]${r.name ? ` (${r.name})` : ''}: fromVersion/toVersion must be valid semver`)
|
|
436
|
+
}
|
|
437
|
+
const recordOf = (name: string) => records.find((r) => r.name === name)
|
|
438
|
+
|
|
439
|
+
if (!prev) return errors
|
|
440
|
+
|
|
441
|
+
// One diff pass for commands and queries alike — read contracts version too, and their breaks are breaks
|
|
442
|
+
let anyStructuralBreak = false
|
|
443
|
+
let anyRemoval = false
|
|
444
|
+
for (const section of ['commands', 'queries'] as const) {
|
|
445
|
+
const label = section === 'commands' ? 'command' : 'query'
|
|
446
|
+
const prevEntries = new Map((prev[section] ?? []).map((c) => [c.name, c]))
|
|
447
|
+
const currEntries = new Map((curr[section] ?? []).map((c) => [c.name, c]))
|
|
448
|
+
for (const [name, c] of currEntries) {
|
|
449
|
+
const p = prevEntries.get(name)
|
|
450
|
+
if (!p) continue // an addition is a compatible change by structure — no record demanded
|
|
451
|
+
const revisionChanged = p.revision !== undefined && c.revision !== undefined && p.revision !== c.revision
|
|
452
|
+
const versionMoved = p.version !== undefined && c.version !== undefined && p.version !== c.version
|
|
453
|
+
const shapeChanged = !shapesEqual(p.shape, c.shape)
|
|
454
|
+
const shapeDiff =
|
|
455
|
+
p.shape !== undefined && c.shape !== undefined ? structuralBreakingChanges(p.shape, c.shape) : []
|
|
456
|
+
const record = recordOf(name)
|
|
457
|
+
if (revisionChanged || versionMoved || shapeChanged) {
|
|
458
|
+
if (!record)
|
|
459
|
+
errors.push(
|
|
460
|
+
versionMoved && !revisionChanged && !shapeChanged
|
|
461
|
+
? `${label} version moved without a change record: ${name} (${p.version} → ${c.version})`
|
|
462
|
+
: `changed contract without a change record: ${label} ${name} — declare what changed and why`,
|
|
463
|
+
)
|
|
464
|
+
// a record is necessary but not sufficient: the contract's OWN version must move too —
|
|
465
|
+
// describing the change while keeping the old version number hides it from consumers
|
|
466
|
+
if (revisionChanged || shapeChanged) {
|
|
467
|
+
if (p.version !== undefined && c.version !== undefined && p.version === c.version)
|
|
468
|
+
errors.push(`contract changed without a version bump: ${label} ${name} (${c.version} unchanged)`)
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
// the record must describe the REAL versions of this release — a fabricated MAJOR on paper is not a bump
|
|
472
|
+
if (record) {
|
|
473
|
+
if (record.fromVersion !== undefined && p.version !== undefined && record.fromVersion !== p.version)
|
|
474
|
+
errors.push(`${label} ${name}: the record's fromVersion (${record.fromVersion}) does not match the previous manifest (${p.version})`)
|
|
475
|
+
if (record.toVersion !== undefined && c.version !== undefined && record.toVersion !== c.version)
|
|
476
|
+
errors.push(`${label} ${name}: the record's toVersion (${record.toVersion}) does not match the current manifest (${c.version})`)
|
|
477
|
+
}
|
|
478
|
+
if (shapeDiff.length > 0) {
|
|
479
|
+
anyStructuralBreak = true
|
|
480
|
+
if (!record) errors.push(`breaking structural change without a change record: ${name} — ${shapeDiff.slice(0, 3).join('; ')}`)
|
|
481
|
+
else {
|
|
482
|
+
const from = record.fromVersion ?? p.version
|
|
483
|
+
const to = record.toVersion ?? c.version
|
|
484
|
+
if (from && to) {
|
|
485
|
+
const f = semverOf(from)
|
|
486
|
+
const t = semverOf(to)
|
|
487
|
+
if (f && t && t.major <= f.major)
|
|
488
|
+
errors.push(`breaking structural change without a MAJOR bump: ${name} (${from} → ${to}) — ${shapeDiff.slice(0, 3).join('; ')}`)
|
|
489
|
+
} else if (record.compatibility !== 'breaking') {
|
|
490
|
+
errors.push(`structural break detected but the record does not classify it as breaking: ${name} — ${shapeDiff.slice(0, 3).join('; ')}`)
|
|
491
|
+
}
|
|
492
|
+
if (record.compatibility === 'compatible')
|
|
493
|
+
errors.push(`the record claims compatibility but the structure broke: ${name} — ${shapeDiff.slice(0, 3).join('; ')}`)
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
for (const name of prevEntries.keys())
|
|
498
|
+
if (!currEntries.has(name)) {
|
|
499
|
+
const record = recordOf(name)
|
|
500
|
+
if (!record)
|
|
501
|
+
errors.push(`${label} removed without a change record: ${name} — a removal is breaking; record it with a replacement or migration`)
|
|
502
|
+
else {
|
|
503
|
+
anyRemoval = true
|
|
504
|
+
if (record.compatibility !== 'breaking') errors.push(`${label} removed but the record is not marked breaking: ${name}`)
|
|
505
|
+
const from = record.fromVersion
|
|
506
|
+
const to = record.toVersion
|
|
507
|
+
if (from && to && semverOf(from) && semverOf(to) && semverOf(to)!.major <= semverOf(from)!.major)
|
|
508
|
+
errors.push(`${label} removal without a MAJOR bump: ${name} (${from} → ${to})`)
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
// a structural break or a removal anywhere is a MAJOR for the WHOLE catalog — the aggregate version must say it
|
|
513
|
+
if ((anyStructuralBreak || anyRemoval) && prev && semverOf(prev.catalogVersion) && semverOf(curr.catalogVersion)) {
|
|
514
|
+
const fromMajor = semverOf(prev.catalogVersion)!.major
|
|
515
|
+
const toMajor = semverOf(curr.catalogVersion)!.major
|
|
516
|
+
if (toMajor <= fromMajor)
|
|
517
|
+
errors.push(`breaking change with a non-MAJOR catalogVersion: ${prev.catalogVersion} → ${curr.catalogVersion} — the aggregate version must carry the break`)
|
|
518
|
+
}
|
|
519
|
+
return errors
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Deep equality over plain JSON trees in CANONICAL form — key order never decides shape equality
|
|
523
|
+
* (shapes may be absent on either side; absent never equals present) */
|
|
524
|
+
function shapesEqual(a: unknown, b: unknown): boolean {
|
|
525
|
+
if (a === undefined || b === undefined) return a === b
|
|
526
|
+
return canonicalJson(a) === canonicalJson(b)
|
|
527
|
+
}
|
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 } from './types.js'
|
|
26
|
+
import type { CommandDefinition, ErrorCodeDefinition, EventUndoPolicy, KernelOptions, 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,6 +44,18 @@ 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) — strict mode requires full coverage */
|
|
48
|
+
undoPolicies: Map<string, EventUndoPolicy>
|
|
49
|
+
/** Undo handlers by id (registerUndoHandler) — domain-owned compensation planners */
|
|
50
|
+
undoHandlers: Map<string, UndoHandler>
|
|
51
|
+
/** Event payload format versions per type (registerEventVersions) — absent = 1 */
|
|
52
|
+
eventVersions: Map<string, number>
|
|
53
|
+
/** Assembly options (configureKernel) — sealed with the registries; null = compat */
|
|
54
|
+
options: KernelOptions | null
|
|
55
|
+
/** The served catalog release declaration (registerCatalogRelease) — null when the app declares none */
|
|
56
|
+
catalogRelease: CatalogRelease | null
|
|
57
|
+
/** Content fingerprints computed once at seal (completeAssembly fills this) */
|
|
58
|
+
revisions: CatalogRevisions | null
|
|
47
59
|
}
|
|
48
60
|
|
|
49
61
|
/** Kernel-common error codes — refusals the 9-stage gate and the query entry raise themselves. Seeded into
|
|
@@ -71,6 +83,20 @@ const KERNEL_COMMON_ERROR_CODES: Record<string, ErrorCodeDefinition> = {
|
|
|
71
83
|
'query.role_denied': { description: 'Query role not allowed (stage 3 policy)', recovery: 'stop' },
|
|
72
84
|
'query.params_invalid': { description: 'Query params violate the query contract', recovery: 'fix_input' },
|
|
73
85
|
'query.execution_failed': { description: 'Query handler error (often transient — safe to retry)', recovery: 'retry' },
|
|
86
|
+
// Contract-versioning refusals (strict mode writes) — no canForce: a stale contract is never a warning to override
|
|
87
|
+
'gate.contract_required': { description: 'Write without a contract — strict mode requires contract:{commandVersion,commandRevision,protocolVersion} beside the business input', recovery: 'fix_input' },
|
|
88
|
+
'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
|
+
// Undo (restore) refusals — none are forceable: hard conflicts and plan movement are never warnings
|
|
90
|
+
'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' },
|
|
91
|
+
'undo.unavailable': { description: 'The event type has no undo support — the registered policy says unavailable', recovery: 'stop' },
|
|
92
|
+
'undo.storage_capability_missing': { description: 'The registered storage engine lacks the operation-ledger capability — undo needs exact operation lookups', recovery: 'stop' },
|
|
93
|
+
'undo.already_undone': { description: 'The source operation already has a successful compensation — compensate that compensation instead to go back again', recovery: 'stop' },
|
|
94
|
+
'undo.plan_changed': { description: 'The undo plan changed since the preview (state·permission·contract moved) — preview again and confirm the new plan hash', recovery: 'refresh' },
|
|
95
|
+
'undo.confirmation_required': { description: 'The plan reports losses — resend the same plan with acceptLosses:true to confirm them explicitly', recovery: 'fix_input' },
|
|
96
|
+
'undo.legacy_operation_unknown': { description: 'Legacy event written before operation metadata — the operation grouping cannot be proven, undo is refused', recovery: 'stop' },
|
|
97
|
+
'undo.snapshot_missing': { description: 'The prior-state snapshot the compensation needs is missing from the ledger', recovery: 'stop' },
|
|
98
|
+
'undo.operation_mixed_policies': { description: 'The operation mixes event types with different undo policies — a single compensation cannot cover it', recovery: 'stop' },
|
|
99
|
+
'undo.plan_invalid': { description: 'The undo handler returned an invalid plan — handler defect', recovery: 'stop' },
|
|
74
100
|
}
|
|
75
101
|
|
|
76
102
|
const isPlainObject = (v: unknown): v is Record<string, unknown> =>
|
|
@@ -108,6 +134,12 @@ export function freshKernelState(): KernelState {
|
|
|
108
134
|
queries: new Map(),
|
|
109
135
|
storage: null,
|
|
110
136
|
sealed: false,
|
|
137
|
+
undoPolicies: new Map(),
|
|
138
|
+
undoHandlers: new Map(),
|
|
139
|
+
eventVersions: new Map(),
|
|
140
|
+
options: null,
|
|
141
|
+
catalogRelease: null,
|
|
142
|
+
revisions: null,
|
|
111
143
|
}
|
|
112
144
|
}
|
|
113
145
|
|