@sudoke/kernel 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +221 -0
- package/package.json +4 -3
- 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/visibility.ts +7 -2
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The contract shape — the canonical fingerprint tree every zod declaration is normalized into,
|
|
3
|
+
* and the structural reader that builds it. This is the kernel's ONE place that reads zod's
|
|
4
|
+
* internal `_def` structure: everything downstream (the published contract shapes, the revision
|
|
5
|
+
* digests, the release walker's compatibility rules) consumes the typed tree below, never zod.
|
|
6
|
+
*
|
|
7
|
+
* Reading rules the revision digest makes load-bearing — any change to this module moves
|
|
8
|
+
* revisions, so every change here is a release decision:
|
|
9
|
+
* - field wrappers are recorded as an ORDERED chain (`wrap`), never flattened — order and
|
|
10
|
+
* multiplicity are contract (`.optional().default('A')` and `.default('A').optional()` parse
|
|
11
|
+
* `{}` differently, nested defaults resolve the OUTER value);
|
|
12
|
+
* - constraint checks are canonicalized and sorted (declaration order carries no meaning);
|
|
13
|
+
* - the omission verdict (`omits`) is judged structurally (staticAccepts) — never by parsing,
|
|
14
|
+
* which would execute domain refine/transform bodies into the contract, and never through the
|
|
15
|
+
* schema's own RegExp objects (a g/y-flagged `.test` is stateful);
|
|
16
|
+
* - unsupported node kinds degrade LOUDLY (`unsupported(...)`), never silently.
|
|
17
|
+
*
|
|
18
|
+
* Internal module: not exported through index.ts.
|
|
19
|
+
*/
|
|
20
|
+
import { canonicalJson } from './canonical.js'
|
|
21
|
+
|
|
22
|
+
/** The single zod boundary — a structural stand-in for the pieces of zod's `_def` this reader uses.
|
|
23
|
+
* Properties are read after the `typeName` switch; the index signatures keep THIS file the only
|
|
24
|
+
* place (outside tests) that touches zod internals. */
|
|
25
|
+
interface ZodDef {
|
|
26
|
+
typeName?: string
|
|
27
|
+
[k: string]: any
|
|
28
|
+
}
|
|
29
|
+
interface ZodLike {
|
|
30
|
+
_def?: ZodDef
|
|
31
|
+
description?: string
|
|
32
|
+
shape?: Record<string, ZodLike>
|
|
33
|
+
schema?: ZodLike
|
|
34
|
+
[k: string]: any
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** One step of a field's wrapper chain, in declaration order — a bare kind or a [kind, value] pair */
|
|
38
|
+
export type WrapperStep = 'optional' | 'readonly' | ['default' | 'catch' | 'effects', unknown]
|
|
39
|
+
|
|
40
|
+
/** Canonicalized zod check (kind·value·inclusive·pattern source+flags — `message` is prose, dropped) */
|
|
41
|
+
export type ContractCheck = Record<string, unknown>
|
|
42
|
+
|
|
43
|
+
/** A field of an object node — `required` is the convenience flag, the `wrap` chain is the material */
|
|
44
|
+
export interface ContractField {
|
|
45
|
+
required: boolean
|
|
46
|
+
/** omission acceptance judged structurally; 'unknown' where function semantics would be needed */
|
|
47
|
+
omits: boolean | 'unknown'
|
|
48
|
+
shape: ContractShape
|
|
49
|
+
desc?: string
|
|
50
|
+
wrap?: WrapperStep[]
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The fingerprint tree — plain JSON by construction (canonicalJson sorts keys at hash time) */
|
|
54
|
+
export interface ContractNode {
|
|
55
|
+
desc?: string
|
|
56
|
+
coerce?: true
|
|
57
|
+
object?: { unknownKeys: string; fields: Record<string, ContractField>; catchall: ContractShape }
|
|
58
|
+
array?: { shape: ContractShape; min: number | null; max: number | null; exact: number | null; checks: ContractCheck[] }
|
|
59
|
+
string?: { checks: ContractCheck[] }
|
|
60
|
+
number?: { checks: ContractCheck[] }
|
|
61
|
+
bigint?: { checks: ContractCheck[] }
|
|
62
|
+
date?: { checks: ContractCheck[] }
|
|
63
|
+
enum?: unknown[]
|
|
64
|
+
nativeEnum?: Array<[string, string]>
|
|
65
|
+
literal?: { t: string; v: string }
|
|
66
|
+
nullable?: ContractShape
|
|
67
|
+
optional?: ContractShape
|
|
68
|
+
default?: { value: unknown; shape: ContractShape }
|
|
69
|
+
readonly?: ContractShape
|
|
70
|
+
catch?: { fallback: unknown; shape: ContractShape }
|
|
71
|
+
effects?: { count: number; shape: ContractShape }
|
|
72
|
+
union?: ContractShape[]
|
|
73
|
+
intersection?: { left: ContractShape; right: ContractShape }
|
|
74
|
+
tuple?: { items: ContractShape[]; rest: ContractShape | null }
|
|
75
|
+
record?: { key: ContractShape; value: ContractShape }
|
|
76
|
+
lazy?: ContractShape
|
|
77
|
+
boolean?: true
|
|
78
|
+
null?: true
|
|
79
|
+
any?: true
|
|
80
|
+
unknown?: true
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A whole tree — either a node or the loud unsupported-marker string for kinds the reader refuses
|
|
84
|
+
* to guess about (a silently degraded fingerprint would lie about the contract) */
|
|
85
|
+
export type ContractShape = ContractNode | string
|
|
86
|
+
|
|
87
|
+
/** The command/query wrappers catalog.commandContractShape·queryContractShape emit around the two
|
|
88
|
+
* trees — the comparator descends input·output·params from here (wrapper scalars are revision
|
|
89
|
+
* material, never walked) */
|
|
90
|
+
export interface CommandContractWrapper {
|
|
91
|
+
kind: 'command'
|
|
92
|
+
[k: string]: unknown
|
|
93
|
+
}
|
|
94
|
+
export interface QueryContractWrapper {
|
|
95
|
+
kind: 'query'
|
|
96
|
+
[k: string]: unknown
|
|
97
|
+
}
|
|
98
|
+
/** Everything the release comparator accepts as a walk input */
|
|
99
|
+
export type WalkableContract = ContractShape | CommandContractWrapper | QueryContractWrapper
|
|
100
|
+
|
|
101
|
+
/** The node member names a contract tree may carry — ONE list beside ContractNode, so a new node
|
|
102
|
+
* kind must be declared here to be walkable at all */
|
|
103
|
+
export const NODE_KEYS = [
|
|
104
|
+
'object', 'array', 'string', 'number', 'bigint', 'date', 'enum', 'nativeEnum', 'literal', 'nullable', 'optional',
|
|
105
|
+
'default', 'readonly', 'catch', 'effects', 'union', 'intersection', 'tuple', 'record', 'lazy', 'boolean', 'null',
|
|
106
|
+
'any', 'unknown', 'desc', 'coerce',
|
|
107
|
+
] as const
|
|
108
|
+
const WRAPPER_KEYS = [
|
|
109
|
+
'kind', 'name', 'version', 'behaviorRevision', 'description', 'example', 'deprecated', 'allowedRoles', 'scope',
|
|
110
|
+
'input', 'output', 'errors', 'transitions', 'clientScoped', 'public', 'params',
|
|
111
|
+
] as const
|
|
112
|
+
|
|
113
|
+
const isTree = (v: unknown): v is ContractShape => isRecognizableShape(v)
|
|
114
|
+
|
|
115
|
+
/** Whether an EXTERNALLY supplied value is a recognizable contract shape — the published fingerprint
|
|
116
|
+
* tree format, or its command/query wrapper. This is the comparator's input boundary: a tree that
|
|
117
|
+
* fails here is never cast into a walk; the caller reports it as unjudgeable (breaking), never lets
|
|
118
|
+
* it pass as provably compatible. Permissive about MISSING members (hand-built manifest trees may
|
|
119
|
+
* carry a subset), strict about present members having the right SHAPE. */
|
|
120
|
+
export function isRecognizableShape(v: unknown): boolean {
|
|
121
|
+
if (typeof v === 'string') return true // unsupported markers are part of the published format
|
|
122
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) return false
|
|
123
|
+
const n = v as Record<string, unknown>
|
|
124
|
+
if (n['kind'] === 'command' || n['kind'] === 'query') {
|
|
125
|
+
if (!Object.keys(n).every((k) => (WRAPPER_KEYS as readonly string[]).includes(k))) return false
|
|
126
|
+
// the walked children must be trees themselves — a junk input/output/params is refused with the
|
|
127
|
+
// wrapper, never silently walked as "no rules fired"
|
|
128
|
+
for (const child of ['input', 'output']) if (n[child] !== undefined && !isTree(n[child])) return false
|
|
129
|
+
const params = n['params']
|
|
130
|
+
if (params !== undefined) {
|
|
131
|
+
if (!Array.isArray(params)) return false
|
|
132
|
+
for (const pair of params)
|
|
133
|
+
if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== 'string' || !isTree(pair[1])) return false
|
|
134
|
+
}
|
|
135
|
+
return true
|
|
136
|
+
}
|
|
137
|
+
if (!Object.keys(n).every((k) => (NODE_KEYS as readonly string[]).includes(k))) return false
|
|
138
|
+
for (const [k, val] of Object.entries(n)) {
|
|
139
|
+
switch (k) {
|
|
140
|
+
case 'desc':
|
|
141
|
+
if (typeof val !== 'string') return false
|
|
142
|
+
break
|
|
143
|
+
case 'coerce':
|
|
144
|
+
case 'boolean':
|
|
145
|
+
case 'null':
|
|
146
|
+
case 'any':
|
|
147
|
+
case 'unknown':
|
|
148
|
+
if (val !== true) return false
|
|
149
|
+
break
|
|
150
|
+
case 'object': {
|
|
151
|
+
if (!val || typeof val !== 'object' || Array.isArray(val)) return false
|
|
152
|
+
const o = val as Record<string, unknown>
|
|
153
|
+
if (o['unknownKeys'] !== undefined && typeof o['unknownKeys'] !== 'string') return false
|
|
154
|
+
if (o['catchall'] !== undefined && !isTree(o['catchall'])) return false
|
|
155
|
+
const fields = o['fields']
|
|
156
|
+
if (fields === undefined) break
|
|
157
|
+
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return false
|
|
158
|
+
for (const f of Object.values(fields as Record<string, unknown>)) {
|
|
159
|
+
if (!f || typeof f !== 'object' || Array.isArray(f)) return false
|
|
160
|
+
const field = f as Record<string, unknown>
|
|
161
|
+
if (!Object.keys(field).every((fk) => ['required', 'omits', 'shape', 'desc', 'wrap'].includes(fk))) return false
|
|
162
|
+
if (field['required'] !== undefined && typeof field['required'] !== 'boolean') return false
|
|
163
|
+
if (field['omits'] !== undefined && field['omits'] !== true && field['omits'] !== false && field['omits'] !== 'unknown') return false
|
|
164
|
+
if (field['desc'] !== undefined && typeof field['desc'] !== 'string') return false
|
|
165
|
+
if (field['shape'] !== undefined && !isTree(field['shape'])) return false
|
|
166
|
+
const wrap = field['wrap']
|
|
167
|
+
if (wrap !== undefined) {
|
|
168
|
+
if (!Array.isArray(wrap)) return false
|
|
169
|
+
for (const w of wrap) {
|
|
170
|
+
if (typeof w === 'string') continue
|
|
171
|
+
if (!Array.isArray(w) || w.length !== 2 || typeof w[0] !== 'string') return false
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
break
|
|
176
|
+
}
|
|
177
|
+
case 'array':
|
|
178
|
+
case 'string':
|
|
179
|
+
case 'number':
|
|
180
|
+
case 'bigint':
|
|
181
|
+
case 'date': {
|
|
182
|
+
if (!val || typeof val !== 'object' || Array.isArray(val)) return false
|
|
183
|
+
// checks is OPTIONAL (partial trees) — its absence must never skip the OTHER members:
|
|
184
|
+
// every present member is validated whatever the rest looks like
|
|
185
|
+
const checks = (val as Record<string, unknown>)['checks']
|
|
186
|
+
if (checks !== undefined && (!Array.isArray(checks) || checks.some((c) => !c || typeof c !== 'object' || Array.isArray(c)))) return false
|
|
187
|
+
if (k === 'array') {
|
|
188
|
+
const a = val as Record<string, unknown>
|
|
189
|
+
if (a['shape'] !== undefined && !isTree(a['shape'])) return false
|
|
190
|
+
for (const b of ['min', 'max', 'exact']) if (a[b] !== undefined && a[b] !== null && typeof a[b] !== 'number') return false
|
|
191
|
+
}
|
|
192
|
+
break
|
|
193
|
+
}
|
|
194
|
+
case 'enum':
|
|
195
|
+
if (!Array.isArray(val)) return false
|
|
196
|
+
break
|
|
197
|
+
case 'nativeEnum':
|
|
198
|
+
if (!Array.isArray(val) || val.some((p) => !Array.isArray(p))) return false
|
|
199
|
+
break
|
|
200
|
+
case 'literal':
|
|
201
|
+
if (!val || typeof val !== 'object' || Array.isArray(val)) return false
|
|
202
|
+
break
|
|
203
|
+
case 'nullable':
|
|
204
|
+
case 'optional':
|
|
205
|
+
case 'readonly':
|
|
206
|
+
case 'lazy':
|
|
207
|
+
if (!isTree(val)) return false
|
|
208
|
+
break
|
|
209
|
+
case 'default':
|
|
210
|
+
case 'catch':
|
|
211
|
+
case 'effects': {
|
|
212
|
+
if (!val || typeof val !== 'object' || Array.isArray(val)) return false
|
|
213
|
+
const h = val as Record<string, unknown>
|
|
214
|
+
if (h['shape'] !== undefined && !isTree(h['shape'])) return false
|
|
215
|
+
if (k === 'effects' && h['count'] !== undefined && typeof h['count'] !== 'number') return false
|
|
216
|
+
break
|
|
217
|
+
}
|
|
218
|
+
case 'union':
|
|
219
|
+
if (!Array.isArray(val) || val.some((o) => !isTree(o))) return false
|
|
220
|
+
break
|
|
221
|
+
case 'tuple': {
|
|
222
|
+
if (!val || typeof val !== 'object' || Array.isArray(val)) return false
|
|
223
|
+
const t = val as Record<string, unknown>
|
|
224
|
+
if (t['items'] !== undefined && (!Array.isArray(t['items']) || t['items'].some((i) => !isTree(i)))) return false
|
|
225
|
+
if (t['rest'] !== undefined && t['rest'] !== null && !isTree(t['rest'])) return false
|
|
226
|
+
break
|
|
227
|
+
}
|
|
228
|
+
case 'record':
|
|
229
|
+
case 'intersection': {
|
|
230
|
+
if (!val || typeof val !== 'object' || Array.isArray(val)) return false
|
|
231
|
+
const r = val as Record<string, unknown>
|
|
232
|
+
for (const part of k === 'record' ? ['key', 'value'] : ['left', 'right'])
|
|
233
|
+
if (r[part] !== undefined && !isTree(r[part])) return false
|
|
234
|
+
break
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return true
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** zod stores .default(v) as a thunk — call it to read the value; a throwing or function-valued default
|
|
242
|
+
* degrades to a marker rather than crashing the fingerprint */
|
|
243
|
+
const defaultValueOf = (v: unknown): unknown => {
|
|
244
|
+
const value = typeof v === 'function' ? (() => {
|
|
245
|
+
try {
|
|
246
|
+
return (v as () => unknown)()
|
|
247
|
+
} catch {
|
|
248
|
+
return '[fn]'
|
|
249
|
+
}
|
|
250
|
+
})() : v
|
|
251
|
+
if (typeof value === 'function') return '[fn]'
|
|
252
|
+
try {
|
|
253
|
+
return JSON.parse(JSON.stringify(value ?? null))
|
|
254
|
+
} catch {
|
|
255
|
+
return String(value)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Constraint checks of a string/number/array schema, sorted by canonical form — the same constraint set
|
|
260
|
+
* declared in a different order hashes identically (order carries no contract meaning here).
|
|
261
|
+
* zod 3 check objects carry their kind in `kind` (email·uuid·regex·min·max·int…) with `value`,
|
|
262
|
+
* boundary `inclusive` flags and RegExp `regex` — every enumerable primitive prop is serialized
|
|
263
|
+
* (source AND flags of the pattern), so .email() vs .uuid(), gt vs gte, /abc/ vs /abc/i never collide.
|
|
264
|
+
* `message` stays out: it is prose, and the description above the field already carries prose in. */
|
|
265
|
+
function checkSummary(checks: unknown[] | undefined): ContractCheck[] {
|
|
266
|
+
return (checks ?? [])
|
|
267
|
+
.map((c) => {
|
|
268
|
+
const out: Record<string, unknown> = {}
|
|
269
|
+
for (const [k, v] of Object.entries(c as Record<string, unknown>)) {
|
|
270
|
+
if (k === 'message') continue
|
|
271
|
+
if (v instanceof RegExp) out[k] = { source: v.source, flags: v.flags }
|
|
272
|
+
else if (typeof v !== 'function' && typeof v !== 'object') out[k] = v
|
|
273
|
+
}
|
|
274
|
+
return out
|
|
275
|
+
})
|
|
276
|
+
.sort((a, b) => (canonicalJson(a) < canonicalJson(b) ? -1 : 1))
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* zod schema → canonical fingerprint tree. Richer than the catalog's describeShape docs: required/optional,
|
|
281
|
+
* defaults, enums, nullability, strict/unknown-key handling, ranges and regex patterns are all part of the
|
|
282
|
+
* contract, so all of them are serialized. What this CANNOT capture — functional refine/transformation
|
|
283
|
+
* bodies and business-logic meaning — is declared explicitly through behaviorRevision (folded into the
|
|
284
|
+
* revision); the kernel never claims the hash discovers meaning changes by itself.
|
|
285
|
+
*/
|
|
286
|
+
export function fingerprintShape(s: ZodLike | undefined, depth = 0): ContractShape {
|
|
287
|
+
if (!s || depth > 12) return `unsupported-depth:${String(s?._def?.typeName ?? 'none')}`
|
|
288
|
+
const d: ZodDef = s._def ?? {}
|
|
289
|
+
const node: ContractNode = {}
|
|
290
|
+
if (s.description) node.desc = s.description
|
|
291
|
+
// coercion changes what the schema ACCEPTS (string input parsed into the primitive) — declared
|
|
292
|
+
// contract, not function semantics, so it fingerprints
|
|
293
|
+
if (d.coerce) node.coerce = true
|
|
294
|
+
switch (d.typeName) {
|
|
295
|
+
case 'ZodObject': {
|
|
296
|
+
const fields: Record<string, ContractField> = {}
|
|
297
|
+
for (const [k, v] of Object.entries<ZodLike>(s.shape ?? d.shape ?? {})) {
|
|
298
|
+
// Peel wrappers ONE at a time, recording the chain IN ORDER. Order and multiplicity are
|
|
299
|
+
// contract: `.optional().default('A')` and `.default('A').optional()` parse `{}` differently
|
|
300
|
+
// ('A' vs undefined), and nested `.default('inner').default('outer')` resolves the OUTER
|
|
301
|
+
// value — a flattened record would erase exactly those differences. `required` stays as a
|
|
302
|
+
// convenience derived from the chain; the chain itself is the fingerprint material.
|
|
303
|
+
let optional = false
|
|
304
|
+
const wrap: WrapperStep[] = []
|
|
305
|
+
let outerDefault: { value: unknown } | undefined
|
|
306
|
+
let cur: ZodLike | undefined = v
|
|
307
|
+
for (let i = 0; i < 8 && cur; i++) {
|
|
308
|
+
const cd: ZodDef | undefined = cur._def
|
|
309
|
+
if (cd?.typeName === 'ZodOptional') {
|
|
310
|
+
optional = true
|
|
311
|
+
wrap.push('optional')
|
|
312
|
+
cur = cd.innerType
|
|
313
|
+
} else if (cd?.typeName === 'ZodDefault') {
|
|
314
|
+
const dv = defaultValueOf(cd.defaultValue)
|
|
315
|
+
wrap.push(['default', dv])
|
|
316
|
+
// the OUTERMOST default is the one an omitted input would hit — reuse the value just
|
|
317
|
+
// recorded into the chain so omits derives from the SAME material as the fingerprint
|
|
318
|
+
// (no second thunk evaluation, no drift between the published shape and the revision)
|
|
319
|
+
if (!outerDefault) outerDefault = { value: dv }
|
|
320
|
+
cur = cd.innerType
|
|
321
|
+
} else if (cd?.typeName === 'ZodCatch') {
|
|
322
|
+
wrap.push(['catch', defaultValueOf(cd.catchValue)])
|
|
323
|
+
cur = cd.innerType
|
|
324
|
+
} else if (cd?.typeName === 'ZodReadonly') {
|
|
325
|
+
wrap.push('readonly')
|
|
326
|
+
cur = cd.innerType
|
|
327
|
+
} else if (cd?.typeName === 'ZodEffects') {
|
|
328
|
+
wrap.push(['effects', (cd.effects ?? []).length])
|
|
329
|
+
cur = cd.schema ?? cd.innerType
|
|
330
|
+
} else break
|
|
331
|
+
}
|
|
332
|
+
const field: ContractField = {
|
|
333
|
+
required: !optional,
|
|
334
|
+
// omission acceptance judged structurally from the declared chain — never by parsing
|
|
335
|
+
// (parsing would execute domain code into the contract; see omitsOf)
|
|
336
|
+
omits: omitsOf(v, outerDefault),
|
|
337
|
+
shape: fingerprintShape(cur, depth + 1),
|
|
338
|
+
}
|
|
339
|
+
if (v.description) field.desc = v.description
|
|
340
|
+
if (wrap.length > 0) field.wrap = wrap
|
|
341
|
+
fields[k] = field
|
|
342
|
+
}
|
|
343
|
+
// the catchall schema (default: never) is declared contract — z.string() vs z.number() catchall
|
|
344
|
+
// changes what unknown keys are accepted as, so it fingerprints like a field
|
|
345
|
+
node.object = { unknownKeys: d.unknownKeys ?? 'strip', fields, catchall: fingerprintShape(d.catchall, depth + 1) }
|
|
346
|
+
break
|
|
347
|
+
}
|
|
348
|
+
case 'ZodArray':
|
|
349
|
+
// zod 3 keeps array bounds in minLength/maxLength/exactLength (not in checks) — a missed bound
|
|
350
|
+
// would make .min(1) and .min(9) (or .length(2) and .length(5)) hash identically, and bounds
|
|
351
|
+
// ARE the contract
|
|
352
|
+
node.array = {
|
|
353
|
+
shape: fingerprintShape(d.type ?? s.element, depth + 1),
|
|
354
|
+
min: (d.minLength as { value: number } | undefined)?.value ?? null,
|
|
355
|
+
max: (d.maxLength as { value: number } | undefined)?.value ?? null,
|
|
356
|
+
exact: (d.exactLength as { value: number } | undefined)?.value ?? null,
|
|
357
|
+
checks: checkSummary(d.checks),
|
|
358
|
+
}
|
|
359
|
+
break
|
|
360
|
+
case 'ZodString':
|
|
361
|
+
node.string = { checks: checkSummary(d.checks) }
|
|
362
|
+
break
|
|
363
|
+
case 'ZodNumber':
|
|
364
|
+
node.number = { checks: checkSummary(d.checks) }
|
|
365
|
+
break
|
|
366
|
+
case 'ZodBigInt':
|
|
367
|
+
node.bigint = { checks: checkSummary(d.checks) }
|
|
368
|
+
break
|
|
369
|
+
case 'ZodDate':
|
|
370
|
+
node.date = { checks: checkSummary(d.checks) }
|
|
371
|
+
break
|
|
372
|
+
case 'ZodEnum':
|
|
373
|
+
node.enum = [...(d.values ?? [])]
|
|
374
|
+
break
|
|
375
|
+
case 'ZodNativeEnum': {
|
|
376
|
+
const entries = Object.entries<any>(d.values ?? {}).filter(([k]) => Number.isNaN(Number(k)))
|
|
377
|
+
node.nativeEnum = entries.sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => [k, String(v)])
|
|
378
|
+
break
|
|
379
|
+
}
|
|
380
|
+
case 'ZodLiteral':
|
|
381
|
+
// the literal's TYPE is part of the contract — z.literal(1) and z.literal('1') must not collide
|
|
382
|
+
node.literal = { t: d.value === null ? 'null' : typeof d.value, v: String(d.value) }
|
|
383
|
+
break
|
|
384
|
+
case 'ZodNullable':
|
|
385
|
+
node.nullable = fingerprintShape(d.innerType, depth + 1)
|
|
386
|
+
break
|
|
387
|
+
case 'ZodOptional':
|
|
388
|
+
// the object-branch marks required:false already; a bare optional keeps its inner shape
|
|
389
|
+
node.optional = fingerprintShape(d.innerType, depth + 1)
|
|
390
|
+
break
|
|
391
|
+
case 'ZodDefault':
|
|
392
|
+
node.default = { value: defaultValueOf(d.defaultValue), shape: fingerprintShape(d.innerType, depth + 1) }
|
|
393
|
+
break
|
|
394
|
+
case 'ZodReadonly':
|
|
395
|
+
node.readonly = fingerprintShape(d.innerType, depth + 1)
|
|
396
|
+
break
|
|
397
|
+
case 'ZodCatch':
|
|
398
|
+
// the catch fallback is what invalid input PARSES to — a declared default, not function semantics
|
|
399
|
+
node.catch = { fallback: defaultValueOf(d.catchValue), shape: fingerprintShape(d.innerType, depth + 1) }
|
|
400
|
+
break
|
|
401
|
+
case 'ZodEffects':
|
|
402
|
+
// the refine/transformation bodies are invisible to the fingerprint — behaviorRevision carries meaning changes
|
|
403
|
+
node.effects = { count: (d.effects ?? []).length, shape: fingerprintShape(d.schema ?? d.innerType, depth + 1) }
|
|
404
|
+
break
|
|
405
|
+
case 'ZodUnion':
|
|
406
|
+
case 'ZodDiscriminatedUnion':
|
|
407
|
+
node.union = (d.options ?? []).map((o: ZodLike) => fingerprintShape(o, depth + 1))
|
|
408
|
+
break
|
|
409
|
+
case 'ZodIntersection':
|
|
410
|
+
node.intersection = { left: fingerprintShape(d.left, depth + 1), right: fingerprintShape(d.right, depth + 1) }
|
|
411
|
+
break
|
|
412
|
+
case 'ZodTuple':
|
|
413
|
+
// the rest schema (z.tuple([...]).rest(…)) decides what longer inputs are accepted — declared
|
|
414
|
+
// contract, serialized beside the fixed items (null = no rest)
|
|
415
|
+
node.tuple = { items: (d.items ?? []).map((i: ZodLike) => fingerprintShape(i, depth + 1)), rest: d.rest ? fingerprintShape(d.rest, depth + 1) : null }
|
|
416
|
+
break
|
|
417
|
+
case 'ZodRecord':
|
|
418
|
+
node.record = { key: fingerprintShape(d.keyType, depth + 1), value: fingerprintShape(d.valueType, depth + 1) }
|
|
419
|
+
break
|
|
420
|
+
case 'ZodLazy':
|
|
421
|
+
node.lazy = fingerprintShape(s.schema ?? (typeof d.getter === 'function' ? d.getter() : undefined), depth + 1)
|
|
422
|
+
break
|
|
423
|
+
case 'ZodBoolean':
|
|
424
|
+
node.boolean = true
|
|
425
|
+
break
|
|
426
|
+
case 'ZodNull':
|
|
427
|
+
node.null = true
|
|
428
|
+
break
|
|
429
|
+
case 'ZodAny':
|
|
430
|
+
node.any = true
|
|
431
|
+
break
|
|
432
|
+
case 'ZodUnknown':
|
|
433
|
+
node.unknown = true
|
|
434
|
+
break
|
|
435
|
+
default:
|
|
436
|
+
// silently degrading an unhandled type would make the fingerprint lie — surface the type name instead
|
|
437
|
+
return `unsupported(${String(d.typeName).replace(/^Zod/, '')})`
|
|
438
|
+
}
|
|
439
|
+
return node
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Whether a value PASSES this schema, judged from DECLARED structure alone — never by executing
|
|
443
|
+
* the schema. safeParse would run refine/transform bodies (review D1): a state-dependent refine
|
|
444
|
+
* makes the fingerprint boot-dependent and desynchronizes the published command_contract from the
|
|
445
|
+
* sealed revision. Here an outer optional admits omission; an outer default feeds its value — the
|
|
446
|
+
* SAME value the wrapper chain already recorded into the fingerprint, so no second evaluation and
|
|
447
|
+
* no divergence between the published shape and the revision — into the remaining chain, judged by
|
|
448
|
+
* built-in constraints only. Where function semantics would be needed — a refine/transform in the
|
|
449
|
+
* path, a default this walker did not pre-record, a value or node shape it does not enumerate —
|
|
450
|
+
* the answer is 'unknown': recorded honestly in the fingerprint, never sampled into a definite
|
|
451
|
+
* boolean, and never treated as a compatibility flip (releases.ts fires only on true→false). */
|
|
452
|
+
const staticAccepts = (schema: ZodLike | undefined, value: unknown, recordedDefault?: { value: unknown }): boolean | 'unknown' => {
|
|
453
|
+
if (!schema) return 'unknown'
|
|
454
|
+
const d: ZodDef = schema._def ?? {}
|
|
455
|
+
switch (d.typeName) {
|
|
456
|
+
case 'ZodOptional':
|
|
457
|
+
return value === undefined ? true : staticAccepts(d.innerType, value, recordedDefault)
|
|
458
|
+
case 'ZodNullable':
|
|
459
|
+
return value === null ? true : staticAccepts(d.innerType, value, recordedDefault)
|
|
460
|
+
case 'ZodReadonly':
|
|
461
|
+
return staticAccepts(d.innerType, value, recordedDefault)
|
|
462
|
+
case 'ZodCatch':
|
|
463
|
+
return true // a catch never rejects — inner failure resolves to the fallback value
|
|
464
|
+
case 'ZodDefault': {
|
|
465
|
+
if (value !== undefined) return staticAccepts(d.innerType, value, recordedDefault)
|
|
466
|
+
if (!recordedDefault) return 'unknown' // a default this walker did not pre-record — never guess
|
|
467
|
+
const dv = recordedDefault.value
|
|
468
|
+
if (dv === null || typeof dv === 'object') return 'unknown' // only primitive default values are judged
|
|
469
|
+
return staticAccepts(d.innerType, dv, recordedDefault)
|
|
470
|
+
}
|
|
471
|
+
case 'ZodUnion': {
|
|
472
|
+
let sawUnknown = false
|
|
473
|
+
for (const option of (d.options ?? []) as ZodLike[]) {
|
|
474
|
+
const r = staticAccepts(option, value, recordedDefault)
|
|
475
|
+
if (r === true) return true
|
|
476
|
+
if (r === 'unknown') sawUnknown = true
|
|
477
|
+
}
|
|
478
|
+
return sawUnknown ? 'unknown' : false
|
|
479
|
+
}
|
|
480
|
+
case 'ZodEnum':
|
|
481
|
+
return (d.values as unknown[]).includes(value)
|
|
482
|
+
case 'ZodLiteral':
|
|
483
|
+
return value === d.value
|
|
484
|
+
case 'ZodString': {
|
|
485
|
+
if (typeof value !== 'string') return false
|
|
486
|
+
for (const c of (d.checks ?? []) as Array<Record<string, any>>) {
|
|
487
|
+
if (c.kind === 'min' && (c.inclusive === false ? value.length <= c.value : value.length < c.value)) return false
|
|
488
|
+
if (c.kind === 'max' && (c.inclusive === false ? value.length >= c.value : value.length > c.value)) return false
|
|
489
|
+
if (c.kind === 'length' && value.length !== c.value) return false
|
|
490
|
+
if (c.kind === 'regex') {
|
|
491
|
+
// never test the schema's OWN RegExp — a g/y-flagged .test is stateful (lastIndex reads
|
|
492
|
+
// and writes), which would alternate the structural verdict across repeated derivations
|
|
493
|
+
// AND mutate the caller's regex (review REX1). A fresh clone from source/flags always
|
|
494
|
+
// starts at position 0 and leaves the original untouched.
|
|
495
|
+
const re = c.regex as RegExp
|
|
496
|
+
if (!new RegExp(re.source, re.flags).test(value)) return false
|
|
497
|
+
}
|
|
498
|
+
// built-in formats (email, uuid, …) and transforms (trim, …) are not re-implemented here
|
|
499
|
+
if (!['min', 'max', 'length', 'regex'].includes(c.kind)) return 'unknown'
|
|
500
|
+
}
|
|
501
|
+
return true
|
|
502
|
+
}
|
|
503
|
+
case 'ZodNumber': {
|
|
504
|
+
if (typeof value !== 'number') return false
|
|
505
|
+
for (const c of (d.checks ?? []) as Array<Record<string, any>>) {
|
|
506
|
+
if (c.kind === 'min' && (c.inclusive === false ? value <= c.value : value < c.value)) return false
|
|
507
|
+
if (c.kind === 'max' && (c.inclusive === false ? value >= c.value : value > c.value)) return false
|
|
508
|
+
if (c.kind === 'lt' && !(value < c.value)) return false
|
|
509
|
+
if (c.kind === 'gt' && !(value > c.value)) return false
|
|
510
|
+
if (c.kind === 'int' && !Number.isInteger(value)) return false
|
|
511
|
+
if (c.kind === 'finite' && !Number.isFinite(value)) return false
|
|
512
|
+
if (!['min', 'max', 'lt', 'gt', 'int', 'finite'].includes(c.kind)) return 'unknown'
|
|
513
|
+
}
|
|
514
|
+
return true
|
|
515
|
+
}
|
|
516
|
+
case 'ZodBoolean':
|
|
517
|
+
return typeof value === 'boolean'
|
|
518
|
+
case 'ZodBigInt':
|
|
519
|
+
return typeof value === 'bigint'
|
|
520
|
+
default:
|
|
521
|
+
// containers (object·array·record·…), effects, lazy and unrecognized nodes: acceptance may
|
|
522
|
+
// exist behind structure (or code) this walker defers on — never a guess, always 'unknown'
|
|
523
|
+
return 'unknown'
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Whether the field accepts an OMITTED value — the structural answer for undefined (see
|
|
528
|
+
* staticAccepts); releases.ts turns a definite omits true→false on the input side into a breaking
|
|
529
|
+
* change, while 'unknown' never claims either direction. */
|
|
530
|
+
const omitsOf = (schema: ZodLike | undefined, recordedDefault?: { value: unknown }): boolean | 'unknown' =>
|
|
531
|
+
staticAccepts(schema, undefined, recordedDefault)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The execution core — what actually runs inside the caller's write transaction: the ledger
|
|
3
|
+
* append (with the operation envelope) and the one command pipeline (execute → output contract →
|
|
4
|
+
* events → projections → in-transaction success audit). Single commands, batch items and undo
|
|
5
|
+
* compensations all pass through here — there is no bypass lane. Always called inside a
|
|
6
|
+
* transaction opened by the gate entry points.
|
|
7
|
+
*
|
|
8
|
+
* Internal module: not exported through index.ts (no public unchecked execution).
|
|
9
|
+
*/
|
|
10
|
+
import { storageOf } from './storage.js'
|
|
11
|
+
import { eventContractOf, eventVersionOf } from './registry.js'
|
|
12
|
+
import { applyDomainEvent } from './projections.js'
|
|
13
|
+
import { recordAudit } from './gate-audit.js'
|
|
14
|
+
import { GateError } from './types.js'
|
|
15
|
+
import type { CommandDefinition, DomainEvent, EventOperationMeta, Identity } from './types.js'
|
|
16
|
+
|
|
17
|
+
/** Ledger append (domain event) — gate-internal only, never exported: there is no public API for writing
|
|
18
|
+
* the ledger, so events reach it only through command execution. The format contract is checked here:
|
|
19
|
+
* unregistered types and violations are never written (exception → stage-8 refusal·rollback). Replay
|
|
20
|
+
* (reads) skips validation for past-format compatibility — the contract is the source of truth for what
|
|
21
|
+
* is written *now*. The operation context, when present and the engine carries the operation-ledger
|
|
22
|
+
* capability, rides beside the payload as the kernel-written envelope. */
|
|
23
|
+
async function appendEvent(e: DomainEvent, op?: OperationContext): Promise<{ seq: number; ts: string; eventVersion?: number }> {
|
|
24
|
+
const contract = eventContractOf(e.type)
|
|
25
|
+
if (!contract)
|
|
26
|
+
throw new GateError(8, 'execute', `No event contract registered for type: ${e.type} — register it with registerEventContracts`, {
|
|
27
|
+
code: 'gate.event_contract_violation',
|
|
28
|
+
})
|
|
29
|
+
const checked = contract.safeParse(e.payload)
|
|
30
|
+
if (!checked.success)
|
|
31
|
+
throw new GateError(
|
|
32
|
+
8,
|
|
33
|
+
'execute',
|
|
34
|
+
`Event violates its format contract: ${e.type} — ${checked.error.issues
|
|
35
|
+
.map((i) => `${i.path.join('.')}: ${i.message}`)
|
|
36
|
+
.join('; ')}`,
|
|
37
|
+
{ code: 'gate.event_contract_violation' },
|
|
38
|
+
)
|
|
39
|
+
// ts is fixed once so storage and projection use the same value — the recorded time, not the replay time, stays in business data
|
|
40
|
+
const ts = new Date().toISOString()
|
|
41
|
+
const capability = storageOf().operationLedger
|
|
42
|
+
let seq: number
|
|
43
|
+
let eventVersion: number | undefined
|
|
44
|
+
if (op && capability) {
|
|
45
|
+
eventVersion = op.eventVersion ?? eventVersionOf(e.type)
|
|
46
|
+
const meta: EventOperationMeta = {
|
|
47
|
+
operationId: op.operationId,
|
|
48
|
+
...(op.batchId ? { batchId: op.batchId } : {}),
|
|
49
|
+
commandName: op.commandName,
|
|
50
|
+
...(op.commandVersion ? { commandVersion: op.commandVersion } : {}),
|
|
51
|
+
...(op.commandRevision ? { commandRevision: op.commandRevision } : {}),
|
|
52
|
+
...(eventVersion !== undefined ? { eventVersion } : {}),
|
|
53
|
+
...(op.undo ? { undoOfOperationId: op.undo.sourceOperationId, undoSourceSeq: op.undo.sourceSeq, undoHandlerVersion: op.undo.handlerVersion } : {}),
|
|
54
|
+
...(op.policyTarget !== undefined ? { policyTarget: op.policyTarget } : {}),
|
|
55
|
+
}
|
|
56
|
+
seq = await capability.appendDomainRowWithMeta(e, ts, meta)
|
|
57
|
+
} else {
|
|
58
|
+
seq = await storageOf().appendDomainRow(e, ts)
|
|
59
|
+
}
|
|
60
|
+
return { seq, ts, ...(eventVersion !== undefined ? { eventVersion } : {}) }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The operation context one command run carries onto its events — the envelope the operation-ledger
|
|
64
|
+
* engines persist beside the payload. Shared by single commands, batch items (each its own operation,
|
|
65
|
+
* grouped by batchId) and undo compensations (the undo fields link back to the source operation). */
|
|
66
|
+
export interface OperationContext {
|
|
67
|
+
operationId: string
|
|
68
|
+
batchId?: string
|
|
69
|
+
commandName: string
|
|
70
|
+
commandVersion?: string
|
|
71
|
+
commandRevision?: string
|
|
72
|
+
eventVersion?: number
|
|
73
|
+
undo?: { sourceOperationId: string; sourceSeq: number; handlerVersion: string }
|
|
74
|
+
/** the normalized policy target this execution was authorized against — stamped by runCommand */
|
|
75
|
+
policyTarget?: string
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Command execution (event append + projection apply + audit) — always called inside a transaction.
|
|
79
|
+
* Exported for undo.ts (the compensation runs the same pipeline — there is no bypass lane), never
|
|
80
|
+
* through index.ts (no public unchecked execution). */
|
|
81
|
+
export async function runCommand(
|
|
82
|
+
def: CommandDefinition<any>,
|
|
83
|
+
name: string,
|
|
84
|
+
input: any,
|
|
85
|
+
rawInput: unknown,
|
|
86
|
+
identity: Identity,
|
|
87
|
+
op: OperationContext,
|
|
88
|
+
auditExtra?: Record<string, unknown>,
|
|
89
|
+
) {
|
|
90
|
+
const { events, result } = await def.execute(input, identity)
|
|
91
|
+
// Output contract — the result shape is checked before commit (the same place as the event contract).
|
|
92
|
+
// A violation is a stage-8 refusal with a full rollback.
|
|
93
|
+
const checked = def.output.safeParse(result)
|
|
94
|
+
if (!checked.success)
|
|
95
|
+
throw new GateError(
|
|
96
|
+
8,
|
|
97
|
+
'execute',
|
|
98
|
+
`Command output violates its contract: ${name} — ${checked.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`,
|
|
99
|
+
{ code: 'gate.output_contract_violation' },
|
|
100
|
+
)
|
|
101
|
+
const eventTypes: string[] = []
|
|
102
|
+
// the normalized policy target this execution was authorized against — recorded on the envelope so
|
|
103
|
+
// later rights checks read the material instead of guessing it from aggregate ids or field names
|
|
104
|
+
const policyTarget = def.scope !== 'none' ? def.targetOf?.(input as never) : undefined
|
|
105
|
+
for (const e of events) {
|
|
106
|
+
// The recording timestamp is fixed once so storage and projection use the same value — replay and live produce the same state
|
|
107
|
+
const { seq, ts, eventVersion } = await appendEvent(e, { ...op, ...(policyTarget !== undefined ? { policyTarget } : {}) })
|
|
108
|
+
await applyDomainEvent(e, { seq, ts, ...(eventVersion !== undefined ? { eventVersion } : {}) })
|
|
109
|
+
eventTypes.push(e.type)
|
|
110
|
+
}
|
|
111
|
+
// The success audit is part of the business transaction — a failed insert propagates and rolls the whole
|
|
112
|
+
// command back (stage-8 refusal). It is never routed through the out-of-transaction helper.
|
|
113
|
+
await recordAudit(name, identity, 'ok', rawInput, undefined, auditExtra)
|
|
114
|
+
return { result, eventTypes }
|
|
115
|
+
}
|