@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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Audit recording — one assembly for every gate attempt (ok·dry-run·refused·replay), the single
3
+ * refusal exit that makes "a refusal without its audit" structurally impossible, and the guarded
4
+ * out-of-transaction write for attempts that never opened one. The SUCCESS audit is not here: it
5
+ * lives inside the business transaction (execution-core), where a failed insert rolls the command
6
+ * back.
7
+ *
8
+ * Internal module: not exported through index.ts.
9
+ */
10
+ import { maskSecrets, storageOf } from './storage.js'
11
+ import { errorCodeOf } from './registry.js'
12
+ import { refusalMeta, withPrefix } from './gate-results.js'
13
+ import type { ExecutionRefusal, ExecutionResult } from './gate-results.js'
14
+ import { GateError } from './types.js'
15
+ import type { Identity } from './types.js'
16
+
17
+ /** Audit subject — for human access act/del are blanks; for agent access the acting subject is recorded */
18
+ const auditSubjectOf = (identity: Identity) => ({
19
+ userId: identity.userId,
20
+ name: identity.name,
21
+ role: identity.role,
22
+ act: identity.act ?? null,
23
+ del: identity.delegation?.id ?? null,
24
+ })
25
+
26
+ /** Audit append — gate-internal only, never exported: the audit trail records gate attempts and nothing else */
27
+ async function appendAudit(payload: Record<string, unknown>): Promise<void> {
28
+ await storageOf().appendAuditRow(JSON.stringify(payload))
29
+ }
30
+
31
+ /** Audit record assembly — one place for the common ok·dry-run·refused·replay shape (subject·input masking
32
+ * via the shared secret-field rule maskSecrets included). Refusals also carry the error code·recovery·force-ability
33
+ * — an unregistered code leaves a trace (no double refusal). `extra` adds tracked context on success rows
34
+ * (the undo success carries its source operation, one record a side). */
35
+ export async function recordAudit(
36
+ command: string,
37
+ identity: Identity,
38
+ result: 'ok' | 'dry-run' | 'refused' | 'replay',
39
+ rawInput: unknown,
40
+ refusal?: GateError,
41
+ extra?: Record<string, unknown>,
42
+ ): Promise<void> {
43
+ await appendAudit({
44
+ command,
45
+ subject: auditSubjectOf(identity),
46
+ result,
47
+ input: maskSecrets(rawInput),
48
+ ...(extra ?? {}),
49
+ ...(refusal
50
+ ? {
51
+ stage: refusal.stage,
52
+ stageName: refusal.stageName,
53
+ reason: refusal.message,
54
+ ...refusalMeta(refusal),
55
+ ...(refusal.code && !errorCodeOf(refusal.code) ? { codeUnregistered: true } : {}),
56
+ }
57
+ : {}),
58
+ })
59
+ }
60
+
61
+ /** Out-of-transaction audit write (refusal·replay·dry-run) — the one guarded helper. The caller's result
62
+ * always wins over the recording: on failure (disk·lock) a single stderr JSON line carries the diagnosis —
63
+ * a stable code, the audit kind, the command, the stage, a limited error classification; never the raw
64
+ * input, never the error text (messages may embed input values). stdout is never touched (MCP stdio owns it).
65
+ * The success audit is NOT routed here: it lives inside the business transaction, where a failed insert
66
+ * rolls the command back (stage-8 refusal — I8's split guarantee). */
67
+ export async function tryRecordOutsideTx(
68
+ kind: 'refused' | 'replay' | 'dry-run',
69
+ command: string,
70
+ identity: Identity,
71
+ rawInput: unknown,
72
+ refusal?: GateError,
73
+ ): Promise<void> {
74
+ try {
75
+ await recordAudit(command, identity, kind, rawInput, refusal)
76
+ } catch (err) {
77
+ console.error(
78
+ JSON.stringify({
79
+ code: 'audit.write_failed',
80
+ auditKind: kind,
81
+ command,
82
+ ...(refusal ? { stage: refusal.stage } : {}),
83
+ errorClass: err instanceof Error ? err.constructor.name : typeof err,
84
+ ts: new Date().toISOString(),
85
+ }),
86
+ )
87
+ }
88
+ }
89
+
90
+ /** Concurrent-retry settlement audit — a settled replay is a redelivery (kind 'replay'), a settled key
91
+ * conflict is a refusal; both are attempts under I8 and never pass silently. */
92
+ export async function auditSettled(command: string, identity: Identity, rawInput: unknown, settled: ExecutionResult): Promise<void> {
93
+ if (settled.ok) {
94
+ await tryRecordOutsideTx('replay', command, identity, rawInput)
95
+ return
96
+ }
97
+ await tryRecordOutsideTx(
98
+ 'refused',
99
+ command,
100
+ identity,
101
+ rawInput,
102
+ new GateError(settled.stage ?? 8, settled.stageName ?? 'execute', settled.reason ?? 'settled refusal', {
103
+ ...(settled.code ? { code: settled.code } : {}),
104
+ ...(settled.recovery ? { recovery: settled.recovery } : {}),
105
+ }),
106
+ )
107
+ }
108
+
109
+ /** Refusal assembly — the single exit every refusal passes through: the attempt is recorded (the
110
+ * out-of-transaction helper — masked input, code·recovery carried) and the canonical ExecutionRefusal is
111
+ * built in one place. A batch prefix states which item failed in the audited sentence; index marks it in
112
+ * the response. Routing every refusal through here is what makes 'a refusal without its audit' structurally
113
+ * impossible rather than a matter of discipline at ~10 call sites. */
114
+ export async function refuse(
115
+ command: string,
116
+ identity: Identity,
117
+ rawInput: unknown,
118
+ err: GateError,
119
+ opts: { index?: number; prefix?: string } = {},
120
+ ): Promise<ExecutionRefusal> {
121
+ const marked = opts.prefix ? withPrefix(err, opts.prefix) : err
122
+ await tryRecordOutsideTx('refused', command, identity, rawInput, marked)
123
+ return {
124
+ ok: false,
125
+ ...(opts.index === undefined ? {} : { index: opts.index }),
126
+ stage: marked.stage,
127
+ stageName: marked.stageName,
128
+ reason: marked.message,
129
+ ...refusalMeta(marked),
130
+ }
131
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The gate's response vocabulary — the success/refusal result shapes and the error→refusal
3
+ * mapping every gate path speaks. Refusals are first-class results: the code·recovery contract
4
+ * is assembled in exactly one place (refusalMeta), so audit rows and responses can never drift.
5
+ *
6
+ * Internal module: not exported through index.ts (the public gate re-exports the types).
7
+ */
8
+ import { errorCodeOf } from './registry.js'
9
+ import { GateError } from './types.js'
10
+ import type { ContractResponseMeta, RecoveryHint } from './types.js'
11
+
12
+ /** Success shape — the result·events of execution, with the replayed/dry-run markers */
13
+ export interface ExecutionSuccess {
14
+ ok: true
15
+ result?: unknown
16
+ events?: string[]
17
+ /** dryRun:true request — passed validation (1~7) but execution (8) was skipped */
18
+ dryRun?: boolean
19
+ /** Same requestKey resent — the stored result was returned as-is */
20
+ replayed?: boolean
21
+ /** Batch execution — per-command results */
22
+ results?: unknown[]
23
+ /** Current contract revisions — see ContractResponseMeta */
24
+ meta?: ContractResponseMeta
25
+ /** The contract that PRODUCED a replayed result — distinguished from `meta` (what is true now).
26
+ * Old idempotency rows that predate producer tracking answer { unknown: true } */
27
+ producedBy?: { commandName?: string; commandVersion?: string; commandRevision?: string; protocolVersion?: string } | { unknown: true }
28
+ }
29
+
30
+ /** Refusal shape — a first-class result; the code·recovery contract is always machine-usable */
31
+ export interface ExecutionRefusal {
32
+ ok: false
33
+ stage: number
34
+ stageName: string
35
+ reason: string
36
+ /** Stable error code — stays stable even as the sentence (reason) changes. An identifier of the registry (errorCodes) */
37
+ code?: string
38
+ /** Next-step guidance — an action classification (refresh·fix_input·reauthenticate·retry·stop) plus an optional query */
39
+ recovery?: RecoveryHint
40
+ /** Marks a warning refusal that can be overridden with a force:true retry */
41
+ canForce?: boolean
42
+ /** Which command (index) failed in a batch */
43
+ index?: number
44
+ }
45
+
46
+ /** One attempt's outcome — success and refusal are the two shapes every surface distinguishes by ok */
47
+ export type ExecutionResult = ExecutionSuccess | ExecutionRefusal
48
+
49
+ /** Common fallback codes for unclassified dynamic-stage errors — a refusal without a code breaks the
50
+ * machine-usable contract, so every refusal carries one (the domain-declared code remains the good path) */
51
+ const STAGE_FALLBACK_CODES: Record<number, string> = {
52
+ 5: 'gate.precondition_error',
53
+ 6: 'gate.invariant_error',
54
+ 8: 'gate.execution_failed',
55
+ }
56
+
57
+ export const toGateError = (err: unknown, stage: number, stageName: string) => {
58
+ if (err instanceof GateError) {
59
+ if (err.code || !STAGE_FALLBACK_CODES[stage]) return err
60
+ // a GateError constructed without a code still breaks the machine-usable contract — stamp the stage's fallback
61
+ return new GateError(err.stage, err.stageName, err.message, { code: STAGE_FALLBACK_CODES[stage], recovery: err.recovery })
62
+ }
63
+ return new GateError(stage, stageName, err instanceof Error ? err.message : String(err), {
64
+ code: STAGE_FALLBACK_CODES[stage],
65
+ })
66
+ }
67
+
68
+ /** Assembles the machine-usable contract of a refusal — merges the error-code definition (recovery action·force-ability)
69
+ * with throw-site hints (query). An unregistered code is still carried; recovery·canForce stay empty (the audit leaves an unregistered trace). */
70
+ export function refusalMeta(err: GateError): Pick<ExecutionRefusal, 'code' | 'recovery' | 'canForce'> {
71
+ const def = err.code ? errorCodeOf(err.code) : undefined
72
+ const action = err.recovery?.action ?? def?.recovery
73
+ const query = err.recovery?.query
74
+ const recovery: RecoveryHint | undefined = action || query ? { ...(action ? { action } : {}), ...(query ? { query } : {}) } : undefined
75
+ return {
76
+ ...(err.code ? { code: err.code } : {}),
77
+ ...(recovery ? { recovery } : {}),
78
+ ...(def?.canForce ? { canForce: true } : {}),
79
+ }
80
+ }
81
+
82
+ /** Copies a refusal with a reason prefix — audit and response carry the same sentence stating which batch item failed.
83
+ * The error code·recovery hints are copied too (the machine-usable contract survives the prefix). */
84
+ export const withPrefix = (refusal: GateError, prefix: string) =>
85
+ prefix
86
+ ? new GateError(refusal.stage, refusal.stageName, `${prefix}${refusal.message}`, { code: refusal.code, recovery: refusal.recovery })
87
+ : refusal
88
+
89
+ /** The refusal response shape of a GateError (code·recovery·force-ability assembled) — shared by the undo
90
+ * entry points, whose refusals are the same first-class contract */
91
+ export function refusalShapeOf(err: GateError): ExecutionRefusal {
92
+ return { ok: false, stage: err.stage, stageName: err.stageName, reason: err.message, ...refusalMeta(err) }
93
+ }