@sudoke/kernel 0.0.0-stage → 0.2.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.
@@ -0,0 +1,235 @@
1
+ import { GateError, type CommandDefinition, type ErrorCodeDefinition } from './types.js'
2
+ import type { ZodTypeAny } from 'zod'
3
+ import { describeShape } from './queries.js'
4
+ import { assertOpenFor, defaultKernelState, frozenCopyOf, sealFor } from './state.js'
5
+
6
+ /**
7
+ * Kernel registry — registers and looks up command definitions and transition tables (S-03).
8
+ * The kernel knows nothing of catalog contents: the app's catalog module registers,
9
+ * and the gate executes only registered definitions. Unregistered commands are refused at
10
+ * stage 0 (registry), unregistered transition tables at stage 7 (transitions).
11
+ */
12
+
13
+ export function registerRoles(list: readonly string[]): void {
14
+ assertOpenFor(defaultKernelState, 'registerRoles')
15
+ for (const r of list) {
16
+ if (!r) throw new Error('Role name cannot be empty')
17
+ if (defaultKernelState.roles.has(r)) throw new Error(`Role registered twice: ${r}`)
18
+ defaultKernelState.roles.add(r)
19
+ }
20
+ }
21
+ /** Role registration — the app registers its role vocabulary. The kernel knows no name semantics; commands and transition tables may reference only registered roles */
22
+
23
+ /** Command registration — duplicate names, empty or unregistered role references, and missing output contracts fail the assembly */
24
+ export function registerCommand(def: CommandDefinition<any, any>): void {
25
+ assertOpenFor(defaultKernelState, `registerCommand ${def.name}`)
26
+ if (defaultKernelState.commands.has(def.name)) throw new Error(`Command registered twice: ${def.name}`)
27
+ if (def.allowedRoles.length === 0) throw new Error(`allowedRoles is empty: ${def.name} — declare at least one role`)
28
+ for (const r of def.allowedRoles)
29
+ if (!defaultKernelState.roles.has(r))
30
+ throw new Error(`Command references an unregistered role: ${def.name} → '${r}' — register it with registerRoles first`)
31
+ if (!def.output)
32
+ throw new Error(`Missing output contract: ${def.name} — declare the result shape with zod (use z.null() when there is nothing to return)`)
33
+ // copy-and-freeze: the caller's object is never touched (no hidden freeze), and the registry's copy
34
+ // shares no plain object with anyone — see frozenCopyOf. The spread wrap guarantees the top level is a
35
+ // fresh plain object even for exotic registrant objects.
36
+ defaultKernelState.commands.set(def.name, frozenCopyOf({ ...def }))
37
+ }
38
+
39
+ export const lookupCommand = (name: string): CommandDefinition<any, any> | undefined => defaultKernelState.commands.get(name)
40
+
41
+ /** Registered commands — a fresh array of the frozen originals (the array is new; the definitions are not copies) */
42
+ export const allCommands = (): CommandDefinition<any, any>[] => [...defaultKernelState.commands.values()]
43
+
44
+ /** Unwraps z.object(...).refine(...) etc. down to the ZodRawShape (for tool schemas and field docs) */
45
+ export const inputShapeOf = (input: any): Record<string, any> => {
46
+ let s = input
47
+ for (let i = 0; i < 5 && s; i++) {
48
+ if (s.shape) return s.shape
49
+ s = s._def?.schema ?? s._def?.innerType
50
+ }
51
+ return {}
52
+ }
53
+
54
+ /** Extracts .describe() docs beneath optional/nullable/refine wrappers */
55
+ const describeOf = (s: any): string | undefined => {
56
+ for (let i = 0; i < 6 && s; i++) {
57
+ if (s.description) return s.description
58
+ s = s._def?.innerType ?? s._def?.schema
59
+ }
60
+ return undefined
61
+ }
62
+
63
+ /** Catalog guidance — every surface (REST /api/catalog, MCP catalog tool) derives from here.
64
+ * Content (descriptions·examples·roles) comes from registered command definitions; this formatter knows only the shape.
65
+ * output (the shape of a successful result) and errors (raisable business error codes) are published here too —
66
+ * the same derivation used for query outputs. */
67
+ export function catalogMeta() {
68
+ return allCommands().map((d) => ({
69
+ name: d.name,
70
+ description: d.description,
71
+ example: d.example,
72
+ allowedRoles: d.allowedRoles,
73
+ scope: d.scope,
74
+ hasTransition: !!d.transition,
75
+ ...(d.deprecated ? { deprecated: d.deprecated } : {}),
76
+ fields: Object.fromEntries(
77
+ Object.entries(inputShapeOf(d.input))
78
+ .map(([k, v]) => [k, describeOf(v)])
79
+ .filter(([, v]) => !!v),
80
+ ),
81
+ output: describeShape(d.output),
82
+ errors: (d.errors ?? []).map((code) => ({ code, ...(errorCodeOf(code) ?? { description: '(unregistered code)', recovery: 'stop' as const }) })),
83
+ }))
84
+ }
85
+
86
+ /** Transition rules — declares from→to together with the command and allowed roles. Roles are catalog-exposed metadata */
87
+ export interface TransitionRule {
88
+ from: string
89
+ to: string
90
+ command: string
91
+ roles: readonly string[]
92
+ }
93
+
94
+ /** Transition-table registration — the app's state-machine module registers at boot.
95
+ * Rules are copied once and frozen (the registrant's own objects stay untouched; see frozenCopyOf). */
96
+ export function registerTransitionMachine(machine: string, rules: readonly TransitionRule[]): void {
97
+ assertOpenFor(defaultKernelState, `registerTransitionMachine ${machine}`)
98
+ if (defaultKernelState.machines.has(machine)) throw new Error(`Transition table registered twice: ${machine}`)
99
+ for (const rule of rules)
100
+ for (const r of rule.roles)
101
+ if (!defaultKernelState.roles.has(r))
102
+ throw new Error(`Transition table references an unregistered role: ${machine}/${rule.command} → '${r}'`)
103
+ defaultKernelState.machines.set(machine, rules.map((r) => frozenCopyOf({ ...r })))
104
+ }
105
+
106
+ /** Registered transition table — the frozen original; missing means a stage-7 refusal (never silently passed) */
107
+ export const transitionRulesOf = (machine: string): readonly TransitionRule[] => {
108
+ const rules = defaultKernelState.machines.get(machine)
109
+ if (!rules) throw new GateError(7, 'transition', `Unregistered transition table: ${machine}`, { code: 'gate.transition_unregistered' })
110
+ return rules
111
+ }
112
+
113
+ /** All registered transition tables — exported by the self-describing catalog (REST /api/catalog·MCP catalog tool).
114
+ * A fresh outer record of the frozen rule lists */
115
+ export const allTransitionMachines = (): Record<string, readonly TransitionRule[]> =>
116
+ Object.fromEntries([...defaultKernelState.machines.entries()])
117
+
118
+ /** Event format contract registration — the app registers payload contracts for its events.
119
+ * appendEvent checks writes against registered contracts: unregistered types and violations never reach the ledger
120
+ * and become gate refusals (stage 8) — cutting format drift between commands (producers) and surfaces (consumers) at write time.
121
+ * The kernel knows nothing of contract contents: formats belong to the app, the 'must pass the contract to write' rule to the kernel. */
122
+ export function registerEventContracts(contracts: Record<string, ZodTypeAny>): void {
123
+ assertOpenFor(defaultKernelState, 'registerEventContracts')
124
+ for (const [type, schema] of Object.entries(contracts)) {
125
+ if (defaultKernelState.eventContracts.has(type)) throw new Error(`Event contract registered twice: ${type}`)
126
+ defaultKernelState.eventContracts.set(type, schema)
127
+ }
128
+ }
129
+
130
+ export const eventContractOf = (type: string): ZodTypeAny | undefined => defaultKernelState.eventContracts.get(type)
131
+
132
+ /** Registered event-contract types — used for assembly completeness checks (every event has a contract) */
133
+ export const allEventContractTypes = (): string[] => [...defaultKernelState.eventContracts.keys()]
134
+
135
+ /**
136
+ * Error-code registry — the dictionary of stable refusal identifiers (code). The kernel seeds the common
137
+ * codes (gate.*) at creation and the domain registers its business codes via registerErrorCodes. Codes stay
138
+ * stable while sentences (reason) change; the catalog's errorCodes dictionary and per-command errors derive
139
+ * from here. A refusal carrying an unregistered code still stands (no double refusal) — only an audit trace is left.
140
+ */
141
+ export function registerErrorCodes(codes: Record<string, ErrorCodeDefinition>): void {
142
+ assertOpenFor(defaultKernelState, 'registerErrorCodes')
143
+ for (const [code, def] of Object.entries(codes)) {
144
+ if (defaultKernelState.errorCodes.has(code)) throw new Error(`Error code registered twice: ${code}`)
145
+ defaultKernelState.errorCodes.set(code, frozenCopyOf({ ...def }))
146
+ }
147
+ }
148
+
149
+ export const errorCodeOf = (code: string): ErrorCodeDefinition | undefined => defaultKernelState.errorCodes.get(code)
150
+
151
+ /** The full registered error-code dictionary — published by the catalog (REST·MCP, same source).
152
+ * A fresh outer record of the frozen definitions */
153
+ export const allErrorCodes = (): Record<string, ErrorCodeDefinition> =>
154
+ Object.fromEntries([...defaultKernelState.errorCodes.entries()])
155
+
156
+ /**
157
+ * Catalog consistency check — called after app assembly to find contradictions between
158
+ * transition tables (descriptions) and commands (execution permissions). A table's roles are
159
+ * catalog-exposed descriptions, so they must not claim more than allowedRoles; registration order
160
+ * cannot know command order, so everything is cross-checked here at once.
161
+ * An empty array means consistent — the list of contradictions is returned so the assembly layer can fail the boot.
162
+ */
163
+ export function catalogConsistencyErrors(): string[] {
164
+ const s = defaultKernelState
165
+ const errors: string[] = []
166
+ for (const [machine, rules] of s.machines) {
167
+ for (const rule of rules) {
168
+ const def = s.commands.get(rule.command)
169
+ if (!def) {
170
+ errors.push(`Transition table references an unregistered command: ${machine} → '${rule.command}'`)
171
+ continue
172
+ }
173
+ if (def.transition && (def.transition.machine !== machine || def.transition.command !== rule.command))
174
+ errors.push(
175
+ `Transition table and command transition declaration disagree: ${machine}/${rule.command} ↔ ${def.name}'s ${def.transition.machine}/${def.transition.command}`,
176
+ )
177
+ const overstated = rule.roles.filter((r) => !def.allowedRoles.includes(r))
178
+ if (overstated.length)
179
+ errors.push(
180
+ `Transition table roles exceed execution permissions: ${machine}/${rule.command} — roles beyond execution permission [${overstated.join(', ')}] (execution permission: [${def.allowedRoles.join('/')}])`,
181
+ )
182
+ }
183
+ }
184
+ // Command self-containment checks — so the catalog never lies to agents (description·example·scope pairing)
185
+ for (const def of s.commands.values()) {
186
+ if (!def.description || def.description.trim().length === 0)
187
+ errors.push(`Command description is empty: ${def.name} — the baseline of a self-describing catalog`)
188
+ if (!def.example)
189
+ errors.push(`Missing usage example: ${def.name} — the catalog carries a real call`)
190
+ if (def.scope !== 'none' && typeof def.targetOf !== 'function')
191
+ errors.push(`Command with scope '${def.scope}' has no targetOf: ${def.name} — delegation·policy checks cannot find the target`)
192
+ // Declared business error codes must exist in the registry — otherwise the catalog promises something it does not have
193
+ for (const code of def.errors ?? [])
194
+ if (!s.errorCodes.has(code)) errors.push(`Command declares an unregistered error code: ${def.name} → '${code}'`)
195
+ // A command declaring a transition must have at least one of its own rules in that machine — otherwise stage 7 always refuses
196
+ if (!def.transition) continue
197
+ const rules = s.machines.get(def.transition.machine)
198
+ if (!rules)
199
+ errors.push(`Command references an unregistered transition machine: ${def.name} → '${def.transition.machine}'`)
200
+ else if (!rules.some((r) => r.command === def.transition!.command))
201
+ errors.push(`Transition machine has no rule for this command: ${def.name} → '${def.transition.machine}' (stage 7 always refuses)`)
202
+ }
203
+ // Scoped commands need the app policy — authorize·delegationCovers are invoked for them, so an assembly
204
+ // registering them without a policy promises scope protection it cannot deliver. Scope-free apps (every
205
+ // command scope:'none') legitimately assemble with no policy.
206
+ if (!s.policy) {
207
+ const scoped = [...s.commands.values()].filter((d) => d.scope !== 'none').map((d) => d.name)
208
+ if (scoped.length > 0)
209
+ errors.push(`Commands with a scope require a registered app policy (registerAppPolicy): [${scoped.join(', ')}]`)
210
+ }
211
+ return errors
212
+ }
213
+
214
+ /** Completes an unsealed assembly — every execution entry point (executeCommand·executeBatch·executeQuery)
215
+ * and the explicit seal (sealRegistries) come through here: the catalog consistency check runs, then the
216
+ * registries seal. Contradictions are an assembly defect — a process-level error, not a refusal — so they
217
+ * surface at boot no matter which path fires first. Sealing without the check exists only as this
218
+ * function's internal last step (sealFor); there is no public unchecked seal. Both entry paths are
219
+ * idempotent. */
220
+ export function completeAssembly(): void {
221
+ if (defaultKernelState.sealed) return
222
+ const errors = catalogConsistencyErrors()
223
+ if (errors.length > 0)
224
+ throw new Error(`Catalog inconsistencies — assembly defect, execution refused: ${errors.join(' / ')}`)
225
+ sealFor(defaultKernelState)
226
+ }
227
+
228
+ /** Seals the kernel — the explicit seal runs the SAME catalog consistency check as the first execution:
229
+ * a contradictory assembly fails here as a process error, a consistent one seals. Idempotent — calling on
230
+ * an already-sealed kernel is a no-op. (Delegates to completeAssembly — the check-then-seal logic lives in
231
+ * exactly one place; there is no public path that seals without the check. Lives beside completeAssembly,
232
+ * not in state.ts, so the state module stays a value-free bottom of the module graph.) */
233
+ export function sealRegistries(): void {
234
+ completeAssembly()
235
+ }
package/src/state.ts ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Kernel state — every registration site (commands·roles·transitions·event contracts·error codes·
3
+ * policy·projector·protocol·queries·storage·seal·gate context) keeps its records in one process-wide
4
+ * bundle. The module-level API ('@sudoke/kernel': registerCommand, executeCommand, db, …) operates on
5
+ * this bundle; there is exactly one kernel per process.
6
+ *
7
+ * Bottom module: this file imports no other kernel module as a value (import type only) — everything
8
+ * above (registries·gate·auth·…) may depend on the state, the state depends on nothing. Keep it that
9
+ * way: a value import from here would create a load-order cycle whose TDZ failures depend on the
10
+ * entry path.
11
+ *
12
+ * Registration is a boot-time act: the bundle is sealed after assembly completes (explicitly via
13
+ * sealRegistries — registry.ts, or automatically at the first execution — completeAssembly), and every
14
+ * register* path across the kernel refuses late registration (assertOpenFor).
15
+ *
16
+ * Tests: node --test already isolates test files as separate processes. Within one file,
17
+ * resetKernelForTests() starts a fresh bundle in place (the object reference is kept — the `db` proxy
18
+ * and other long-lived bindings stay valid).
19
+ */
20
+ import type { ZodTypeAny } from 'zod'
21
+ import type { AppPolicy } from './policy.js'
22
+ import type { ProjectionHandler } from './projections.js'
23
+ import type { QueryDefinition } from './queries.js'
24
+ import type { TransitionRule } from './registry.js'
25
+ import type { StoragePort } from './storage.js'
26
+ import type { CommandDefinition, ErrorCodeDefinition } from './types.js'
27
+
28
+ /** Registered projector — the app contract (AppProjector) collected into handler maps */
29
+ export interface RegisteredProjector {
30
+ initTables: string[]
31
+ preservedTables: Array<{ table: string; reason: string }>
32
+ handlers: Map<string, ProjectionHandler>
33
+ }
34
+
35
+ export interface KernelState {
36
+ commands: Map<string, CommandDefinition<any, any>>
37
+ roles: Set<string>
38
+ machines: Map<string, readonly TransitionRule[]>
39
+ eventContracts: Map<string, ZodTypeAny>
40
+ errorCodes: Map<string, ErrorCodeDefinition>
41
+ policy: AppPolicy | null
42
+ projector: RegisteredProjector | null
43
+ protocolLines: readonly string[] | null
44
+ queries: Map<string, QueryDefinition>
45
+ storage: StoragePort | null
46
+ sealed: boolean
47
+ }
48
+
49
+ /** Kernel-common error codes — refusals the 9-stage gate and the query entry raise themselves. Seeded into
50
+ * the state at creation; the domain registers its business codes beside them (registerErrorCodes). */
51
+ const KERNEL_COMMON_ERROR_CODES: Record<string, ErrorCodeDefinition> = {
52
+ 'gate.unknown_command': { description: 'Call to an unregistered command (stage 0 registry)', recovery: 'stop' },
53
+ 'auth.token_invalid': { description: 'Missing or invalid token (expired/revoked) — re-login or reissue the token (stage 1 identify)', recovery: 'reauthenticate' },
54
+ 'auth.login_failed': { description: 'Login credential mismatch or malformed request — fix the input and retry', recovery: 'fix_input' },
55
+ 'gate.delegation_denied': { description: "Command outside the delegation token's scope (stage 2 delegation)", recovery: 'stop' },
56
+ 'gate.role_denied': { description: 'Role not allowed (stage 3 policy)', recovery: 'stop' },
57
+ 'policy.denied': { description: 'App-policy scope refusal — e.g. target outside the assigned scope (stage 3 policy)', recovery: 'stop' },
58
+ 'policy.unregistered': { description: 'App policy not registered — assembly defect (stage 3 policy)', recovery: 'stop' },
59
+ 'auth.relogin_required': { description: 'Identity invalid at execution time (e.g. deactivated) — re-login required (stage 3)', recovery: 'reauthenticate' },
60
+ 'gate.schema_invalid': { description: 'Input violates the command schema (stage 4 schema)', recovery: 'fix_input' },
61
+ 'gate.option_not_supported': { description: 'Protocol option (requestKey·dryRun) in an unsupported place — batch items carry no options; batch-level dryRun is not supported (dry-run each command individually)', recovery: 'fix_input' },
62
+ 'gate.idempotency_key_conflict': { description: 'Different input reusing the same requestKey (stage 6 invariants)', recovery: 'fix_input' },
63
+ 'gate.transition_denied': { description: 'Illegal transition from the current status (stage 7 transitions)', recovery: 'refresh' },
64
+ 'gate.transition_unregistered': { description: 'Reference to an unregistered transition table — assembly defect (stage 7)', recovery: 'stop' },
65
+ 'gate.event_contract_violation': { description: 'Event violates its format contract — assembly defect (stage 8 execute)', recovery: 'stop' },
66
+ 'gate.output_contract_violation': { description: 'Command result violates its output contract — assembly defect (stage 8 execute)', recovery: 'stop' },
67
+ 'gate.execution_failed': { description: 'Unclassified execution error (stage 8 execute)', recovery: 'stop' },
68
+ 'gate.precondition_error': { description: 'Unclassified precondition error — the domain should throw GateError with a registered code (stage 5)', recovery: 'stop' },
69
+ 'gate.invariant_error': { description: 'Unclassified invariant error — the domain should throw GateError with a registered code (stage 6)', recovery: 'stop' },
70
+ 'query.unknown': { description: 'Call to an unregistered query', recovery: 'stop' },
71
+ 'query.params_invalid': { description: 'Query params violate the query contract', recovery: 'fix_input' },
72
+ 'query.execution_failed': { description: 'Query handler error (often transient — safe to retry)', recovery: 'retry' },
73
+ }
74
+
75
+ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
76
+ typeof v === 'object' && v !== null && !Array.isArray(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null)
77
+
78
+ /** The registry's copy-and-freeze: deep-copies every plain object·array, keeps everything else by
79
+ * reference (functions, class instances — zod schemas —, primitives), then freezes the copy. Two
80
+ * guarantees in one pass: (1) the registrant's own object is never touched — no hidden freeze side
81
+ * effect on the caller, later mutations of theirs never reach the registry; (2) what the registry
82
+ * stores and returns shares no plain object with anyone, and ESM strict mode turns any tamper into an
83
+ * immediate TypeError instead of a silent no-op. */
84
+ export function frozenCopyOf<T>(v: T): T {
85
+ if (Array.isArray(v)) return Object.freeze(v.map(frozenCopyOf)) as T
86
+ if (isPlainObject(v)) {
87
+ const out: Record<string, unknown> = {}
88
+ for (const [k, val] of Object.entries(v)) out[k] = frozenCopyOf(val)
89
+ return Object.freeze(out) as T
90
+ }
91
+ return v
92
+ }
93
+
94
+ export function freshKernelState(): KernelState {
95
+ return {
96
+ commands: new Map(),
97
+ roles: new Set(),
98
+ machines: new Map(),
99
+ eventContracts: new Map(),
100
+ // seeded frozen, same discipline as registerErrorCodes — every definition leaves the registry frozen
101
+ errorCodes: new Map<string, ErrorCodeDefinition>(
102
+ Object.entries(KERNEL_COMMON_ERROR_CODES).map(([code, def]) => [code, frozenCopyOf(def)]),
103
+ ),
104
+ policy: null,
105
+ projector: null,
106
+ protocolLines: null,
107
+ queries: new Map(),
108
+ storage: null,
109
+ sealed: false,
110
+ }
111
+ }
112
+
113
+ /** The process kernel state — every module-level function operates on it */
114
+ export const defaultKernelState: KernelState = freshKernelState()
115
+
116
+ /** Test-only — resets the process kernel state in place (same object reference, so long-lived bindings
117
+ * like the `db` proxy stay valid). Production code never calls this; isolation between test files is
118
+ * already provided by node --test running each file as its own process. */
119
+ export function resetKernelForTests(): void {
120
+ Object.assign(defaultKernelState, freshKernelState())
121
+ }
122
+
123
+ /** Seals the state — called after assembly and the consistency check. Late registration is a defect */
124
+ export function sealFor(s: KernelState): void {
125
+ s.sealed = true
126
+ }
127
+
128
+ export const registriesSealed = (): boolean => defaultKernelState.sealed
129
+
130
+ /** Guard used at the top of every register* function across the kernel */
131
+ export function assertOpenFor(s: KernelState, what: string): void {
132
+ if (s.sealed)
133
+ throw new Error(`Registries are sealed — ${what} after assembly is a defect (contracts must not change during execution)`)
134
+ }
package/src/storage.ts ADDED
@@ -0,0 +1,208 @@
1
+ import type { DomainEvent } from './types.js'
2
+ import { assertOpenFor, defaultKernelState } from './state.js'
3
+
4
+ /**
5
+ * Physical storage port — the kernel states the capabilities it requires; a separate physical
6
+ * package (default: @sudoke/infra-sqlite) implements and registers them at assembly time.
7
+ * The kernel itself imports no storage engine, no filesystem, no secret store.
8
+ *
9
+ * The port is asynchronous (Promise-returning). Node's client libraries for networked engines
10
+ * (Postgres and the like) are async-only, while an async port can also wrap a synchronous engine
11
+ * (SQLite calls resolve immediately) — the reverse is impossible, so async is the one contract
12
+ * every engine fits. Which engine serves the port stays the physical layer's choice.
13
+ *
14
+ * Required capabilities (the contract behind this port — swapping the implementation must uphold all of them):
15
+ * 1. Write-lock transactions — `immediate` takes the write lock up front, before the first read, by an
16
+ * engine-appropriate means (SQLite: BEGIN IMMEDIATE + busy wait; Postgres: a transaction-dedicated
17
+ * connection + an advisory transaction lock). A deferred read→write upgrade fails under overlap with
18
+ * another process's commit, which would break concurrent-retry settlement; lock waits are absorbed
19
+ * by the adapter. Overlapping `immediate` closures must never observe each other's uncommitted
20
+ * state — the adapter serializes them (in-process queue or DB-level lock, as the engine requires).
21
+ * The same lane covers EVERY writer: replay (`rebuild`) and out-of-transaction audit appends serialize
22
+ * with command writes too, so ledger sequences become visible in commit order — a consumer advancing
23
+ * a sequence cursor can never skip a record that commits later with a lower sequence. Locking and
24
+ * connection routing are the physical layer's internal concern; engine-specific means stay out of
25
+ * the kernel's execution code.
26
+ * 2. Durable ordered append — event rows are monotonically sequenced and written inside the caller's
27
+ * transaction, so execution, projection and recording commit or vanish together.
28
+ * 3. Idempotency uniqueness — one stored result per (subjectId, act, command, requestKey); a duplicate
29
+ * insert surfaces as a constraint error inside the caller's transaction (settled as a concurrent retry).
30
+ *
31
+ * The port also exposes the raw SQL dialect (`sql`) for the app's projections and queries — those are
32
+ * app-owned content written in the dialect of the registered physical layer, which is why the handle
33
+ * passes through here rather than the kernel speaking SQL itself.
34
+ */
35
+
36
+ /** Minimal statement surface the app's projections·queries rely on (prepare/exec dialect handle).
37
+ * Statements resolve rather than return rows directly, so networked engines sit behind the same handle */
38
+ export interface SqlStatement {
39
+ get(...args: unknown[]): Promise<unknown>
40
+ all(...args: unknown[]): Promise<unknown[]>
41
+ run(...args: unknown[]): Promise<unknown>
42
+ }
43
+ export interface SqlDialect {
44
+ prepare(sql: string): SqlStatement
45
+ exec(sql: string): Promise<void>
46
+ }
47
+
48
+ /** User status values — a closed set. The name 'deprecated' is kept for stored-data compatibility.
49
+ * Auth judgments are fail-closed: any value other than 'active' counts as inactive (an unknown status
50
+ * must never widen permissions — see login·loadIdentity·currentIdentityOf in auth.ts). */
51
+ export const USER_STATUS_ACTIVE = 'active' as const
52
+ export const USER_STATUS_DEPRECATED = 'deprecated' as const
53
+ export type UserStatus = typeof USER_STATUS_ACTIVE | typeof USER_STATUS_DEPRECATED
54
+
55
+ export interface StoredUser {
56
+ id: string
57
+ email: string
58
+ name: string
59
+ role: string
60
+ password: string
61
+ status: UserStatus
62
+ }
63
+ export interface StoredDelegation {
64
+ id: string
65
+ subject_id: string
66
+ name: string
67
+ scopes: string /* JSON array: '*' | 'commandName' | 'commandName:target' */
68
+ issued_at: string
69
+ expires_at: string
70
+ revoked_at: string | null
71
+ }
72
+ export interface LedgerRow {
73
+ seq: number
74
+ ts: string
75
+ /** 'domain' (event) | 'audit' */
76
+ kind: string
77
+ type: string
78
+ aggregate_type: string | null
79
+ aggregate_id: string | null
80
+ payload: string
81
+ }
82
+ export interface IdempotencyHit {
83
+ inputHash: string
84
+ resultJson: string
85
+ }
86
+
87
+ export interface StoragePort {
88
+ /** SQL dialect handle for app-owned projections and queries (business reads/writes against read tables) */
89
+ sql: SqlDialect
90
+ /** Signing secret for long-lived tokens — provisioned by the app (deployment premise), stored by the physical layer */
91
+ jwtSecret(): Uint8Array
92
+
93
+ /** Physical append of a domain event (format validation stays kernel-side in appendEvent) — returns the sequence */
94
+ appendDomainRow(e: DomainEvent, ts: string): Promise<number>
95
+ appendAuditRow(payloadJson: string): Promise<void>
96
+ /** Every domain event row in sequence order (replay source) */
97
+ domainRows(): Promise<LedgerRow[]>
98
+ /** Ledger page read — rows strictly after `after`, up to `limit`, in ascending (true) or descending (false)
99
+ * sequence order, domain and audit rows alike. Feeds the kernel's sanctioned ledger read path (readLedger) */
100
+ ledgerRows(after: number, limit: number, ascending: boolean): Promise<LedgerRow[]>
101
+ /** Latest payload of a domain event strictly before a sequence (restore/undo snapshots) */
102
+ latestDomainPayloadBefore(type: string, aggregateId: string, beforeSeq: number): Promise<string | undefined>
103
+
104
+ userByEmail(email: string): Promise<StoredUser | undefined>
105
+ userById(id: string): Promise<StoredUser | undefined>
106
+ delegationById(id: string): Promise<StoredDelegation | undefined>
107
+ insertUser(u: StoredUser): Promise<void>
108
+
109
+ findIdempotency(subjectId: string, act: string, command: string, requestKey: string): Promise<IdempotencyHit | undefined>
110
+ insertIdempotency(row: {
111
+ subjectId: string
112
+ act: string
113
+ command: string
114
+ requestKey: string
115
+ inputHash: string
116
+ resultJson: string
117
+ createdAt: string
118
+ }): Promise<void>
119
+
120
+ /** Write-lock transaction (capability 1) — the kernel's execution·record·idempotency atomicity unit */
121
+ immediate<T>(fn: () => Promise<T>): Promise<T>
122
+ /** Replay transaction — clears the given derived tables, runs the replay, commits atomically */
123
+ rebuild<T>(clearTables: readonly string[], fn: () => Promise<T>): Promise<T>
124
+ /** Release the physical connection (optional) — file removal, e.g. test cleanup, requires it on platforms that lock open files */
125
+ close?(): void
126
+ }
127
+
128
+ /** Register the physical layer — the assembly layer (or a physical package factory like sqliteStorage) calls it before anything else */
129
+ export function registerStorage(p: StoragePort): void {
130
+ assertOpenFor(defaultKernelState, 'registerStorage')
131
+ defaultKernelState.storage = p
132
+ }
133
+
134
+ export function storageOf(): StoragePort {
135
+ const s = defaultKernelState.storage
136
+ if (!s)
137
+ throw new Error(
138
+ 'No physical storage registered — call the physical package factory (e.g. sqliteStorage) in the assembly layer before anything else',
139
+ )
140
+ return s
141
+ }
142
+
143
+ /** App-facing SQL handle — the dialect of the registered physical layer.
144
+ * Lazy by design: imports stay side-effect-free, resolution happens at first use (assembly registers first). */
145
+ export const db: SqlDialect = new Proxy({} as SqlDialect, {
146
+ get: (_target, prop) => {
147
+ const sql = storageOf().sql as unknown as Record<string | symbol, unknown>
148
+ const value = sql[prop]
149
+ return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(sql) : value
150
+ },
151
+ })
152
+
153
+ /**
154
+ * Gate-execution context and ledger appends: the kernel publishes NO ledger-append API. Domain events and
155
+ * audit rows reach the physical ledger only through the gate's execution path (gate.ts internal functions)
156
+ * — a direct write anywhere else would bypass the 9-stage gate. Writing kernel tables directly through
157
+ * `db` is a rule violation the structure does not prevent (the SQL dialect handle is app-owned surface);
158
+ * what the kernel can guarantee, it guarantees by not exposing the append path at all.
159
+ */
160
+
161
+ /** Secret-field rule — the one place deciding which keys never leave the system in readable records.
162
+ * Audit input masking (gate.ts) and the ledger read path (readLedger) share this function, so the two
163
+ * can never drift apart. The rule itself (password-like key names) is deliberately unchanged. */
164
+ export function maskSecrets<T>(v: T): T {
165
+ if (Array.isArray(v)) return v.map(maskSecrets) as unknown as T
166
+ if (v && typeof v === 'object') {
167
+ const out: Record<string, unknown> = {}
168
+ for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
169
+ if (/pass(word)?/i.test(k)) continue
170
+ out[k] = maskSecrets(val)
171
+ }
172
+ return out as T
173
+ }
174
+ return v
175
+ }
176
+
177
+ /** One ledger row as the kernel read path returns it — payload parsed and masked (secret fields removed) */
178
+ export interface LedgerReadRow {
179
+ seq: number
180
+ ts: string
181
+ kind: string
182
+ type: string
183
+ aggregate_type: string | null
184
+ aggregate_id: string | null
185
+ payload: unknown
186
+ }
187
+
188
+ /** Ledger payloads are kernel-written JSON; a non-JSON payload (hand-edited row) passes through raw rather than failing the read */
189
+ const parsePayload = (raw: string): unknown => {
190
+ try {
191
+ return JSON.parse(raw)
192
+ } catch {
193
+ return raw
194
+ }
195
+ }
196
+
197
+ /**
198
+ * The kernel's ledger read path — the sanctioned way to show the ledger (event log + audit trail) to the
199
+ * outside: payloads are parsed and passed through the same secret-field rule as audit input masking, so
200
+ * password-like fields never leave through this route, domain and audit rows alike. When a surface exposes
201
+ * the ledger, it reads through this function.
202
+ * Which rows a given caller may see (row-range filtering, role limits) is business interpretation and stays
203
+ * with the caller — the kernel does not decide it.
204
+ */
205
+ export async function readLedger(opts: { after?: number; limit?: number; ascending?: boolean } = {}): Promise<LedgerReadRow[]> {
206
+ const rows = await storageOf().ledgerRows(opts.after ?? 0, opts.limit ?? 50, opts.ascending ?? true)
207
+ return rows.map((r) => ({ ...r, payload: maskSecrets(parsePayload(r.payload)) }))
208
+ }