@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,133 @@
1
+ /**
2
+ * Idempotency — the stored·replayed·settled request results: the keyed input hash (domain-
3
+ * separated, canonicalized), the lookup that decides retries before business checks, the
4
+ * concurrent-retry settlement after a rolled-back execution, the store that persists results with
5
+ * their producer material, and the producer/rights records a later redelivery is re-proved on.
6
+ *
7
+ * Internal module: not exported through index.ts.
8
+ */
9
+ import { createHmac } from 'node:crypto'
10
+ import { storageOf } from './storage.js'
11
+ import { canonicalJson } from './canonical.js'
12
+ import { commandRevisionOf, PROTOCOL_VERSION } from './catalog.js'
13
+ import { refusalMeta, toGateError } from './gate-results.js'
14
+ import type { ExecutionResult } from './gate-results.js'
15
+ import { GateError } from './types.js'
16
+ import type { CommandDefinition, Identity } from './types.js'
17
+
18
+ /** Idempotency lookup — retries are decided before business checks (structure 2) */
19
+ function findIdempotency(identity: Identity, command: string, requestKey: string) {
20
+ return storageOf().findIdempotency(identity.userId, identity.act ?? '', command, requestKey)
21
+ }
22
+
23
+ /** Idempotency decision — the current hash form only: the stored hash must equal the input's hash, byte
24
+ * for byte. A row whose stored hash is not in the current form (written by an older algorithm, or with
25
+ * an empty hash) never matches — the resend is refused as a key conflict (fail safe) instead of risking a
26
+ * replay of a different request. The replayed result is exempt from the current output contract — the
27
+ * contract is the source of truth for what is written *now* (the same principle as event replay). */
28
+ function storedResultOf(hit: { inputHash: string; resultJson: string }, requestKey: string, hashValue: unknown): ExecutionResult {
29
+ if (hit.inputHash !== inputHashOf(hashValue))
30
+ throw new GateError(6, 'invariant', `A different request was sent with the same requestKey ('${requestKey}') — use a new key`, {
31
+ code: 'gate.idempotency_key_conflict',
32
+ })
33
+ const stored = JSON.parse(hit.resultJson)
34
+ // The producer contract travels with the stored result — a replay states BOTH what produced it and
35
+ // (via meta at the response site) what is true now. Rows older than producer tracking say unknown.
36
+ return { ok: true, result: stored.result, events: stored.events, replayed: true, producedBy: stored.producer ?? { unknown: true } }
37
+ }
38
+
39
+ /** Server-keyed digest with domain separation — the idempotency hash and the undo plan hash share the
40
+ * key, never the meaning. Exported for undo.ts. */
41
+ export const keyedDigestOf = (domain: string, value: string): string =>
42
+ createHmac('sha256', storageOf().jwtSecret()).update(domain + '\0' + value).digest('hex')
43
+
44
+ /** Idempotency input hash — a keyed digest (version-prefixed) of the canonicalized business input (protocol
45
+ * options stripped, keys sorted; the contract identity joins when one was sent). A bare SHA-256 would leave
46
+ * offline-verifiable password material in the idempotency table whenever a request carries one — the same
47
+ * premise under which audit input is masked (G-01). The JWT secret keys it, with a domain-separation prefix
48
+ * so the same key never signs two meanings. */
49
+ const inputHashOf = (hashValue: unknown) => 'h2:' + keyedDigestOf('idempotency-input', canonicalJson(hashValue))
50
+
51
+ export async function replayOrReject(identity: Identity, command: string, requestKey: string, hashValue: unknown): Promise<ExecutionResult | null> {
52
+ const hit = await findIdempotency(identity, command, requestKey)
53
+ if (!hit) return null
54
+ return storedResultOf(hit, requestKey, hashValue)
55
+ }
56
+
57
+ /**
58
+ * Concurrent-retry settlement — after rolling back on a lock or duplicate-key conflict during execution,
59
+ * if another process already committed with the same key, the stored result is returned (no double apply).
60
+ * A different input keeps the existing rule (same key·different input refused); if the recheck itself fails,
61
+ * null is returned so the caller proceeds with the original error.
62
+ */
63
+ export async function settleConcurrentRetry(identity: Identity, command: string, requestKey: string, hashValue: unknown): Promise<ExecutionResult | null> {
64
+ try {
65
+ const hit = await findIdempotency(identity, command, requestKey)
66
+ if (!hit) return null
67
+ try {
68
+ return storedResultOf(hit, requestKey, hashValue)
69
+ } catch (err) {
70
+ const refusal = toGateError(err, 6, 'invariant')
71
+ return { ok: false, stage: refusal.stage, stageName: refusal.stageName, reason: refusal.message, ...refusalMeta(refusal) }
72
+ }
73
+ } catch {
74
+ return null // recheck failed (lock etc.) — the original error is reported as-is
75
+ }
76
+ }
77
+
78
+ export async function storeIdempotency(
79
+ identity: Identity,
80
+ command: string,
81
+ requestKey: string,
82
+ hashValue: unknown,
83
+ result: unknown,
84
+ events: string[],
85
+ producer?: { commandName: string; commandVersion?: string; commandRevision?: string; protocolVersion: string; items?: unknown[] },
86
+ ) {
87
+ await storageOf().insertIdempotency({
88
+ subjectId: identity.userId,
89
+ act: identity.act ?? '',
90
+ command,
91
+ requestKey,
92
+ inputHash: inputHashOf(hashValue),
93
+ resultJson: JSON.stringify({ result, events, ...(producer ? { producer } : {}) }),
94
+ createdAt: new Date().toISOString(),
95
+ })
96
+ }
97
+
98
+ /** The producer contract recorded beside a stored result — which command, which versions, which
99
+ * protocol, and the role that executed. The role is the RIGHTS MATERIAL a later redelivery of a
100
+ * REMOVED command is judged on (the definition is gone, so allowedRoles can no longer be consulted):
101
+ * the stored result returns only while the caller's current role still matches what produced it. */
102
+ export function producerOf(
103
+ commandName: string,
104
+ def?: CommandDefinition<any>,
105
+ role?: string,
106
+ input?: unknown,
107
+ ): {
108
+ commandName: string
109
+ commandVersion?: string
110
+ commandRevision?: string
111
+ protocolVersion: string
112
+ role?: string
113
+ /** the rights material a removed command's redelivery is judged on: ALWAYS recorded, including
114
+ * scope:'none' (so a row WITHOUT rights is a row that predates tracking — unprovable, refused,
115
+ * never read as "no restriction") */
116
+ rights?: { scope: string; target?: string }
117
+ } {
118
+ return {
119
+ commandName,
120
+ ...(def?.version ? { commandVersion: def.version } : {}),
121
+ ...(commandRevisionOf(commandName) ? { commandRevision: commandRevisionOf(commandName)! } : {}),
122
+ protocolVersion: PROTOCOL_VERSION,
123
+ ...(role ? { role } : {}),
124
+ ...(def ? { rights: { scope: def.scope, ...(def.scope !== 'none' && def.targetOf ? { target: def.targetOf(input as never) } : {}) } } : {}),
125
+ }
126
+ }
127
+
128
+ /** The batch row's producer material — the batch-level facts plus EACH ITEM's recorded rights, so a
129
+ * later redelivery re-proves every item (a removed command's item included). Rows written before
130
+ * per-item tracking carry no items — unprovable, refused as a whole (never read as "no restriction"). */
131
+ export function batchProducerOf(validated: { def: CommandDefinition<any>; name: string; input: any }[], role: string) {
132
+ return { ...producerOf('batch', undefined, role), items: validated.map((v) => producerOf(v.name, v.def, role, v.input)) }
133
+ }
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * per process; tests reset it in place with resetKernelForTests. */
6
6
  export { GateError, STAGE_NAMES } from './types.js'
