@sudoke/kernel 0.3.1 → 0.5.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/src/gate.ts CHANGED
@@ -1,70 +1,52 @@
1
- import { ZodError } from 'zod'
2
- import { createHmac } from 'node:crypto'
3
- import { currentIdentityOf } from './auth.js'
4
- import { maskSecrets, storageOf } from './storage.js'
5
- import { appPolicy } from './policy.js'
6
- import { applyDomainEvent } from './projections.js'
7
- import { completeAssembly, errorCodeOf, eventContractOf, lookupCommand, transitionRulesOf } from './registry.js'
8
- import { delegationScopeEntries, roleAllowsCommand } from './visibility.js'
9
- import type { PolicyRefusal } from './policy.js'
10
- import { GateError, type CommandDefinition, type DomainEvent, type Identity, type RecoveryHint } from './types.js'
11
-
12
1
  /**
13
- * Decision-time table (2026-10-22 time-axis audit) — which read each gate judgment is based on.
14
- * Any change to this table is committed together with the affected time-point cases in smoke·policy-test.
2
+ * The write kernel (gatekeeper) — the single path every write passes through.
3
+ * 1 identify 2 delegation 3 policy 4 schema (static) 5 preconditions 6 invariants 7 transitions (dynamic, just before execution) 8 execute 9 audit.
4
+ * Refusals are first-class results: the stage and reason remain as audit events — early refusals such as
5
+ * unregistered commands are no exception. Common options: requestKey (idempotent replay — decided before business
6
+ * checks), dryRun (validation only).
15
7
  *
16
- * - 1 identify (token→identity) : re-read from the DB on every request (loadIdentity — role changes·deactivation apply immediately)
17
- * - 2 delegation scope : request (static) + just before execution (reauthorize) — revocation·expiry are also blocked at execution time
18
- * - 3 role·business scope : request (static) + just before execution (reauthorize) — business interpretation of scope belongs to the app policy
19
- * - 4 schema : once per request (state-independent; must also pass before replay)
20
- * - 5 preconditions·6 invariants·7 transitions : just before execution, inside the transaction
21
- * (an earlier command's changes in a batch are reflected)
22
- * - 8~9 execute·audit : inside the transaction — events·projections·idempotency·audit commit/roll back together
23
- * - idempotent replay (requestKey) : right after the static (1~4) checks, immediately. It is a 'redelivery' of an already-committed
24
- * result, so execution-time rechecks are skipped by design (re-checking only adds false negatives;
25
- * there is no new result). Re-enabling rechecks is a deliberate policy change.
26
- * Each redelivery still leaves exactly one 'replay' audit row (I8 — every attempt is recorded).
27
- * - idempotency SELECT→INSERT : split outside/inside the transaction — on conflict, roll back, re-read, and return the stored result (settleConcurrentRetry)
28
- * - command·transition·contract registration : once at boot (catalogConsistencyErrors checks for contradictions) — immutable during
29
- * execution; the registries are sealed after assembly, so late registration fails
8
+ * This module holds the ENTRY POINTS and the check sequence (checks·replay·transaction·execution
9
+ * order reads here); the machinery lives in dedicated internal modules: gate-results (the refusal
10
+ * vocabulary), gate-audit (audit recording and the single refusal exit), idempotency (stored
11
+ * results and settlement), execution-core (the in-transaction command pipeline), permissions
12
+ * (the shared permission judgments).
30
13
  */
31
- /** Success shape — the result·events of execution, with the replayed/dry-run markers */
32
- export interface ExecutionSuccess {
33
- ok: true
34
- result?: unknown
35
- events?: string[]
36
- /** dryRun:true request — passed validation (1~7) but execution (8) was skipped */
37
- dryRun?: boolean
38
- /** Same requestKey resent — the stored result was returned as-is */
39
- replayed?: boolean
40
- /** Batch execution — per-command results */
41
- results?: unknown[]
42
- }
43
-
44
- /** Refusal shape — a first-class result; the code·recovery contract is always machine-usable */
45
- export interface ExecutionRefusal {
46
- ok: false
47
- stage: number
48
- stageName: string
49
- reason: string
50
- /** Stable error code — stays stable even as the sentence (reason) changes. An identifier of the registry (errorCodes) */
51
- code?: string
52
- /** Next-step guidance — an action classification (refresh·fix_input·reauthenticate·retry·stop) plus an optional query */
53
- recovery?: RecoveryHint
54
- /** Marks a warning refusal that can be overridden with a force:true retry */
55
- canForce?: boolean
56
- /** Which command (index) failed in a batch */
57
- index?: number
58
- }
59
-
60
- /** One attempt's outcome — success and refusal are the two shapes every surface distinguishes by ok */
61
- export type ExecutionResult = ExecutionSuccess | ExecutionRefusal
14
+ import { ZodError } from 'zod'
15
+ import { randomUUID } from 'node:crypto'
16
+ import { storageOf } from './storage.js'
17
+ import { appPolicy } from './policy.js'
18
+ import { completeAssembly, lookupCommand, transitionRulesOf } from './registry.js'
19
+ import { commandRevisionOf, PROTOCOL_VERSION, responseMetaOf } from './catalog.js'
20
+ import { roleAllowsCommand } from './visibility.js'
21
+ import { GateError, type CommandDefinition, type ContractMeta, type Identity } from './types.js'
22
+ import { canonicalJson } from './canonical.js'
23
+ import {
24
+ assertLiveRoleAllows,
25
+ assertRecordedDelegationCovers,
26
+ delegationAllowsRecorded,
27
+ judgedIdentityOf,
28
+ liveIdentityOf,
29
+ policyRefusalGateError,
30
+ unprovableRefusal,
31
+ } from './permissions.js'
32
+ import { toGateError } from './gate-results.js'
33
+ import type { ExecutionResult, ExecutionRefusal, ExecutionSuccess } from './gate-results.js'
34
+ import { auditSettled, refuse, tryRecordOutsideTx } from './gate-audit.js'
35
+ import { batchProducerOf, producerOf, replayOrReject, settleConcurrentRetry, storeIdempotency } from './idempotency.js'
36
+ import { runCommand, type OperationContext } from './execution-core.js'
37
+
38
+ /** Contract metadata on every success response — the CURRENT revisions, distinguished from the result
39
+ * itself: a replayed result was produced by an older contract, and the meta says what is true now. */
40
+ export type { ContractResponseMeta } from './types.js'
41
+ export type { ExecutionSuccess, ExecutionRefusal, ExecutionResult } from './gate-results.js'
62
42
 
63
43
  /**
64
44
  * Delegation scope check — the acting radius of an agent token.
65
45
  * Scope syntax (kernel contract): '*' | 'commandName' | 'commandName:target' — what a target refers to is defined by the app policy.
66
46
  * Target restrictions reflect only 'entries attached to this command' — so target ranges of other commands never mix in (G-05).
67
47
  */