7
7
  export type { CommandDefinition, DomainEvent, ErrorCodeDefinition, Identity, RecoveryAction, RecoveryHint, Role } from './types.js'
8
+ export type { EventOperationMeta, ContractMeta, ContractResponseMeta, EventUndoPolicy, SourceEvent, SourceOperation, UndoPlan, UndoPlanChange, UndoPlanLoss, UndoPlanBlocker, UndoHandler, UndoPreview, KernelOptions, CatalogChangeRecord, CatalogRelease, CatalogRevisions } from './types.js'
8
9
  export { hashPassword, verifyPassword, issueUserToken, issueDelegationToken, login, unauthenticated, loadIdentity, currentIdentityOf, identityFromToken, ensureUser } from './auth.js'
9
10
  export { executeCommand, executeBatch } from './gate.js'
10
11
  export type { ExecutionRefusal, ExecutionResult, ExecutionSuccess } from './gate.js'
@@ -18,9 +19,14 @@ export { registerAppProtocol, protocolPreamble, PROTOCOL_BATCH, PROTOCOL_DELEGAT
18
19
  export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape, queryAccessOf } from './queries.js'
19
20
  export type { QueryDefinition, QueryOutcome, QueryRefusal } from './queries.js'
20
21
  export { registerRoles, registerCommand, lookupCommand, allCommands, inputShapeOf, catalogMeta, registerTransitionMachine, transitionRulesOf, allTransitionMachines, registerEventContracts, eventContractOf, allEventContractTypes, registerErrorCodes, errorCodeOf, allErrorCodes, catalogConsistencyErrors, completeAssembly, sealRegistries } from './registry.js'
22
+ export { registerUndoHandler, registerUndoPolicies, undoPolicyOf, undoHandlerOf, allUndoPolicies, registerEventVersions, eventVersionOf, allEventVersions, configureKernel, kernelOptions, registerCatalogRelease } from './registry.js'
21
23
  export type { TransitionRule } from './registry.js'
24
+ export { buildCatalogDocument, catalogStatus, catalogChanges, catalogRevisionOf, commandRevisionOf, queryRevisionOf, viewRevisionOf, commandContractShape, queryContractShape, computeCatalogRevisions, responseMetaOf, PROTOCOL_VERSION } from './catalog.js'
25
+ export { validateReleaseManifest, structuralBreakingChanges } from './releases.js'
26
+ export type { CatalogReleaseManifest, ReleaseManifestContract } from './releases.js'
27
+ export { previewUndo, executeUndo, undoStatus } from './undo.js'
22
28
  export { roleAllowsCommand, delegationScopeEntries, commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
23
29
  export type { CommandAccess, CommandRestriction } from './visibility.js'
24
30
  export { registriesSealed, resetKernelForTests } from './state.js'
25
31
  export { registerStorage, storageOf, db, readLedger, maskSecrets, USER_STATUS_ACTIVE, USER_STATUS_DEPRECATED } from './storage.js'
26
- export type { IdempotencyHit, LedgerReadRow, LedgerRow, SqlDialect, SqlStatement, StoragePort, StoredDelegation, StoredUser, UserStatus } from './storage.js'
32
+ export type { IdempotencyHit, LedgerReadRow, LedgerRow, OperationLedgerCapability, SqlDialect, SqlStatement, StoragePort, StoredDelegation, StoredUser, UserStatus } from './storage.js'
package/src/mcp.ts CHANGED
@@ -18,10 +18,11 @@ import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
18
18
  import { z } from 'zod'
19
19
  import { executeCommand } from './gate.js'
20
20
  import { identityFromToken, unauthenticated } from './auth.js'
21
- import { allQueries, describeShape, executeQuery } from './queries.js'
22
- import { protocolPreamble } from './protocol.js'
23
- import { allCommands, allErrorCodes, inputShapeOf } from './registry.js'
24
- import { commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
21
+ import { allQueries, executeQuery } from './queries.js'
22
+ import { buildCatalogDocument, catalogChanges, catalogStatus } from './catalog.js'
23
+ import { executeUndo, previewUndo, undoStatus } from './undo.js'
24
+ import { allCommands, inputShapeOf } from './registry.js'
25
+ import { commandAccessOf, visibleQueriesFor } from './visibility.js'
25
26
 
26
27
  // Identify rejections use the same contract as gate refusals (code·recovery included) — same source as REST 401 (auth.ts)
27
28
  const denied = (reason: string) => JSON.stringify(unauthenticated(reason))
@@ -31,6 +32,36 @@ const denied = (reason: string) => JSON.stringify(unauthenticated(reason))
31
32
  const toolNameOf = (name: string) =>
32
33
  'cmd_' + name.replace(/\./g, '_').replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
33
34
 
35
+ /** A tool-schema field that DESCRIBES the domain contract but never judges or normalizes. The SDK
36
+ * parses tool arguments with this schema before the handler runs — a domain field here must not
37
+ * transform (a coerce·transform chain would apply TWICE: SDK once, gate again), must not inject
38
+ * defaults (the gate's idempotency hash must see the request exactly as sent), and must not reject
39
+ * (a stored-success redelivery must reach the gate's replay-first ordering even under today's
40
+ * schema). Sharing the inner _def keeps tools/list faithful — JSON-schema derivation still sees the
41
+ * domain type, checks, defaults and descriptions — while _parse returns the caller's raw value
42
+ * untouched. The gate remains the single judge and the single normalizer. */
43
+ class RawArgField extends z.ZodType<unknown, z.ZodTypeDef, unknown> {
44
+ constructor(private readonly inner: z.ZodTypeAny) {
45
+ super(inner._def as z.ZodTypeDef)
46
+ }
47
+ // always-valid with the raw value — the gate decides (see the class doc)
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ _parse(input: any): any {
50
+ return { status: 'valid' as const, value: input.data }
51
+ }
52
+ // JSON-schema derivation probes optionality through isOptional() — answer like the described
53
+ // contract, not like the always-valid passthrough
54
+ isOptional(): boolean {
55
+ return this.inner.isOptional()
56
+ }
57
+ }
58
+
59
+ /** A whole tool-argument schema: every field a RawArgField, the object passthrough — the handler
60
+ * receives the arguments exactly as the client sent them (unknown keys included, so a newer contract
61
+ * or a redelivery reaches the gate byte-for-byte as sent). */
62
+ const rawArgsOf = (shape: Record<string, z.ZodTypeAny>) =>
63
+ z.object(Object.fromEntries(Object.entries(shape).map(([k, v]) => [k, new RawArgField(v)]))).passthrough()
64
+
34
65
  /** App identity mounted onto the MCP server — server name·version and catalog version (app-specific values) */
35
66
  export interface McpAppInfo {
36
67
  name: string
@@ -50,12 +81,22 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
50
81
  toolNameOf(def.name),
51
82
  {
52
83
  description: `[${def.allowedRoles.join('/')}] ${def.description}`,
53
- // Common protocol options merged into every command tool — never re-declared per command (G-03)
54
- inputSchema: {
84
+ // Common protocol options merged into every command tool — never re-declared per command (G-03).
85
+ // Every field is a RawArgField: the schema DESCRIBES for tools/list but never judges at the SDK
86
+ // layer — the gate owns replay-first ordering, contract comparison and single normalization.
87
+ inputSchema: rawArgsOf({
55
88
  ...inputShapeOf(def.input),
56
89
  dryRun: z.boolean().optional().describe('true validates stages 1-7 only, without executing (pre-check)'),
57
90
  requestKey: z.string().optional().describe('Idempotency key for retries — resending the same key with the same request returns the stored result'),
58
- },
91
+ contract: z
92
+ .object({
93
+ commandVersion: z.string(),
94
+ commandRevision: z.string(),
95
+ protocolVersion: z.string(),
96
+ })
97
+ .optional()
98
+ .describe('strict contract mode: the command contract this call was built against (commandVersion·commandRevision from the catalog, protocolVersion from catalog status)'),
99
+ }),
59
100
  },
60
101
  async (args: Record<string, unknown>) => {
61
102
  if (!identity) return { content: [{ type: 'text' as const, text: denied('No valid token — sign in and pass the issued token') }], isError: true }
@@ -75,8 +116,8 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
75
116
  for (const def of allQueries()) {
76
117
  server.registerTool(
77
118
  `query_${def.name}`,
78
- { description: `Query: ${def.name} — ${def.description} (read-only, outside the gate)`, inputSchema: def.params ?? {} },
79
- async (args: Record<string, string>) => {
119
+ { description: `Query: ${def.name} — ${def.description} (read-only, outside the gate)`, inputSchema: rawArgsOf(def.params ?? {}) },
120
+ async (args: Record<string, unknown>) => {
80
121
  // public queries (allowlist — only explicit true) are callable without a token; reads otherwise use the
81
122
  // call-time identity (delegation·revocation reflected). Params·errors are unified by the kernel entry
82
123
  // (executeQuery) — the same contract as the REST surface.
@@ -92,41 +133,152 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
92
133
  // Catalog guidance tool — the first gate for agents that arrive without source code
93
134
  // (what can be done + how refusals are handled + who am I). The document is personal: it lists
94
135
  // only what the current identity may use, derived with the same predicates as the tool list.
136
+ // Body: the single manifest builder (buildCatalogDocument) — REST and MCP dress the same source,
137
+ // only the transport-specific dressing (tool names) is added here.
95
138
  server.registerTool(
96
139
  'catalog',
97
- { description: 'Returns the commands·queries the CURRENT identity may use (name·description·roles·example·fields·output shape·error codes·target restrictions), the transition tables, the error-code dictionary, protocol guidance, and the current identity' },
140
+ { description: 'Returns the commands·queries the CURRENT identity may use (name·description·roles·example·fields·output shape·error codes·contract version·revision), the transition tables, the error-code dictionary, the undo policies, protocol guidance, and the current identity' },
98
141
  async () => {
99
142
  // The identity is re-read at call time (role·assignment·delegation revocation reflected immediately)
100
143
  const live = await liveIdentity()
101
- // Command guidance derives from the visibility module (same source as REST /api/catalog) + the tool name
102
- const cmds = visibleCatalogMeta(live).map((d) => ({ ...d, tool: toolNameOf(d.name) }))
144
+ const doc = buildCatalogDocument(live)
103
145
  return {
104
146
  content: [{
105
147
  type: 'text',
106
148
  text: JSON.stringify({
107
149
  ok: true,
108
- version: appInfo.catalogVersion,
109
- protocol: protocolPreamble(),
110
- transitions: visibleTransitionMachinesFor(live),
111
- errorCodes: allErrorCodes(),
112
- identity: live,
113
- commands: cmds,
114
- queries: visibleQueriesFor(live).map((q) => ({
115
- name: q.name,
116
- tool: `query_${q.name}`,
117
- description: q.description,
118
- clientScoped: q.clientScoped,
119
- public: q.public ?? false,
120
- ...(q.allowedRoles ? { allowedRoles: q.allowedRoles } : {}),
121
- params: Object.fromEntries(Object.entries(q.params ?? {}).map(([k, v]) => [k, describeShape(v)])),
122
- output: describeShape(q.output),
123
- })),
150
+ ...doc,
151
+ catalogVersion: doc.catalogVersion ?? appInfo.catalogVersion,
152
+ commands: doc.commands.map((c: { name: string }) => ({ ...c, tool: toolNameOf(c.name) })),
153
+ queries: doc.queries.map((q: { name: string }) => ({ ...q, tool: `query_${q.name}` })),
124
154
  }),
125
155
  }],
126
156
  }
127
157
  },
128
158
  )
129
159
 
160
+ // Common contract tools — version discovery, change lookup and the undo surface. None of them assume
161
+ // server push or tools/list_changed: status·response meta·write preconditions alone let a session-less
162
+ // caller detect changes and get stale writes refused. All re-read the identity at call time.
163
+ const requireLive = async (what: string) => {
164
+ if (identity) {
165
+ const live = await liveIdentity()
166
+ if (live) return live
167
+ return { denied: denied('Token invalidated (delegation revoked/expired or user deactivated)') }
168
+ }
169
+ return { denied: denied(`No valid token — sign in and pass the issued token (${what})`) }
170
+ }
171
+
172
+ // The machine-readable contract of ONE command — the SAME canonical shape the revision fingerprint
173
+ // is computed from, so the published contract and the fingerprint can never drift apart. Catalog-only
174
+ // consumers (REST surfaces without tools/list) rebuild the input contract from here.
175
+ server.registerTool(
176
+ 'command_contract',
177
+ {
178
+ description:
179
+ 'The machine-readable input·output contract of one command (types, required-ness, checks, defaults) — the same canonical shape the command revision fingerprint is computed from; role-visible commands only',
180
+ inputSchema: { command: z.string().describe('the command name from the catalog') },
181
+ },
182
+ async (args: { command?: string }) => {
183
+ const live = await requireLive('command_contract')
184
+ if ('denied' in live) return { content: [{ type: 'text' as const, text: live.denied }], isError: true }
185
+ const name = String(args?.command ?? '')
186
+ const def = allCommands().find((c) => c.name === name)
187
+ if (!def) return { content: [{ type: 'text' as const, text: denied(`Unknown command: ${name}`) }], isError: true }
188
+ if (!commandAccessOf(def, live).visible)
189
+ return { content: [{ type: 'text' as const, text: denied('This command is not visible to your identity') }], isError: true }
190
+ const { commandContractShape, commandRevisionOf } = await import('./catalog.js')
191
+ return {
192
+ content: [
193
+ {
194
+ type: 'text',
195
+ text: JSON.stringify({
196
+ ok: true,
197
+ name,
198
+ version: def.version ?? null,
199
+ revision: commandRevisionOf(name) ?? null,
200
+ contract: commandContractShape(def),
201
+ }),
202
+ },
203
+ ],
204
+ }
205
+ },
206
+ )
207
+
208
+ server.registerTool(
209
+ 'catalog_status',
210
+ { description: 'Current contract versions and revisions for your view (protocolVersion·catalogVersion·catalogRevision·viewRevision) — compare on reconnect to detect changes cheaply' },
211
+ async () => {
212
+ const live = await requireLive('catalog_status')
213
+ if ('denied' in live) return { content: [{ type: 'text' as const, text: live.denied }], isError: true }
214
+ return { content: [{ type: 'text' as const, text: JSON.stringify({ ok: true, ...catalogStatus(live) }) }] }
215
+ },
216
+ )
217
+ server.registerTool(
218
+ 'catalog_changes',
219
+ {
220
+ description: 'What changed in the catalog since a revision you last learned — an optimization; an unknown revision answers fullRefreshRequired (the full catalog is always the source of truth)',
221
+ inputSchema: { since: z.string().describe('the catalogRevision you last learned') },
222
+ },
223
+ async (args: { since?: string }) => {
224
+ const live = await requireLive('catalog_changes')
225
+ if ('denied' in live) return { content: [{ type: 'text' as const, text: live.denied }], isError: true }
226
+ return { content: [{ type: 'text' as const, text: JSON.stringify({ ok: true, ...catalogChanges({ since: String(args?.since ?? '') }, live) }) }] }
227
+ },
228
+ )
229
+ server.registerTool(
230
+ 'undo_status',
231
+ {
232
+ description: 'Per-sequence undo support·processing state (exact ledger sequences — the status is a list view, not an execution guarantee)',
233
+ inputSchema: { sourceSeqs: z.array(z.number().int()).describe('exact ledger sequences to check (up to 100)') },
234
+ },
235
+ async (args: { sourceSeqs?: number[] }) => {
236
+ const live = await requireLive('undo_status')
237
+ if ('denied' in live) return { content: [{ type: 'text' as const, text: live.denied }], isError: true }
238
+ const res = await undoStatus({ sourceSeqs: (args?.sourceSeqs ?? []).map(Number) }, live)
239
+ return { content: [{ type: 'text' as const, text: JSON.stringify(res) }], isError: res.ok === false }
240
+ },
241
+ )
242
+ server.registerTool(
243
+ 'undo_preview',
244
+ {
245
+ description: 'Preview the undo of the operation behind a ledger sequence — the compensation plan, conflicts, losses and the plan hash, judged for your current identity against current state',
246
+ inputSchema: { sourceSeq: z.number().int().describe('any event sequence of the operation — the whole atomic operation is resolved') },
247
+ },
248
+ async (args: { sourceSeq?: number }) => {
249
+ const live = await requireLive('undo_preview')
250
+ if ('denied' in live) return { content: [{ type: 'text' as const, text: live.denied }], isError: true }
251
+ const res = await previewUndo({ sourceSeq: Number(args?.sourceSeq) }, live)
252
+ return { content: [{ type: 'text' as const, text: JSON.stringify(res) }], isError: 'ok' in res && res.ok === false }
253
+ },
254
+ )
255
+ server.registerTool(
256
+ 'undo_execute',
257
+ {
258
+ description: 'Execute an undo — a forward compensation through the full gate. Send the plan hash from undo_preview (and acceptLosses:true when the preview reported losses)',
259
+ inputSchema: {
260
+ sourceSeq: z.number().int(),
261
+ expectedPlanHash: z.string().describe('the plan hash your preview showed — a moved plan is refused with undo.plan_changed'),
262
+ acceptLosses: z.boolean().optional().describe('confirm the losses the preview reported'),
263
+ requestKey: z.string().optional().describe('idempotency key for retries'),
264
+ },
265
+ },
266
+ async (args: Record<string, unknown>) => {
267
+ const live = await requireLive('undo_execute')
268
+ if ('denied' in live) return { content: [{ type: 'text' as const, text: live.denied }], isError: true }
269
+ const res = await executeUndo(
270
+ {
271
+ sourceSeq: Number(args?.sourceSeq),
272
+ expectedPlanHash: String(args?.expectedPlanHash ?? ''),
273
+ ...(args?.acceptLosses !== undefined ? { acceptLosses: args.acceptLosses === true } : {}),
274
+ ...(typeof args?.requestKey === 'string' && args.requestKey ? { requestKey: args.requestKey } : {}),
275
+ },
276
+ live,
277
+ )
278
+ return { content: [{ type: 'text' as const, text: JSON.stringify(res) }], isError: res.ok === false }
279
+ },
280
+ )
281
+
130
282
  // Tool-list visibility — wraps the SDK's installed tools/list handler so the answer carries only the
131
283
  // tools the *current* identity may use. The identity is re-read at every list request (role change·
132
284
  // delegation revocation apply to the next list, in both stdio and HTTP transports). The 'catalog'
@@ -141,7 +293,9 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
141
293
  lowLevel.setRequestHandler(ListToolsRequestSchema, async (request: unknown, extra: unknown) => {
142
294
  const res: any = await installed(request, extra)
143
295
  const identity = await identityFromToken(authHeader)
144
- const allowed = new Set<string>(['catalog'])
296
+ // Common tools stay listed for any identity — catalog is the manual that explains a denial; the
297
+ // status·changes·undo tools answer clearly (permission is decided per call, like hidden commands)
298
+ const allowed = new Set<string>(['catalog', 'catalog_status', 'catalog_changes', 'command_contract', 'undo_status', 'undo_preview', 'undo_execute'])
145
299
  for (const def of allCommands()) if (commandAccessOf(def, identity).visible) allowed.add(toolNameOf(def.name))
146
300
  for (const q of visibleQueriesFor(identity)) allowed.add(`query_${q.name}`)
147
301
  return { ...res, tools: (res?.tools ?? []).filter((t: { name?: string }) => allowed.has(String(t?.name))) }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Shared permission judgments — the primitive decisions every authorization site repeats:
3
+ * re-reading the live identity (inactive accounts are refused everywhere), the judged identity
4
+ * with CURRENT assignment scopes, delegation coverage over RECORDED material, the unprovable-
5
+ * rights refusal and the policy refusal→GateError mapping.
6
+ *
7
+ * What deliberately stays OUT of here: the path differences. Each caller states WHEN it judges
8
+ * (fresh execution vs replay of a stored result) and WHAT material it holds (the schema-parsed
9
+ * current input vs the recorded rights·target) — those decisions live at the call sites, never
10
+ * hidden behind a shared default.
11
+ *
12
+ * Internal module: not exported through index.ts.
13
+ */
14
+ import { currentIdentityOf } from './auth.js'
15
+ import { appPolicy, type PolicyRefusal } from './policy.js'
16
+ import { delegationScopeEntries, roleAllowsCommand } from './visibility.js'
17
+ import { GateError, type CommandDefinition, type Identity } from './types.js'
18
+
19
+ /** Re-reads the live identity; a caller whose account went inactive gets the caller's exact refusal
20
+ * (the messages differ by moment — execution, replay — so the refusal is passed in, not defaulted) */
21
+ export async function liveIdentityOf(identity: Identity, refuseInactive: () => GateError): Promise<Identity> {
22
+ const current = await currentIdentityOf(identity)
23
+ if (!current) throw refuseInactive()
24
+ return current
25
+ }
26
+
27
+ /** The identity a permission verdict is judged with: the CURRENT account with RE-COMPUTED
28
+ * assignment scopes. currentIdentityOf preserves the request-start scopes; a verdict — whether a
29
+ * fresh execution's scope recheck or a redelivery's re-proof — is judged with live assignments,
30
+ * so an assignment revoked mid-request refuses exactly as a new request would be refused. */
31
+ export async function judgedIdentityOf(current: Identity): Promise<Identity> {
32
+ return { ...current, scopes: await appPolicy().scopesFor(current.role, current.userId) }
33
+ }
34
+
35
+ /** Whether a still-valid delegation still covers a RECORDED command×scope×target — the range is
36
+ * judged on the recorded material (never a fresh targetOf over a past input); narrowing a
37
+ * delegation refuses later replays of results it produced. */
38
+ export async function delegationAllowsRecorded(
39
+ del: NonNullable<Identity['delegation']>,
40
+ commandName: string,
41
+ scope: string,
42
+ target: string | undefined,
43
+ ): Promise<boolean> {
44
+ const entries = delegationScopeEntries(del.scopes, commandName)
45
+ if (entries.length === 0) return false
46
+ if (entries.some((sc) => !sc.includes(':'))) return true
47
+ if (scope === 'none' || target === undefined) return false
48
+ const targets = entries.map((sc) => sc.slice(sc.indexOf(':') + 1))
49
+ return await appPolicy().delegationCovers(target, targets)
50
+ }
51
+
52
+ /** Delegation coverage refusal over recorded material — the stage is the caller's (2 at the
53
+ * delegation gate of a fresh pass, 3 inside a replay verdict); the sentence is the same one. */
54
+ export function assertRecordedDelegationCovers(
55
+ delegation: NonNullable<Identity['delegation']>,
56
+ commandName: string,
57
+ scope: string,
58
+ target: string | undefined,
59
+ stage: 2 | 3,
60
+ ): Promise<void> {
61
+ return delegationAllowsRecorded(delegation, commandName, scope, target).then((ok) => {
62
+ if (!ok) throw new GateError(stage, 'delegation', 'The current delegation no longer covers this command and target', { code: 'gate.delegation_denied' })
63
+ })
64
+ }
65
+
66
+ /** Rights material that cannot be re-proven (a row predating rights tracking, a missing recorded
67
+ * target) is REFUSED — never read as "no restriction" */
68
+ export function unprovableRefusal(message: string): GateError {
69
+ return new GateError(3, 'policy', message, { code: 'policy.denied' })
70
+ }
71
+
72
+ /** One mapping from the app policy's refusal to a stage-3 GateError — string refusals become
73
+ * policy.denied, object refusals keep their code. `carryRecovery` decides whether the policy's
74
+ * recovery hint travels with the refusal, and the two paths differ ON PURPOSE (review F1): a FRESH
75
+ * execution propagates the policy's guidance (the caller can act on it); a REPLAY verdict does not —
76
+ * a stored result's re-proof keeps the ERROR-CODE definition's default guidance, never the policy's
77
+ * momentary hint, exactly as the pre-refactoring replay paths behaved. */
78
+ export function policyRefusalGateError(refusal: string | PolicyRefusal, prefix = '', opts: { carryRecovery?: boolean } = {}): GateError {
79
+ const reason = `${prefix}${typeof refusal === 'string' ? refusal : refusal.reason}`
80
+ if (typeof refusal === 'string') return new GateError(3, 'policy', reason, { code: 'policy.denied' })
81
+ return new GateError(3, 'policy', reason, {
82
+ code: refusal.code,
83
+ ...(opts.carryRecovery && refusal.recovery ? { recovery: { action: refusal.recovery } } : {}),
84
+ })
85
+ }
86
+
87
+ /** Live role grant of a STILL-REGISTERED definition — an unchanged account role can lose the
88
+ * command when the definition narrows allowedRoles; removed commands have no live definition and
89
+ * stay judged on their recorded material only */
90
+ export function assertLiveRoleAllows(def: CommandDefinition<any>, role: string, message: string): void {
91
+ if (!roleAllowsCommand(def, role)) throw new GateError(3, 'policy', message, { code: 'gate.role_denied' })
92
+ }
@@ -2,10 +2,13 @@ import { storageOf } from './storage.js'
2
2
  import { assertOpenFor, defaultKernelState, type RegisteredProjector } from './state.js'
3
3
  import type { DomainEvent } from './types.js'
4
4
 
5
- /** Projection context — the recorded facts of an event (timestamp, sequence). Live application and replay receive the same values. */
5
+ /** Projection context — the recorded facts of an event (timestamp, sequence, format version).
6
+ * Live application and replay receive the same values. eventVersion defaults to 1 (legacy rows and
7
+ * engines without the operation-ledger capability) — per-version interpretation is the projector's concern. */
6
8
  export interface ProjectContext {
7
9
  ts: string
8
10
  seq: number
11
+ eventVersion?: number
9
12
  }
10
13
 
11
14
  export type ProjectionHandler = (payload: any, ctx: ProjectContext) => Promise<void>
@@ -99,6 +102,17 @@ export async function rebuildProjections(): Promise<void> {
99
102
  proj.initTables,
100
103
  async () => {
101
104
  for (const r of await storageOf().domainRows()) {
105
+ // eventVersion reaches replay through the envelope (operation-ledger engines) or the legacy
106
+ // version column; rows carrying neither are version 1 by definition
107
+ let eventVersion: number | undefined = r.version
108
+ if (r.meta) {
109
+ try {
110
+ const parsed = JSON.parse(r.meta) as { eventVersion?: number }
111
+ if (parsed.eventVersion !== undefined) eventVersion = parsed.eventVersion
112
+ } catch {
113
+ // a non-JSON envelope on a hand-edited row falls back to the version column — the read never fails
114
+ }
115
+ }
102
116
  await applyDomainEvent(
103
117
  {
104
118
  type: r.type,
@@ -107,7 +121,7 @@ export async function rebuildProjections(): Promise<void> {
107
121
  aggregate_id: r.aggregate_id ?? '',
108
122
  payload: JSON.parse(r.payload),
109
123
  },
110
- { seq: r.seq, ts: r.ts },
124
+ { seq: r.seq, ts: r.ts, ...(eventVersion !== undefined ? { eventVersion } : {}) },
111
125
  )
112
126
  }
113
127
  },
package/src/protocol.ts CHANGED
@@ -18,6 +18,10 @@ const baseProtocol: readonly string[] = [
18
18
  'Attach a requestKey to writes that may be retried — a resend with the same key returns the stored result (prevents double creation).',
19
19
  'dryRun:true passes validation (stages 1-7) without executing.',
20
20
  'Transition tables for stateful collections are in catalog.transitions — check which commands are legal from the current status (from) before executing.',
21
+ 'Success responses carry meta — the CURRENT contract revisions (protocolVersion·catalogRevision·viewRevision, and commandVersion·commandRevision for the command). A revision is a content fingerprint: it changes only when contract content changes. viewRevision is your personal view — it also moves when your permissions change. A replayed result keeps its old payload while meta states what is true now.',
22
+ 'Discover changes by comparing revisions, then reading the change list — a diff is an optimization; the full catalog is always the source of truth, and an unknown revision means refresh in full.',
23
+ 'In strict contract mode every write carries contract:{commandVersion,commandRevision,protocolVersion} beside the business input (from the catalog). A missing contract is refused (gate.contract_required); an outdated one is refused before execution (gate.contract_changed). After gate.contract_changed: read the status, read what changed, re-learn the fields — resending with the revision bumped but nothing re-read is not safe. Only the called command\'s revision matters: other commands changing never refuses yours.',
24
+ 'Undo (restore) is forward compensation — a new write, never a rewrite. Preview first (undo preview), confirm reported losses with acceptLosses and the whole plan with expectedPlanHash (the plan hash), then execute. Execution re-derives the plan under the write lock and refuses with undo.plan_changed when anything moved — preview again. Hard conflicts are never forceable; to go back again, undo the compensation itself.',
21
25
  ]
22
26
 
23
27
  /** Optional protocol lines — true of this kernel, relevant only when the app opens the feature.
@@ -43,7 +47,9 @@ export const PROTOCOL_LARGE_JOBS: string =
43
47
  /** App-specific guidance to append — the assembly layer calls this once at boot */
44
48
  export function registerAppProtocol(lines: readonly string[]): void {
45
49
  assertOpenFor(defaultKernelState, 'registerAppProtocol')
46
- defaultKernelState.protocolLines = lines
50
+ // copy-and-freeze — the caller's array never stays aliased: mutating it after registration must not
51
+ // change the published preamble (the same lifecycle rule every sealed registration follows)
52
+ defaultKernelState.protocolLines = Object.freeze([...lines])
47
53
  }
48
54
 
49
55
  /** The full preamble — app guidance follows the common section (the common section alone is valid without additions) */
package/src/queries.ts CHANGED
@@ -28,6 +28,11 @@ export interface QueryDefinition {
28
28
  /** Output contract — smoke fails when a declared field is missing from real results or has a different type */
29
29
  output: z.ZodTypeAny
30
30
  handler: (params: Record<string, string>, identity?: Identity) => Promise<unknown>
31
+ /** Query contract version (semver) — the read contract versions too, so surfaces detect read drift.
32
+ * Required in strict mode */
33
+ version?: string
34
+ /** Explicit revision for meaning changes no fingerprint can derive — bumped by the domain */
35
+ behaviorRevision?: string
31
36
  }
32
37
 
33
38
  /** Query registration — registering the same name twice fails the assembly. Copy-and-freeze (frozenCopyOf):