48
+ /** The delegation verdict on RECORDED material (a removed command's redelivery): same entry
49
+ * selection and same target logic as the live check below — one predicate, no drift. */
68
50
  async function delegationAllows(
69
51
  del: NonNullable<Identity['delegation']>,
70
52
  commandName: string,
@@ -72,225 +54,50 @@ async function delegationAllows(
72
54
  input: unknown,
73
55
  ): Promise<boolean> {
74
56
  // Entry selection is shared with the catalog visibility derivation (visibility.ts) — one predicate, no drift
75
- const entries = delegationScopeEntries(del.scopes, commandName)
76
- if (entries.length === 0) return false
77
- if (entries.some((sc) => !sc.includes(':'))) return true
78
57
  const targetId = def.scope !== 'none' ? def.targetOf?.(input as any) : undefined
79
- if (!targetId) return false
80
- const targets = entries.map((sc) => sc.slice(sc.indexOf(':') + 1))
81
- return await appPolicy().delegationCovers(targetId, targets)
58
+ return delegationAllowsRecorded(del, commandName, def.scope, targetId)
82
59
  }
83
60
 
84
- /** Common protocol options (requestKey·dryRun) ride beside the business input but are not part of it — stripped
85
- * before the schema so even a .strict() business schema never sees them, and excluded from permission targets
86
- * and the idempotency hash (the same business request hashes identically however the options were spelled). */
87
- function splitProtocolOptions(raw: unknown): { requestKey?: string; dryRun: boolean; body: unknown } {
88
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { dryRun: false, body: raw }
89
- const { requestKey, dryRun, ...body } = raw as Record<string, unknown>
61
+ /** Common protocol options (requestKey·dryRun·contract) ride beside the business input but are not part
62
+ * of it — stripped before the schema so even a .strict() business schema never sees them, and excluded
63
+ * from permission targets (the same business request hashes identically however the options were spelled).
64
+ * The idempotency hash DOES include the contract identity when one was sent: a resend under the same key
65
+ * must carry the same contract — a new contract on a stored key is an input conflict, never a replay. */
66
+ function splitProtocolOptions(raw: unknown): {
67
+ requestKey?: string
68
+ dryRun: boolean
69
+ contract?: ContractMeta
70
+ /** the contract field was present but malformed — refused as contract_required, never silently ignored */
71
+ contractMalformed: boolean
72
+ body: unknown
73
+ } {
74
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { dryRun: false, contractMalformed: false, body: raw }
75
+ const { requestKey, dryRun, contract, ...body } = raw as Record<string, unknown>
76
+ const wellFormed =
77
+ !!contract &&
78
+ typeof contract === 'object' &&
79
+ typeof (contract as Record<string, unknown>).commandVersion === 'string' &&
80
+ typeof (contract as Record<string, unknown>).commandRevision === 'string' &&
81
+ typeof (contract as Record<string, unknown>).protocolVersion === 'string'
90
82
  return {
91
83
  requestKey: typeof requestKey === 'string' && requestKey.length > 0 ? requestKey.slice(0, 100) : undefined,
92
84
  dryRun: dryRun === true,
85
+ ...(wellFormed ? { contract: contract as ContractMeta } : {}),
86
+ contractMalformed: contract !== undefined && !wellFormed,
93
87
  body,
94
88
  }
95
89
  }
96
90
 
97
- /** Common fallback codes for unclassified dynamic-stage errors — a refusal without a code breaks the
98
- * machine-usable contract, so every refusal carries one (the domain-declared code remains the good path) */
99
- const STAGE_FALLBACK_CODES: Record<number, string> = {
100
- 5: 'gate.precondition_error',
101
- 6: 'gate.invariant_error',
102
- 8: 'gate.execution_failed',
103
- }
104
-
105
- const toGateError = (err: unknown, stage: number, stageName: string) => {
106
- if (err instanceof GateError) {
107
- if (err.code || !STAGE_FALLBACK_CODES[stage]) return err
108
- // a GateError constructed without a code still breaks the machine-usable contract — stamp the stage's fallback
109
- return new GateError(err.stage, err.stageName, err.message, { code: STAGE_FALLBACK_CODES[stage], recovery: err.recovery })
110
- }
111
- return new GateError(stage, stageName, err instanceof Error ? err.message : String(err), {
112
- code: STAGE_FALLBACK_CODES[stage],
113
- })
114
- }
115
-
116
- /** Assembles the machine-usable contract of a refusal — merges the error-code definition (recovery action·force-ability)
117
- * with throw-site hints (query). An unregistered code is still carried; recovery·canForce stay empty (the audit leaves an unregistered trace). */
118
- function refusalMeta(err: GateError): Pick<ExecutionRefusal, 'code' | 'recovery' | 'canForce'> {
119
- const def = err.code ? errorCodeOf(err.code) : undefined
120
- const action = err.recovery?.action ?? def?.recovery
121
- const query = err.recovery?.query
122
- const recovery: RecoveryHint | undefined = action || query ? { ...(action ? { action } : {}), ...(query ? { query } : {}) } : undefined
123
- return {
124
- ...(err.code ? { code: err.code } : {}),
125
- ...(recovery ? { recovery } : {}),
126
- ...(def?.canForce ? { canForce: true } : {}),
127
- }
128
- }
129
-
130
- /** Audit subject — for human access act/del are blanks; for agent access the acting subject is recorded */
131
- const auditSubjectOf = (identity: Identity) => ({
132
- userId: identity.userId,
133
- name: identity.name,
134
- role: identity.role,
135
- act: identity.act ?? null,
136
- del: identity.delegation?.id ?? null,
137
- })
138
-
139
- /** Ledger append (domain event) — gate-internal only, never exported: there is no public API for writing
140
- * the ledger, so events reach it only through command execution. The format contract is checked here:
141
- * unregistered types and violations are never written (exception → stage-8 refusal·rollback). Replay
142
- * (reads) skips validation for past-format compatibility — the contract is the source of truth for what
143
- * is written *now*. */
144
- async function appendEvent(e: DomainEvent): Promise<{ seq: number; ts: string }> {
145
- const contract = eventContractOf(e.type)
146
- if (!contract)
147
- throw new GateError(8, 'execute', `No event contract registered for type: ${e.type} — register it with registerEventContracts`, {
148
- code: 'gate.event_contract_violation',
149
- })
150
- const checked = contract.safeParse(e.payload)
151
- if (!checked.success)
152
- throw new GateError(
153
- 8,
154
- 'execute',
155
- `Event violates its format contract: ${e.type} — ${checked.error.issues
156
- .map((i) => `${i.path.join('.')}: ${i.message}`)
157
- .join('; ')}`,
158
- { code: 'gate.event_contract_violation' },
159
- )
160
- // ts is fixed once so storage and projection use the same value — the recorded time, not the replay time, stays in business data
161
- const ts = new Date().toISOString()
162
- const seq = await storageOf().appendDomainRow(e, ts)
163
- return { seq, ts }
164
- }
165
-
166
- /** Audit append — gate-internal only, never exported: the audit trail records gate attempts and nothing else */
167
- async function appendAudit(payload: Record<string, unknown>): Promise<void> {
168
- await storageOf().appendAuditRow(JSON.stringify(payload))
169
- }
170
-
171
- /** Audit record assembly — one place for the common ok·dry-run·refused·replay shape (subject·input masking
172
- * via the shared secret-field rule maskSecrets included). Refusals also carry the error code·recovery·force-ability
173
- * — an unregistered code leaves a trace (no double refusal). */
174
- async function recordAudit(
175
- command: string,
176
- identity: Identity,
177
- result: 'ok' | 'dry-run' | 'refused' | 'replay',
178
- rawInput: unknown,
179
- refusal?: GateError,
180
- ): Promise<void> {
181
- await appendAudit({
182
- command,
183
- subject: auditSubjectOf(identity),
184
- result,
185
- input: maskSecrets(rawInput),
186
- ...(refusal
187
- ? {
188
- stage: refusal.stage,
189
- stageName: refusal.stageName,
190
- reason: refusal.message,
191
- ...refusalMeta(refusal),
192
- ...(refusal.code && !errorCodeOf(refusal.code) ? { codeUnregistered: true } : {}),
193
- }
194
- : {}),
195
- })
196
- }
197
-
198
- /** Out-of-transaction audit write (refusal·replay·dry-run) — the one guarded helper. The caller's result
199
- * always wins over the recording: on failure (disk·lock) a single stderr JSON line carries the diagnosis —
200
- * a stable code, the audit kind, the command, the stage, a limited error classification; never the raw
201
- * input, never the error text (messages may embed input values). stdout is never touched (MCP stdio owns it).
202
- * The success audit is NOT routed here: it lives inside the business transaction, where a failed insert
203
- * rolls the command back (stage-8 refusal — I8's split guarantee). */
204
- async function tryRecordOutsideTx(
205
- kind: 'refused' | 'replay' | 'dry-run',
206
- command: string,
207
- identity: Identity,
208
- rawInput: unknown,
209
- refusal?: GateError,
210
- ): Promise<void> {
211
- try {
212
- await recordAudit(command, identity, kind, rawInput, refusal)
213
- } catch (err) {
214
- console.error(
215
- JSON.stringify({
216
- code: 'audit.write_failed',
217
- auditKind: kind,
218
- command,
219
- ...(refusal ? { stage: refusal.stage } : {}),
220
- errorClass: err instanceof Error ? err.constructor.name : typeof err,
221
- ts: new Date().toISOString(),
222
- }),
223
- )
224
- }
225
- }
226
-
227
- /** Concurrent-retry settlement audit — a settled replay is a redelivery (kind 'replay'), a settled key
228
- * conflict is a refusal; both are attempts under I8 and never pass silently. */
229
- async function auditSettled(command: string, identity: Identity, rawInput: unknown, settled: ExecutionResult): Promise<void> {
230
- if (settled.ok) {
231
- await tryRecordOutsideTx('replay', command, identity, rawInput)
232
- return
233
- }
234
- await tryRecordOutsideTx(
235
- 'refused',
236
- command,
237
- identity,
238
- rawInput,
239
- new GateError(settled.stage ?? 8, settled.stageName ?? 'execute', settled.reason ?? 'settled refusal', {
240
- ...(settled.code ? { code: settled.code } : {}),
241
- ...(settled.recovery ? { recovery: settled.recovery } : {}),
242
- }),
243
- )
244
- }
245
-
246
- /** Refusal assembly — the single exit every refusal passes through: the attempt is recorded (the
247
- * out-of-transaction helper — masked input, code·recovery carried) and the canonical ExecutionRefusal is
248
- * built in one place. A batch prefix states which item failed in the audited sentence; index marks it in
249
- * the response. Routing every refusal through here is what makes 'a refusal without its audit' structurally
250
- * impossible rather than a matter of discipline at ~10 call sites. */
251
- async function refuse(
252
- command: string,
253
- identity: Identity,
254
- rawInput: unknown,
255
- err: GateError,
256
- opts: { index?: number; prefix?: string } = {},
257
- ): Promise<ExecutionRefusal> {
258
- const marked = opts.prefix ? withPrefix(err, opts.prefix) : err
259
- await tryRecordOutsideTx('refused', command, identity, rawInput, marked)
260
- return {
261
- ok: false,
262
- ...(opts.index === undefined ? {} : { index: opts.index }),
263
- stage: marked.stage,
264
- stageName: marked.stageName,
265
- reason: marked.message,
266
- ...refusalMeta(marked),
267
- }
268
- }
269
-
270
- /** Copies a refusal with a reason prefix — audit and response carry the same sentence stating which batch item failed.
271
- * The error code·recovery hints are copied too (the machine-usable contract survives the prefix). */
272
- const withPrefix = (refusal: GateError, prefix: string) =>
273
- prefix
274
- ? new GateError(refusal.stage, refusal.stageName, `${prefix}${refusal.message}`, { code: refusal.code, recovery: refusal.recovery })
275
- : refusal
276
-
277
- /** Wraps an app-policy scope refusal into a GateError — a plain string gets the kernel common code (policy.denied);
278
- * an object carries the app-declared code·recovery action as-is (error codes are never inferred from sentences). */
279
- const policyRefusalOf = (refusal: string | PolicyRefusal, prefix = '') => {
280
- const reason = `${prefix}${typeof refusal === 'string' ? refusal : refusal.reason}`
281
- return typeof refusal === 'string'
282
- ? new GateError(3, 'policy', reason, { code: 'policy.denied' })
283
- : new GateError(3, 'policy', reason, {
284
- code: refusal.code,
285
- ...(refusal.recovery ? { recovery: { action: refusal.recovery } } : {}),
286
- })
287
- }
91
+ /** The value the idempotency hash covers — the business input plus the contract identity when sent.
92
+ * canonicalJson sorts keys, so option spelling and field order never change the hash. */
93
+ const hashBodyOf = (body: unknown, contract?: ContractMeta): unknown => (contract ? { contract, body } : body)
288
94
 
289
95
  /**
290
96
  * Static checks — once per request, independent of state changes, and must pass before replay of retries.
291
97
  * Of stages 1~4 this function checks 2~4 (delegation·policy·schema) — stage 1 identify happens in the server layer before entry.
98
+ * Exported for undo.ts — a compensation passes the identical checks (no bypass lane).
292
99
  */
293
- async function validateStatic(def: CommandDefinition<any>, name: string, rawInput: unknown, identity: Identity): Promise<any> {
100
+ export async function validateStatic(def: CommandDefinition<any>, name: string, rawInput: unknown, identity: Identity): Promise<any> {
294
101
  // 4 schema is parsed first so permission decisions (2~3) read the *normalized* input — targetOf promises the
295
102
  // parsed shape, and normalization (trim·default·transform) must not split what policy approved from what runs.
296
103
  // Stage precedence is unchanged: a parse failure is held back and surfaces as stage 4 only after 2~3 passed
@@ -321,7 +128,7 @@ async function validateStatic(def: CommandDefinition<any>, name: string, rawInpu
321
128
  })
322
129
  if (def.scope !== 'none') {
323
130
  const refusal = await appPolicy().authorize(identity, def.scope, def.targetOf?.(authInput as any))
324
- if (refusal) throw policyRefusalOf(refusal)
131
+ if (refusal) throw policyRefusalGateError(refusal, '', { carryRecovery: true })
325
132
  }
326
133
 
327
134
  // 4 schema — the held-back parse failure (ZodError → contract refusal; anything else propagates as-is)
@@ -341,18 +148,16 @@ async function validateStatic(def: CommandDefinition<any>, name: string, rawInpu
341
148
  * scope state (e.g. an assignment) is also caught here. The users·delegations tables are kernel-owned so current values
342
149
  * can be re-read; business interpretation of scope still belongs to the app policy. targetOf sees the schema-parsed
343
150
  * input — the same normalized value the static checks and execution act on. Returns the current identity for execution·audit.
151
+ * Exported for undo.ts — the compensation re-authorizes identically.
344
152
  */
345
- async function reauthorize(def: CommandDefinition<any>, name: string, input: any, identity: Identity): Promise<Identity> {
346
- const current = await currentIdentityOf(identity)
347
- if (!current) {
153
+ export async function reauthorize(def: CommandDefinition<any>, name: string, input: any, identity: Identity): Promise<Identity> {
154
+ const current = await liveIdentityOf(identity, () => {
348
155
  if (identity.delegation)
349
156
  throw new GateError(2, 'delegation', 'Delegation is invalid at execution time — revoked, expired, not owned by this account, or the delegating account is inactive', {
350
157
  code: 'gate.delegation_denied',
351
158
  })
352
- throw new GateError(3, 'policy', 'User is inactive at execution time — log in again', {
353
- code: 'auth.relogin_required',
354
- })
355
- }
159
+ throw new GateError(3, 'policy', 'User is inactive at execution time — log in again', { code: 'auth.relogin_required' })
160
+ })
356
161
  // 2 delegation — re-decides with the scopes of the currently valid delegation
357
162
  if (current.delegation && !(await delegationAllows(current.delegation, name, def, input)))
358
163
  throw new GateError(2, 'delegation', `Delegation recheck failed at execution time — this token's scopes: ${current.delegation.scopes.join(', ')}`, {
@@ -361,14 +166,11 @@ async function reauthorize(def: CommandDefinition<any>, name: string, input: any
361
166
  // 3 role·scope — the assignment scope (scopes) used for the decision is also recalculated with current values
362
167
  // (an assignment revoked after the request applies immediately). Calculated only for scoped commands — pulling in
363
168
  // unscoped commands would entangle the minimal policy-free assembly test. Role predicate shared with visibility.ts
364
- if (!roleAllowsCommand(def, current.role))
365
- throw new GateError(3, 'policy', `Role recheck failed at execution time — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`, {
366
- code: 'gate.role_denied',
367
- })
169
+ assertLiveRoleAllows(def, current.role, `Role recheck failed at execution time — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`)
368
170
  if (def.scope !== 'none') {
369
- const nowScopes: Identity = { ...current, scopes: await appPolicy().scopesFor(current.role, current.userId) }
171
+ const nowScopes = await judgedIdentityOf(current)
370
172
  const refusal = await appPolicy().authorize(nowScopes, def.scope, def.targetOf?.(input as any))
371
- if (refusal) throw policyRefusalOf(refusal, 'Scope recheck failed at execution time — ')
173
+ if (refusal) throw policyRefusalGateError(refusal, 'Scope recheck failed at execution time — ', { carryRecovery: true })
372
174
  }
373
175
  return current
374
176
  }
@@ -376,8 +178,9 @@ async function reauthorize(def: CommandDefinition<any>, name: string, input: any
376
178
  /**
377
179
  * Dynamic checks (5~7) — depend on current state, so they run just before execution.
378
180
  * In a batch, when an earlier command changes state, later commands are re-checked against the changed state (bank-balance analogy).
181
+ * Exported for undo.ts — the compensation runs them inside the same transaction.
379
182
  */
380
- async function validateDynamic(def: CommandDefinition<any>, input: any, identity: Identity): Promise<void> {
183
+ export async function validateDynamic(def: CommandDefinition<any>, input: any, identity: Identity): Promise<void> {
381
184
  // 5 preconditions
382
185
  try {
383
186
  await def.precondition?.(input)
@@ -409,106 +212,72 @@ async function validateDynamic(def: CommandDefinition<any>, input: any, identity
409
212
  }
410
213
  }
411
214
 
412
- /** Command execution (event append + projection apply + audit) — always called inside a transaction */
413
- async function runCommand(def: CommandDefinition<any>, name: string, input: any, rawInput: unknown, identity: Identity) {
414
- const { events, result } = await def.execute(input, identity)
415
- // Output contract — the result shape is checked before commit (the same place as the event contract).
416
- // A violation is a stage-8 refusal with a full rollback.
417
- const checked = def.output.safeParse(result)
418
- if (!checked.success)
215
+ /** Permission precheck without schema parsing — the replay-first path uses it where the resent
216
+ * input may no longer parse under the current schema. Role needs no input; delegation target extraction
217
+ * reads the raw body (a plain field read in practice). The app-policy scope check (parsed-input
218
+ * dependent) is not repeated for a redelivery — there is no new effect to authorize. */
219
+ export async function quickPermissionCheck(def: CommandDefinition<any>, name: string, input: unknown, identity: Identity): Promise<void> {
220
+ if (!roleAllowsCommand(def, identity.role))
221
+ throw new GateError(3, 'policy', `Only roles [${def.allowedRoles.join('/')}] may run this command (current role: ${identity.role})`, {
222
+ code: 'gate.role_denied',
223
+ })
224
+ if (identity.delegation && !(await delegationAllows(identity.delegation, name, def, input)))
419
225
  throw new GateError(
420
- 8,
421
- 'execute',
422
- `Command output violates its contract: ${name} — ${checked.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`,
423
- { code: 'gate.output_contract_violation' },
226
+ 2,
227
+ 'delegation',
228
+ `Out of delegation scope — this token's scopes: ${identity.delegation.scopes.join(', ')}`,
229
+ { code: 'gate.delegation_denied' },
424
230
  )
425
- const eventTypes: string[] = []
426
- for (const e of events) {
427
- // The recording timestamp is fixed once so storage and projection use the same value — replay and live produce the same state
428
- const { seq, ts } = await appendEvent(e)
429
- await applyDomainEvent(e, { seq, ts })
430
- eventTypes.push(e.type)
431
- }
432
- // The success audit is part of the business transaction — a failed insert propagates and rolls the whole
433
- // command back (stage-8 refusal). It is never routed through the out-of-transaction helper.
434
- await recordAudit(name, identity, 'ok', rawInput)
435
- return { result, eventTypes }
436
231
  }
437
232
 
438
- /** Idempotency lookup — retries are decided before business checks (structure 2) */
439
- function findIdempotency(identity: Identity, command: string, requestKey: string) {
440
- return storageOf().findIdempotency(identity.userId, identity.act ?? '', command, requestKey)
441
- }
442
-
443
- /** Idempotency decision — the current hash form only: the stored hash must equal the input's hash, byte
444
- * for byte. A row whose stored hash is not in the current form (written by an older algorithm, or with an
445
- * empty hash) never matches — the resend is refused as a key conflict (fail safe) instead of risking a
446
- * replay of a different request. The replayed result is exempt from the current output contract — the
447
- * contract is the source of truth for what is written *now* (the same principle as event replay). */
448
- function storedResultOf(hit: { inputHash: string; resultJson: string }, requestKey: string, body: unknown): ExecutionResult {
449
- if (hit.inputHash !== inputHashOf(body))
450
- throw new GateError(6, 'invariant', `A different request was sent with the same requestKey ('${requestKey}') — use a new key`, {
451
- code: 'gate.idempotency_key_conflict',
452
- })
453
- const stored = JSON.parse(hit.resultJson)
454
- return { ok: true, result: stored.result, events: stored.events, replayed: true }
455
- }
456
-
457
- /** Canonical JSON — object keys sorted at every depth, so the same business request hashes identically no matter
458
- * the field order (agents rebuild JSON on retries; only array order is meaningfully part of a request). */
459
- function canonicalJson(v: unknown): string {
460
- if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`
461
- if (v && typeof v === 'object') {
462
- const entries = Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
463
- return `{${entries.map(([k, val]) => `${JSON.stringify(k)}:${canonicalJson(val)}`).join(',')}}`
464
- }
465
- return JSON.stringify(v) ?? 'null'
466
- }
467
-
468
- /** Idempotency input hash — a keyed digest (version-prefixed) of the canonicalized business input (protocol
469
- * options stripped, keys sorted). A bare SHA-256 would leave offline-verifiable password material in the
470
- * idempotency table whenever a request carries one — the same premise under which audit input is masked (G-01).
471
- * The JWT secret keys it, with a domain-separation prefix so the same key never signs two meanings. */
472
- const inputHashOf = (body: unknown) =>
473
- 'h2:' + createHmac('sha256', storageOf().jwtSecret()).update('idempotency-input\0' + canonicalJson(body)).digest('hex')
474
-
475
- async function replayOrReject(identity: Identity, command: string, requestKey: string, body: unknown): Promise<ExecutionResult | null> {
476
- const hit = await findIdempotency(identity, command, requestKey)
477
- if (!hit) return null
478
- return storedResultOf(hit, requestKey, body)
233
+ /** The contract check — the write is refused before execution when the caller's contract view is
234
+ * stale. The revision match is exact: within one MAJOR, description·warning·behavior changes must be
235
+ * re-confirmed too. Only THIS command's revision matters — other commands changing never refuses here
236
+ * (their revisions did not move). */
237
+ export function checkContract(def: CommandDefinition<any>, contract: ContractMeta | undefined, malformed: boolean): void {
238
+ if (malformed || !contract)
239
+ throw new GateError(
240
+ 4,
241
+ 'schema',
242
+ 'This kernel requires the command contract — send contract:{commandVersion,commandRevision,protocolVersion} beside the business input (read them from the catalog)',
243
+ { code: 'gate.contract_required' },
244
+ )
245
+ const diffs: string[] = []
246
+ if (contract.commandVersion !== (def.version ?? ''))
247
+ diffs.push(`commandVersion ${contract.commandVersion} → ${def.version ?? '(undeclared)'}`)
248
+ if (contract.commandRevision !== (commandRevisionOf(def.name) ?? '')) diffs.push('commandRevision changed')
249
+ if (contract.protocolVersion !== PROTOCOL_VERSION) diffs.push(`protocolVersion ${contract.protocolVersion} → ${PROTOCOL_VERSION}`)
250
+ if (diffs.length > 0)
251
+ throw new GateError(
252
+ 4,
253
+ 'schema',
254
+ `The command contract changed since this request was built (${diffs.join(', ')}) — read the catalog status and what changed, re-learn the fields, then resend with the current contract`,
255
+ { code: 'gate.contract_changed', recovery: { action: 'refresh' } },
256
+ )
479
257
  }
480
258
 
481
- /**
482
- * Concurrent-retry settlement — after rolling back on a lock or duplicate-key conflict during execution,
483
- * if another process already committed with the same key, the stored result is returned (no double apply).
484
- * A different input keeps the existing rule (same key·different input refused); if the recheck itself fails,
485
- * null is returned so the caller proceeds with the original error.
486
- */
487
- async function settleConcurrentRetry(identity: Identity, command: string, requestKey: string, body: unknown): Promise<ExecutionResult | null> {
488
- try {
489
- const hit = await findIdempotency(identity, command, requestKey)
490
- if (!hit) return null
259
+ /** Re-proves each item's recorded rights for a stored batch result — the replay probe and the
260
+ * concurrent-retry settlement share this (a batch redelivery is a fresh READ of every item). Returns
261
+ * the refusal response, or null when the whole batch is still provable. */
262
+ async function batchRightsRefusal(items: { name: string }[], identity: Identity, producedBy: unknown): Promise<ExecutionResult | null> {
263
+ const perItem = (producedBy as { items?: unknown[] } | undefined)?.items
264
+ if (!Array.isArray(perItem) || perItem.length !== items.length)
265
+ return await refuse(
266
+ 'batch',
267
+ identity,
268
+ items,
269
+ new GateError(3, 'policy', 'The stored batch predates per-item rights tracking — the rights cannot be re-proven, so the result is refused', {
270
+ code: 'policy.denied',
271
+ }),
272
+ )
273
+ for (let i = 0; i < items.length; i++) {
491
274
  try {
492
- return storedResultOf(hit, requestKey, body)
275
+ await assertReplayRights(String((perItem[i] as { commandName?: string })?.commandName ?? items[i]?.name), identity, perItem[i])
493
276
  } catch (err) {
494
- const refusal = toGateError(err, 6, 'invariant')
495
- return { ok: false, stage: refusal.stage, stageName: refusal.stageName, reason: refusal.message, ...refusalMeta(refusal) }
277
+ return await refuse('batch', identity, items, toGateError(err, 3, 'policy'), { index: i, prefix: `#${i} ${items[i]?.name ?? ''}: ` })
496
278
  }
497
- } catch {
498
- return null // recheck failed (lock etc.) — the original error is reported as-is
499
279
  }
500
- }
501
-
502
- async function storeIdempotency(identity: Identity, command: string, requestKey: string, body: unknown, result: unknown, events: string[]) {
503
- await storageOf().insertIdempotency({
504
- subjectId: identity.userId,
505
- act: identity.act ?? '',
506
- command,
507
- requestKey,
508
- inputHash: inputHashOf(body),
509
- resultJson: JSON.stringify({ result, events }),
510
- createdAt: new Date().toISOString(),
511
- })
280
+ return null
512
281
  }
513
282
 
514
283
  /**
@@ -523,22 +292,132 @@ export async function executeCommand(name: string, rawInput: unknown, identity:
523
292
  return executeCommandInner(name, rawInput, identity)
524
293
  }
525
294
 
295
+ /** A redelivery is a fresh READ of a stored outcome — the RECORDED producer material decides whether
296
+ * the current identity may still see it. One rule shared by every replay site (removed commands,
297
+ * still-registered commands, undo compensations, batch items): the recorded role must still match,
298
+ * the rights material must exist (its absence is unprovable — a row predating rights tracking —
299
+ * never a read of "no restriction"), the current delegation must still cover the recorded
300
+ * command×target, and scoped commands are re-authorized by the CURRENT app policy against the
301
+ * recorded normalized target. Throws a stage-3 GateError on refusal. */
302
+ export async function verifyReplayRights(name: string, current: Identity, producedBy: unknown): Promise<void> {
303
+ // the assignment scopes (business targets) are RE-COMPUTED for the verdict — currentIdentityOf
304
+ // preserves the request-start scopes, but a redelivery is judged like any fresh read: an assignment
305
+ // revoked mid-request must refuse the replay exactly as it refuses a new request (the same refresh
306
+ // reauthorize applies before execution)
307
+ const judged = await judgedIdentityOf(current)
308
+ const by = producedBy as { role?: string; rights?: { scope: string; target?: string } } | { unknown: true } | undefined
309
+ if (!by || !('role' in by) || by.role !== current.role)
310
+ throw new GateError(
311
+ 3,
312
+ 'policy',
313
+ `The stored result was produced under a different role (current: '${current.role}') — a redelivery is returned only while the recorded rights still match`,
314
+ { code: 'gate.role_denied' },
315
+ )
316
+ const rights = 'rights' in (by ?? {}) ? (by as { rights?: { scope: string; target?: string } }).rights : undefined
317
+ if (!rights)
318
+ throw unprovableRefusal('The stored result predates rights tracking — the right cannot be re-proven, so the result is refused')
319
+ // a still-valid delegation may have been NARROWED: the current command×target range is judged on
320
+ // the recorded material (delegation validity itself was re-read by the caller via currentIdentityOf)
321
+ if (current.delegation) await assertRecordedDelegationCovers(current.delegation, name, rights.scope, rights.target, 3)
322
+ // scoped commands: the CURRENT app policy judges the recorded normalized target with CURRENT scopes
323
+ if (rights.scope !== 'none') {
324
+ if (rights.target === undefined)
325
+ throw unprovableRefusal('The stored result carries no recorded target — the right cannot be re-proven, so the result is refused')
326
+ const refusal = await appPolicy().authorize(judged, rights.scope, rights.target)
327
+ // a replay verdict keeps the ERROR-CODE default guidance — the policy's momentary recovery hint
328
+ // never travels with a stored result's re-proof (review F1)
329
+ if (refusal) throw policyRefusalGateError(refusal)
330
+ }
331
+ }
332
+
333
+ /** Replay-site guard — re-reads the live identity (inactive accounts never receive stored results),
334
+ * then re-proves the recorded rights. Callers already holding the current identity may call
335
+ * verifyReplayRights directly. */
336
+ async function assertReplayRights(name: string, identity: Identity, producedBy: unknown): Promise<void> {
337
+ const current = await liveIdentityOf(identity, () =>
338
+ new GateError(3, 'policy', 'User is inactive at replay time — stored results are not returned to inactive accounts', { code: 'auth.relogin_required' }))
339
+ // a STILL-REGISTERED command's LIVE role grant: the account role may be unchanged while the
340
+ // definition narrowed its allowedRoles since — a redelivery respects the CURRENT permission set
341
+ // (a removed command has no live definition; its recorded material remains the only basis)
342
+ const def = lookupCommand(name)
343
+ if (def)
344
+ assertLiveRoleAllows(def, current.role, `Role no longer allowed for this command — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`)
345
+ await verifyReplayRights(name, current, producedBy)
346
+ }
347
+
348
+ /** Replay probe for a command the registry no longer knows — a resend for a removed command:
349
+ * when the stored provenance (same subject, same requestKey, same hashed request) says this caller
350
+ * already succeeded, the stored result MAY be returned. The account must be valid NOW, and the
351
+ * rights must still be provable (verifyReplayRights). Null when nothing is stored for this
352
+ * caller·key·request. */
353
+ export async function replayStoredCommand(identity: Identity, name: string, rawInput: unknown): Promise<ExecutionResult | null> {
354
+ const current = await liveIdentityOf(identity, () =>
355
+ new GateError(3, 'policy', 'User is inactive at replay time — stored results are not returned to inactive accounts', { code: 'auth.relogin_required' }))
356
+ if (!rawInput || typeof rawInput !== 'object' || Array.isArray(rawInput)) return null
357
+ const { requestKey, dryRun, contract, body } = splitProtocolOptions(rawInput)
358
+ if (!requestKey || dryRun) return null
359
+ const replayed = await replayOrReject(identity, name, requestKey, hashBodyOf(body, contract))
360
+ if (replayed?.ok) await verifyReplayRights(name, current, replayed.producedBy)
361
+ return replayed
362
+ }
363
+
526
364
  async function executeCommandInner(name: string, rawInput: unknown, identity: Identity): Promise<ExecutionResult> {
527
365
  const def = lookupCommand(name)
528
- if (!def)
366
+ if (!def) {
367
+ {
368
+ try {
369
+ const replayed = await replayStoredCommand(identity, name, rawInput)
370
+ if (replayed) {
371
+ if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
372
+ await tryRecordOutsideTx('replay', name, identity, rawInput)
373
+ return replayed.ok ? { ...replayed, meta: responseMetaOf(undefined, identity) } : replayed
374
+ }
375
+ } catch (err) {
376
+ return await refuse(name, identity, rawInput, toGateError(err, 3, 'policy'))
377
+ }
378
+ }
529
379
  return await refuse(name, identity, rawInput, new GateError(0, 'registry', `Unknown command: ${name}`, { code: 'gate.unknown_command' }))
380
+ }
530
381
 
531
- const { requestKey, dryRun, body } = splitProtocolOptions(rawInput)
382
+ const { requestKey, dryRun, contract, contractMalformed, body } = splitProtocolOptions(rawInput)
383
+ const hashValue = hashBodyOf(body, contract)
532
384
  try {
385
+ // the replay probe precedes the schema·contract checks: a stored success is returned even
386
+ // when today's schema or contract would refuse the resent input (the result already exists;
387
+ // re-validating it against today's contract adds false negatives, never safety). The stored row is
388
+ // found FIRST — judging the resent raw input through TODAY'S targetOf would refuse legitimate
389
+ // redeliveries whose input field names moved (the recorded rights material is the verdict, never a
390
+ // re-extraction from the past input). A HIT is a fresh READ: the recorded rights are re-proven
391
+ // (role·delegation·policy target·current scopes), so a redelivery never widens permissions. A MISS
392
+ // is a NEW request — the current definition judges everything from here.
393
+ if (requestKey && !dryRun && contract) {
394
+ const replayed = await replayOrReject(identity, name, requestKey, hashValue)
395
+ if (replayed) {
396
+ if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
397
+ await tryRecordOutsideTx('replay', name, identity, rawInput)
398
+ return replayed.ok ? { ...replayed, meta: responseMetaOf(name, identity) } : replayed
399
+ }
400
+ await quickPermissionCheck(def, name, body, identity)
401
+ }
402
+
403
+ // the contract the call was built against must be declared and current BEFORE the business
404
+ // schema judges the input: a caller working from a stale contract is told to re-learn the contract,
405
+ // not lectured on schema details of fields they have never seen
406
+ checkContract(def, contract, contractMalformed)
407
+
533
408
  const input = await validateStatic(def, name, body, identity)
534
409
 
535
410
  // Idempotent replay — a resend of the same request that passed connection·permissions·format (1~4) returns the stored result.
536
411
  // Decided before business checks so a state-changed retry (e.g. version conflict) never overwrites the original success.
537
412
  if (requestKey && !dryRun) {
538
- const replayed = await replayOrReject(identity, name, requestKey, body)
413
+ const replayed = await replayOrReject(identity, name, requestKey, hashValue)
539
414
  if (replayed) {
415
+ // the FIRST probe missed and a concurrent request may have stored this key while the static
416
+ // checks were awaiting — a hit HERE is still a redelivery: the current rights are re-proved
417
+ // exactly as on the first probe (review F1)
418
+ if (replayed.ok) await assertReplayRights(name, identity, replayed.producedBy)
540
419
  await tryRecordOutsideTx('replay', name, identity, rawInput)
541
- return replayed
420
+ return replayed.ok ? { ...replayed, meta: responseMetaOf(name, identity) } : replayed
542
421
  }
543
422
  }
544
423
 
@@ -555,29 +434,38 @@ async function executeCommandInner(name: string, rawInput: unknown, identity: Id
555
434
  // 8~9 execution + audit — permissions (2~3) are re-checked against current state just before execution
556
435
  // (refused when role·delegation·scope changed after the request), and events·projections·idempotency·audit
557
436
  // are handled atomically in one write-lock transaction (the physical layer takes the write lock up front —
558
- // see the capability contract on the storage port).
437
+ // see the capability contract on the storage port). Each execution is one operation: every event it
438
+ // appends carries the operation envelope when the engine supports it.
559
439
  let out: { result: unknown; eventTypes: string[] }
560
440
  try {
561
441
  out = await storageOf().immediate(async () => {
562
442
  const current = await reauthorize(def, name, input, identity)
563
443
  await validateDynamic(def, input, current)
564
- const r = await runCommand(def, name, input, rawInput, current)
565
- if (requestKey) await storeIdempotency(identity, name, requestKey, body, r.result, r.eventTypes)
444
+ const op: OperationContext = {
445
+ operationId: 'op_' + randomUUID(),
446
+ commandName: name,
447
+ ...(def.version ? { commandVersion: def.version } : {}),
448
+ ...(commandRevisionOf(name) ? { commandRevision: commandRevisionOf(name)! } : {}),
449
+ }
450
+ const r = await runCommand(def, name, input, rawInput, current, op)
451
+ if (requestKey) await storeIdempotency(identity, name, requestKey, hashValue, r.result, r.eventTypes, producerOf(name, def, current.role, input))
566
452
  return r
567
453
  })
568
454
  } catch (err) {
569
455
  // concurrent retry — if another process committed first with the same key, the stored result is returned
570
456
  if (requestKey) {
571
- const settled = await settleConcurrentRetry(identity, name, requestKey, body)
457
+ const settled = await settleConcurrentRetry(identity, name, requestKey, hashValue)
572
458
  if (settled) {
459
+ // a settled success is a redelivery too — the recorded rights are re-proved
460
+ if (settled.ok) await assertReplayRights(name, identity, (settled as { producedBy?: unknown }).producedBy)
573
461
  await auditSettled(name, identity, rawInput, settled)
574
- return settled
462
+ return settled.ok ? { ...settled, meta: responseMetaOf(name, identity) } : settled
575
463
  }
576
464
  }
577
465
  throw toGateError(err, 8, 'execute')
578
466
  }
579
467
 
580
- return { ok: true, result: out.result, events: out.eventTypes }
468
+ return { ok: true, result: out.result, events: out.eventTypes, meta: responseMetaOf(name, identity) }
581
469
  } catch (err) {
582
470
  // A failure here includes a failed success-audit insert — the transaction already rolled the command back
583
471
  return await refuse(name, identity, rawInput, toGateError(err, 8, 'execute'))
@@ -624,6 +512,43 @@ async function executeBatchInner(
624
512
  if (!Array.isArray(items) || items.length === 0 || items.length > 20)
625
513
  return await refuse('batch', identity, items, new GateError(4, 'schema', 'commands must be an array of 1 to 20 items', { code: 'gate.schema_invalid' }))
626
514
 
515
+ // the batch replay probe precedes the per-item checks, on the same principle as the single
516
+ // command: a stored batch success is returned even when today's item schemas/contracts would refuse.
517
+ // The stored row is found FIRST (today's targetOf never re-extracts targets from resent raw items —
518
+ // the recorded per-item material is the verdict); a HIT re-proves every item's recorded rights,
519
+ // including items whose command has since been removed. A MISS falls through to the current
520
+ // definitions' full checks below.
521
+ if (batchRequestKey) {
522
+ let replayed: ExecutionResult | null = null
523
+ try {
524
+ replayed = await replayOrReject(identity, 'batch', batchRequestKey, items)
525
+ } catch (err) {
526
+ return await refuse('batch', identity, items, toGateError(err, 6, 'invariant'))
527
+ }
528
+ if (replayed) {
529
+ if (replayed.ok) {
530
+ const refused = await batchRightsRefusal(items, identity, (replayed as { producedBy?: unknown }).producedBy)
531
+ if (refused) return refused
532
+ }
533
+ await tryRecordOutsideTx('replay', 'batch', identity, items)
534
+ return replayed.ok ? { ...replayed, meta: responseMetaOf(undefined, identity), results: (replayed.result as any)?.results } : replayed
535
+ }
536
+ // a miss is a NEW batch — still-registered items get the early clear role·delegation refusal
537
+ // (removed commands have no definition; the validation loop below refuses them by index)
538
+ for (let i = 0; i < items.length; i++) {
539
+ const it = items[i] ?? {}
540
+ const def = lookupCommand(it.name)
541
+ if (!def) continue
542
+ const { requestKey: itemKey, dryRun: itemDry, body: itemBody } = splitProtocolOptions(it.input ?? {})
543
+ if (itemKey || itemDry) continue // refused below with the canonical option refusal
544
+ try {
545
+ await quickPermissionCheck(def, it.name, itemBody, identity)
546
+ } catch (err) {
547
+ return await refuse('batch', identity, items, toGateError(err, 3, 'policy'), { index: i, prefix: `#${i} ${it.name}: ` })
548
+ }
549
+ }
550
+ }
551
+
627
552
  const validated: { def: CommandDefinition<any>; name: string; input: any; rawInput: unknown }[] = []
628
553
  for (let i = 0; i < items.length; i++) {
629
554
  const it = items[i] ?? {}
@@ -633,8 +558,10 @@ async function executeBatchInner(
633
558
  index: i,
634
559
  prefix: `#${i} ${it.name}: `,
635
560
  })
636
- // Protocol options are batch-level, not item-level — an item carrying one is a clear refusal, never silent execution
637
- const { requestKey: itemKey, dryRun: itemDry, body: itemBody } = splitProtocolOptions(it.input ?? {})
561
+ // Protocol options are batch-level, not item-level — an item carrying one is a clear refusal, never
562
+ // silent execution. (contract is the exception: every item CARRIES a contract — it is
563
+ // checked per item below; the batch requestKey hash covers the items as sent, contract included.)
564
+ const { requestKey: itemKey, dryRun: itemDry, contract: itemContract, contractMalformed: itemMalformed, body: itemBody } = splitProtocolOptions(it.input ?? {})
638
565
  if (itemKey || itemDry)
639
566
  return await refuse(
640
567
  'batch',
@@ -649,7 +576,12 @@ async function executeBatchInner(
649
576
  { index: i, prefix: `#${i} ${it.name}: ` },
650
577
  )
651
578
  try {
652
- validated.push({ def, name: it.name, input: await validateStatic(def, it.name, itemBody, identity), rawInput: it.input })
579
+ // the caller's contract view is judged before the business schema — the same order as single
580
+ // commands (a stale-contract caller is told to re-learn the contract, not lectured on fields
581
+ // they have never seen)
582
+ checkContract(def, itemContract, itemMalformed)
583
+ const input = await validateStatic(def, it.name, itemBody, identity)
584
+ validated.push({ def, name: it.name, input, rawInput: it.input })
653
585
  } catch (err) {
654
586
  return await refuse('batch', identity, items, toGateError(err, 8, 'execute'), { index: i, prefix: `#${i} ${it.name}: ` })
655
587
  }
@@ -663,33 +595,51 @@ async function executeBatchInner(
663
595
  return await refuse('batch', identity, items, toGateError(err, 6, 'invariant'))
664
596
  }
665
597
  if (replayed) {
598
+ // concurrent batch stored this key while the per-item validation was awaiting — the hit is a
599
+ // redelivery and every item's recorded rights are re-proved, exactly as on the first probe
600
+ if (replayed.ok) {
601
+ const refused = await batchRightsRefusal(items, identity, (replayed as { producedBy?: unknown }).producedBy)
602
+ if (refused) return refused
603
+ }
666
604
  await tryRecordOutsideTx('replay', 'batch', identity, items)
667
- return replayed.ok ? { ...replayed, results: (replayed.result as any)?.results } : replayed
605
+ return replayed.ok
606
+ ? { ...replayed, meta: responseMetaOf(undefined, identity), results: (replayed.result as any)?.results }
607
+ : replayed
668
608
  }
669
609
  }
670
610
 
671
611
  // One write-lock transaction for the whole batch (the BEGIN and lock waits follow the storage port's
672
612
  // capability contract — see the single-command note above). The BEGIN is inside the try, so a lock-wait
673
- // timeout also reaches the common handling below and returns the canonical refusal·audit.
613
+ // timeout also reaches the common handling below and returns the canonical refusal·audit. Every item is
614
+ // its own operation (its own operationId) grouped under one batchId — undo compensates items, not batches.
674
615
  try {
675
616
  const results = await storageOf().immediate(async () => {
676
617
  const rs = []
618
+ const batchId = 'batch_' + randomUUID()
677
619
  for (let i = 0; i < validated.length; i++) {
678
620
  const v = validated[i]
679
621
  try {
680
622
  const current = await reauthorize(v.def, v.name, v.input, identity) // execution-time permissions — earlier command scope changes are caught here
681
623
  await validateDynamic(v.def, v.input, current) // current-state checks just before execution
682
- const r = await runCommand(v.def, v.name, v.input, v.rawInput, current)
624
+ const op: OperationContext = {
625
+ operationId: 'op_' + randomUUID(),
626
+ batchId,
627
+ commandName: v.name,
628
+ ...(v.def.version ? { commandVersion: v.def.version } : {}),
629
+ ...(commandRevisionOf(v.name) ? { commandRevision: commandRevisionOf(v.name)! } : {}),
630
+ }
631
+ const r = await runCommand(v.def, v.name, v.input, v.rawInput, current, op)
683
632
  rs.push({ name: v.name, ok: true, result: r.result, events: r.eventTypes })
684
633
  } catch (err) {
685
634
  ;(err as any).batchIndex = i // carries which command (index) failed into the refusal response
686
635
  throw err
687
636
  }
688
637
  }
689
- if (batchRequestKey) await storeIdempotency(identity, 'batch', batchRequestKey, items, { results: rs }, rs.flatMap((r) => r.events))
638
+ if (batchRequestKey)
639
+ await storeIdempotency(identity, 'batch', batchRequestKey, items, { results: rs }, rs.flatMap((r) => r.events), batchProducerOf(validated, identity.role))
690
640
  return rs
691
641
  })
692
- return { ok: true, results }
642
+ return { ok: true, results, meta: responseMetaOf(undefined, identity) }
693
643
  } catch (err) {
694
644
  // A failure here includes a failed success-audit insert — the transaction already rolled the whole batch back
695
645
  const i = (err as any).batchIndex as number | undefined
@@ -697,9 +647,14 @@ async function executeBatchInner(
697
647
  if (batchRequestKey) {
698
648
  const settled = await settleConcurrentRetry(identity, 'batch', batchRequestKey, items)
699
649
  if (settled) {
650
+ // a settled success is a redelivery too — every item's recorded rights are re-proved
651
+ if (settled.ok) {
652
+ const refused = await batchRightsRefusal(items, identity, (settled as { producedBy?: unknown }).producedBy)
653
+ if (refused) return refused
654
+ }
700
655
  await auditSettled('batch', identity, items, settled)
701
656
  return settled.ok
702
- ? { ...settled, ...(i === undefined ? {} : { index: i }), results: (settled.result as any)?.results }
657
+ ? { ...settled, ...(i === undefined ? {} : { index: i }), meta: responseMetaOf(undefined, identity), results: (settled.result as any)?.results }
703
658
  : { ...settled, ...(i === undefined ? {} : { index: i }) }
704
659
  }
705
660
  }