@sudoke/kernel 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +29 -4
- package/src/auth.ts +125 -0
- package/src/gate.ts +710 -0
- package/src/index.ts +24 -0
- package/src/mcp.ts +123 -0
- package/src/policy.ts +60 -0
- package/src/projections.ts +115 -0
- package/src/protocol.ts +51 -0
- package/src/queries.ts +148 -0
- package/src/registry.ts +235 -0
- package/src/state.ts +134 -0
- package/src/storage.ts +208 -0
- package/src/types.ts +121 -0
- package/README.md +0 -3
package/src/index.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Public kernel entry — apps (domain·assembly) import only from here as '@sudoke/kernel'.
|
|
2
|
+
* Kernel files import each other via relative paths (this gate exists for apps).
|
|
3
|
+
* The list is explicit on purpose: the process-state plumbing (xxxIn·KernelState·defaultKernelState·
|
|
4
|
+
* freshKernelState·sealFor·assertOpenFor) is not part of the app surface. There is exactly one kernel
|
|
5
|
+
* per process; tests reset it in place with resetKernelForTests. */
|
|
6
|
+
export { GateError, STAGE_NAMES } from './types.js'
|
|
7
|
+
export type { CommandDefinition, DomainEvent, ErrorCodeDefinition, Identity, RecoveryAction, RecoveryHint, Role } from './types.js'
|
|
8
|
+
export { hashPassword, verifyPassword, issueUserToken, issueDelegationToken, login, unauthenticated, loadIdentity, currentIdentityOf, identityFromToken, ensureUser } from './auth.js'
|
|
9
|
+
export { executeCommand, executeBatch } from './gate.js'
|
|
10
|
+
export type { ExecutionRefusal, ExecutionResult, ExecutionSuccess } from './gate.js'
|
|
11
|
+
export { buildMcpServer } from './mcp.js'
|
|
12
|
+
export type { McpAppInfo } from './mcp.js'
|
|
13
|
+
export { registerAppPolicy, appPolicy } from './policy.js'
|
|
14
|
+
export type { AppPolicy, PolicyRefusal } from './policy.js'
|
|
15
|
+
export { registerAppProjector, applyDomainEvent, eventPayloadBefore, rebuildProjections } from './projections.js'
|
|
16
|
+
export type { AppProjector, ProjectContext, ProjectionHandler } from './projections.js'
|
|
17
|
+
export { registerAppProtocol, protocolPreamble, PROTOCOL_BATCH, PROTOCOL_DELEGATION_TOKENS, PROTOCOL_EVENT_SUBSCRIPTION, PROTOCOL_LARGE_JOBS } from './protocol.js'
|
|
18
|
+
export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape } from './queries.js'
|
|
19
|
+
export type { QueryDefinition, QueryOutcome, QueryRefusal } from './queries.js'
|
|
20
|
+
export { registerRoles, registerCommand, lookupCommand, allCommands, inputShapeOf, catalogMeta, registerTransitionMachine, transitionRulesOf, allTransitionMachines, registerEventContracts, eventContractOf, allEventContractTypes, registerErrorCodes, errorCodeOf, allErrorCodes, catalogConsistencyErrors, completeAssembly, sealRegistries } from './registry.js'
|
|
21
|
+
export type { TransitionRule } from './registry.js'
|
|
22
|
+
export { registriesSealed, resetKernelForTests } from './state.js'
|
|
23
|
+
export { registerStorage, storageOf, db, readLedger, maskSecrets, USER_STATUS_ACTIVE, USER_STATUS_DEPRECATED } from './storage.js'
|
|
24
|
+
export type { IdempotencyHit, LedgerReadRow, LedgerRow, SqlDialect, SqlStatement, StoragePort, StoredDelegation, StoredUser, UserStatus } from './storage.js'
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP surface derivation — builds tools from the kernel registry. The app's mcp.ts injects contracts, then invokes this assembly.
|
|
3
|
+
*
|
|
4
|
+
* A newly registered command becomes a tool with no extra code (cmd_*). Auth is JWT —
|
|
5
|
+
* agents pass the same 9-stage gate as humans. Policy and invariant refusals come back as
|
|
6
|
+
* results (ok:false), not errors, so agents can read and react to them.
|
|
7
|
+
*
|
|
8
|
+
* The app provides only the server identity (name·version·catalog version). Commands and queries
|
|
9
|
+
* come from the kernel registry; protocol guidance comes from the common preamble plus the injected app section.
|
|
10
|
+
* Tool parameter descriptions come from the command schema's .describe(); roles and examples come from the catalog.
|
|
11
|
+
*/
|
|
12
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
13
|
+
import { z } from 'zod'
|
|
14
|
+
import { executeCommand } from './gate.js'
|
|
15
|
+
import { identityFromToken, unauthenticated } from './auth.js'
|
|
16
|
+
import { allQueries, describeShape, executeQuery } from './queries.js'
|
|
17
|
+
import { protocolPreamble } from './protocol.js'
|
|
18
|
+
import { allCommands, allErrorCodes, allTransitionMachines, catalogMeta, inputShapeOf } from './registry.js'
|
|
19
|
+
|
|
20
|
+
// Identify rejections use the same contract as gate refusals (code·recovery included) — same source as REST 401 (auth.ts)
|
|
21
|
+
const denied = (reason: string) => JSON.stringify(unauthenticated(reason))
|
|
22
|
+
|
|
23
|
+
// Command tool names — normalize dots·camelCase to snake_case (function. → cmd_function_add_node)
|
|
24
|
+
// The registration loop and the catalog guidance use the same function (a name can never split into two copies)
|
|
25
|
+
const toolNameOf = (name: string) =>
|
|
26
|
+
'cmd_' + name.replace(/\./g, '_').replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
|
|
27
|
+
|
|
28
|
+
/** App identity mounted onto the MCP server — server name·version and catalog version (app-specific values) */
|
|
29
|
+
export interface McpAppInfo {
|
|
30
|
+
name: string
|
|
31
|
+
version: string
|
|
32
|
+
catalogVersion: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Builds an MCP server with command·query·catalog tools registered — transport-agnostic (stdio/HTTP).
|
|
36
|
+
* authHeader: the identity-source header. Re-loaded on every call so delegation revocation/expiry applies immediately. */
|
|
37
|
+
export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | undefined): Promise<McpServer> {
|
|
38
|
+
const identity = await identityFromToken(authHeader)
|
|
39
|
+
const liveIdentity = () => identityFromToken(authHeader)
|
|
40
|
+
const server = new McpServer({ name: appInfo.name, version: appInfo.version })
|
|
41
|
+
|
|
42
|
+
for (const def of allCommands()) {
|
|
43
|
+
server.registerTool(
|
|
44
|
+
toolNameOf(def.name),
|
|
45
|
+
{
|
|
46
|
+
description: `[${def.allowedRoles.join('/')}] ${def.description}`,
|
|
47
|
+
// Common protocol options merged into every command tool — never re-declared per command (G-03)
|
|
48
|
+
inputSchema: {
|
|
49
|
+
...inputShapeOf(def.input),
|
|
50
|
+
dryRun: z.boolean().optional().describe('true validates stages 1-7 only, without executing (pre-check)'),
|
|
51
|
+
requestKey: z.string().optional().describe('Idempotency key for retries — resending the same key with the same request returns the stored result'),
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
async (args: Record<string, unknown>) => {
|
|
55
|
+
if (!identity) return { content: [{ type: 'text' as const, text: denied('No valid token — sign in and pass the issued token') }], isError: true }
|
|
56
|
+
// The identity is read at call time — a delegation cancelled after startup is refused immediately (G-04)
|
|
57
|
+
const live = await liveIdentity()
|
|
58
|
+
if (!live) return { content: [{ type: 'text' as const, text: denied('Token invalidated (delegation revoked/expired or user deactivated)') }], isError: true }
|
|
59
|
+
const res = await executeCommand(def.name, args ?? {}, live)
|
|
60
|
+
return {
|
|
61
|
+
content: [{ type: 'text' as const, text: JSON.stringify(res) }],
|
|
62
|
+
isError: res.ok === false,
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Query tools: query_<name> — parameters and descriptions also come from the query definition (no surface hardcoding)
|
|
69
|
+
for (const def of allQueries()) {
|
|
70
|
+
server.registerTool(
|
|
71
|
+
`query_${def.name}`,
|
|
72
|
+
{ description: `Query: ${def.name} — ${def.description} (read-only, outside the gate)`, inputSchema: def.params ?? {} },
|
|
73
|
+
async (args: Record<string, string>) => {
|
|
74
|
+
// public queries (allowlist — only explicit true) are callable without a token; reads otherwise use the
|
|
75
|
+
// call-time identity (delegation·revocation reflected). Params·errors are unified by the kernel entry
|
|
76
|
+
// (executeQuery) — the same contract as the REST surface.
|
|
77
|
+
const live = def.public ? null : await liveIdentity()
|
|
78
|
+
if (!def.public && !live)
|
|
79
|
+
return { content: [{ type: 'text' as const, text: denied(identity ? 'Token invalidated (delegation revoked/expired or user deactivated)' : 'No valid token — sign in and pass the issued token') }], isError: true }
|
|
80
|
+
const res = await executeQuery(def.name, args ?? {}, live)
|
|
81
|
+
return { content: [{ type: 'text' as const, text: JSON.stringify(res) }], isError: res.ok === false }
|
|
82
|
+
},
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Catalog guidance tool — the first gate for agents that arrive without source code
|
|
87
|
+
// (what can be done + how refusals are handled + who am I)
|
|
88
|
+
server.registerTool(
|
|
89
|
+
'catalog',
|
|
90
|
+
{ description: 'Returns every available command (name·description·roles·example·fields·output shape·error codes), the query list, transition tables, the error-code dictionary, protocol guidance, and the current identity' },
|
|
91
|
+
async () => {
|
|
92
|
+
// Command guidance derives from catalogMeta (same source as REST /api/catalog) + the tool name
|
|
93
|
+
const cmds = catalogMeta().map((d) => ({ ...d, tool: toolNameOf(d.name) }))
|
|
94
|
+
// The identity is re-read at call time (role·assignment·delegation revocation reflected immediately)
|
|
95
|
+
const live = await liveIdentity()
|
|
96
|
+
return {
|
|
97
|
+
content: [{
|
|
98
|
+
type: 'text',
|
|
99
|
+
text: JSON.stringify({
|
|
100
|
+
ok: true,
|
|
101
|
+
version: appInfo.catalogVersion,
|
|
102
|
+
protocol: protocolPreamble(),
|
|
103
|
+
transitions: allTransitionMachines(),
|
|
104
|
+
errorCodes: allErrorCodes(),
|
|
105
|
+
identity: live,
|
|
106
|
+
commands: cmds,
|
|
107
|
+
queries: allQueries().map((q) => ({
|
|
108
|
+
name: q.name,
|
|
109
|
+
tool: `query_${q.name}`,
|
|
110
|
+
description: q.description,
|
|
111
|
+
clientScoped: q.clientScoped,
|
|
112
|
+
public: q.public ?? false,
|
|
113
|
+
params: Object.fromEntries(Object.entries(q.params ?? {}).map(([k, v]) => [k, describeShape(v)])),
|
|
114
|
+
output: describeShape(q.output),
|
|
115
|
+
})),
|
|
116
|
+
}),
|
|
117
|
+
}],
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
return server
|
|
123
|
+
}
|
package/src/policy.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { GateError, type Identity, type RecoveryAction } from './types.js'
|
|
2
|
+
import { assertOpenFor, defaultKernelState } from './state.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* App-specific policy contract — the kernel knows no business model (S-01).
|
|
6
|
+
* Business-target interpretation, hierarchy inheritance and scope decisions belong to the app policy;
|
|
7
|
+
* the gate guarantees the registered policy is invoked, then executes or refuses accordingly.
|
|
8
|
+
*
|
|
9
|
+
* Registration is required only when a scope decision is actually needed: the catalog consistency check
|
|
10
|
+
* fails an assembly that registers scope-bearing commands without a policy (authorize·delegationCovers
|
|
11
|
+
* would be unreachable), while an app whose commands are all scope:'none' assembles with none —
|
|
12
|
+
* scopesFor then contributes an empty scope list (resolveScopes).
|
|
13
|
+
*
|
|
14
|
+
* Read-side helpers some apps also need (query row scoping, event target attribution) are app-owned
|
|
15
|
+
* extensions of this interface, not kernel contract — the kernel never invokes them.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** App-policy scope refusal — a sentence plus a stable code (registered in the domain error-code registry).
|
|
19
|
+
* Returning a plain string makes the kernel stamp the common code (policy.denied) instead */
|
|
20
|
+
export interface PolicyRefusal {
|
|
21
|
+
reason: string
|
|
22
|
+
code: string
|
|
23
|
+
recovery?: RecoveryAction
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface AppPolicy {
|
|
27
|
+
/** Compute the identity's access scope — role→scope rules (e.g. managers only cover assigned targets) are app-defined.
|
|
28
|
+
* Async: policies commonly read assignment tables through the storage port */
|
|
29
|
+
scopesFor(role: string, userId: string): Promise<string[]>
|
|
30
|
+
/** Does the identity's assigned scope cover this request's business target? — null to allow, a sentence or sentence+code to refuse (gate stage 3) */
|
|
31
|
+
authorize(identity: Identity, scopeKind: string, targetId: string | undefined): Promise<string | PolicyRefusal | null>
|
|
32
|
+
/** Do the delegation-scope targets (only entries attached to this command) cover the request's target? (gate stage 2) */
|
|
33
|
+
delegationCovers(targetId: string, scopeTargets: string[]): Promise<boolean>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Register the app policy — the assembly layer calls this once at boot */
|
|
37
|
+
export function registerAppPolicy(p: AppPolicy): void {
|
|
38
|
+
assertOpenFor(defaultKernelState, 'registerAppPolicy')
|
|
39
|
+
defaultKernelState.policy = p
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Scope resolution — an unregistered policy contributes no scopes (scope-free apps need no policy) */
|
|
43
|
+
export async function resolveScopes(role: string, userId: string): Promise<string[]> {
|
|
44
|
+
return defaultKernelState.policy ? defaultKernelState.policy.scopesFor(role, userId) : []
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The registered app policy — required the moment a scope decision is needed (scoped commands,
|
|
48
|
+
* delegation targets). The consistency check fails such assemblies at boot; this throw is the defensive
|
|
49
|
+
* backstop, never the first line. */
|
|
50
|
+
export function appPolicy(): AppPolicy {
|
|
51
|
+
const p = defaultKernelState.policy
|
|
52
|
+
if (!p)
|
|
53
|
+
throw new GateError(
|
|
54
|
+
3,
|
|
55
|
+
'policy',
|
|
56
|
+
'No app policy registered, so scope cannot be decided — check policy registration in the assembly layer',
|
|
57
|
+
{ code: 'policy.unregistered' },
|
|
58
|
+
)
|
|
59
|
+
return p
|
|
60
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { storageOf } from './storage.js'
|
|
2
|
+
import { assertOpenFor, defaultKernelState, type RegisteredProjector } from './state.js'
|
|
3
|
+
import type { DomainEvent } from './types.js'
|
|
4
|
+
|
|
5
|
+
/** Projection context — the recorded facts of an event (timestamp, sequence). Live application and replay receive the same values. */
|
|
6
|
+
export interface ProjectContext {
|
|
7
|
+
ts: string
|
|
8
|
+
seq: number
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type ProjectionHandler = (payload: any, ctx: ProjectContext) => Promise<void>
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* App projector contract — the kernel knows neither event names nor table structures (S-02).
|
|
15
|
+
* The app provides per-event apply rules, replay-init targets, and preserved tables with their reasons;
|
|
16
|
+
* the kernel guarantees registration, invocation, the replay procedure and atomicity. The assembly layer registers it.
|
|
17
|
+
*
|
|
18
|
+
* Discipline of the rules (replay integrity contract):
|
|
19
|
+
* - Business timestamps use ctx.ts (recorded time) only — depending on the current time, randomness or external calls changes values per replay.
|
|
20
|
+
* - Past events are read only via eventPayloadBefore(…, ctx) — the seq bound is structurally enforced.
|
|
21
|
+
* - Never begin or commit transactions inside rules — atomicity is the kernel's guarantee.
|
|
22
|
+
*/
|
|
23
|
+
export interface AppProjector {
|
|
24
|
+
/** Read tables to empty before replay — only tables fully derived from events. The ledger (events) can never be listed here */
|
|
25
|
+
initTables: string[]
|
|
26
|
+
/** Tables not emptied during replay, with reasons — the preservation rationale stays in the contract */
|
|
27
|
+
preservedTables: Array<{ table: string; reason: string }>
|
|
28
|
+
/** Register per-event apply rules — a second rule for the same event type fails registration */
|
|
29
|
+
rules: (on: (event: string, apply: ProjectionHandler) => void) => void
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const TABLE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
33
|
+
|
|
34
|
+
/** Replay-init forbidden targets — kernel-owned tables (ledger·audit·idempotency). Wiping idempotency records would erase retry keys and re-execute the same requests */
|
|
35
|
+
const INIT_FORBIDDEN: readonly string[] = ['events', 'idempotency']
|
|
36
|
+
|
|
37
|
+
/** Register the app projector — the assembly layer (server·mcp·seed) calls it before execution or replay */
|
|
38
|
+
export function registerAppProjector(p: AppProjector): void {
|
|
39
|
+
assertOpenFor(defaultKernelState, 'registerAppProjector')
|
|
40
|
+
const handlers = new Map<string, ProjectionHandler>()
|
|
41
|
+
p.rules((event, apply) => {
|
|
42
|
+
if (handlers.has(event)) throw new Error(`Projection rule registered twice: ${event}`)
|
|
43
|
+
handlers.set(event, apply)
|
|
44
|
+
})
|
|
45
|
+
// Init-target validation — SQLite does not distinguish table-name case, so compare lowercased (EVENTS·Idempotency cannot bypass the guard)
|
|
46
|
+
const init = new Map<string, string>()
|
|
47
|
+
for (const t of p.initTables) {
|
|
48
|
+
if (!TABLE_NAME_RE.test(t)) throw new Error(`Invalid init table name: ${t}`)
|
|
49
|
+
const key = t.toLowerCase()
|
|
50
|
+
if (INIT_FORBIDDEN.includes(key))
|
|
51
|
+
throw new Error(`Table cannot be a replay-init target: ${t} — the ledger/audit (events) and idempotency records are kernel-owned`)
|
|
52
|
+
if (init.has(key)) throw new Error(`Init tables collide case-insensitively: ${init.get(key)} / ${t}`)
|
|
53
|
+
init.set(key, t)
|
|
54
|
+
}
|
|
55
|
+
for (const { table } of p.preservedTables) {
|
|
56
|
+
if (!TABLE_NAME_RE.test(table)) throw new Error(`Invalid preserved table name: ${table}`)
|
|
57
|
+
if (init.has(table.toLowerCase()))
|
|
58
|
+
throw new Error(`Table is listed as both init and preserved: ${table} — pick one`)
|
|
59
|
+
}
|
|
60
|
+
defaultKernelState.projector = { initTables: [...init.values()], preservedTables: p.preservedTables, handlers }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function requireProjector(): RegisteredProjector {
|
|
64
|
+
const p = defaultKernelState.projector
|
|
65
|
+
if (!p) throw new Error('No app projector registered — check that registerAppProjector is called in the assembly layer')
|
|
66
|
+
return p
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Projection: applies domain events to read tables.
|
|
71
|
+
* Commands never mutate state directly — they only emit events —
|
|
72
|
+
* so this one function is the sole path of state change (ledger → passbook).
|
|
73
|
+
* An event with no apply rule fails instead of being skipped.
|
|
74
|
+
*/
|
|
75
|
+
export async function applyDomainEvent(e: DomainEvent, ctx: ProjectContext): Promise<void> {
|
|
76
|
+
const h = requireProjector().handlers.get(e.type)
|
|
77
|
+
if (!h) throw new Error(`No projection rule for event: ${e.type}`)
|
|
78
|
+
await h(e.payload, ctx)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Sequence-bounded event recovery — the source for restore/undo snapshots.
|
|
83
|
+
* It only reads records earlier than ctx.seq, so future references during replay are structurally impossible.
|
|
84
|
+
*/
|
|
85
|
+
export async function eventPayloadBefore(type: string, aggregateId: string, ctx: ProjectContext): Promise<any> {
|
|
86
|
+
const payload = await storageOf().latestDomainPayloadBefore(type, aggregateId, ctx.seq)
|
|
87
|
+
if (payload === undefined) throw new Error(`Replay failed — no record of ${type}(${aggregateId}) before seq ${ctx.seq}`)
|
|
88
|
+
return JSON.parse(payload)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Replay check: rebuilds every read table from the ledger (verification criterion #3).
|
|
93
|
+
* The registered contract is validated first, then init and the full replay run in one transaction —
|
|
94
|
+
* a failure mid-way returns to the pre-init state. The ledger and audit records are never touched.
|
|
95
|
+
*/
|
|
96
|
+
export async function rebuildProjections(): Promise<void> {
|
|
97
|
+
const proj = requireProjector()
|
|
98
|
+
await storageOf().rebuild(
|
|
99
|
+
proj.initTables,
|
|
100
|
+
async () => {
|
|
101
|
+
for (const r of await storageOf().domainRows()) {
|
|
102
|
+
await applyDomainEvent(
|
|
103
|
+
{
|
|
104
|
+
type: r.type,
|
|
105
|
+
// Domain rows always carry their aggregates (the column is only physically nullable for audit rows)
|
|
106
|
+
aggregate_type: r.aggregate_type ?? '',
|
|
107
|
+
aggregate_id: r.aggregate_id ?? '',
|
|
108
|
+
payload: JSON.parse(r.payload),
|
|
109
|
+
},
|
|
110
|
+
{ seq: r.seq, ts: r.ts },
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
)
|
|
115
|
+
}
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Operating protocol preamble — the minimum operating rules for agents that arrive without source code.
|
|
2
|
+
* The common section (baseProtocol) carries only sentences true for every app·surface assembled on this
|
|
3
|
+
* kernel — no HTTP paths, no query names, no surface conventions. Guidance that depends on a feature the
|
|
4
|
+
* app may or may not open is exported as the named optional constants below; an app that opens the feature
|
|
5
|
+
* appends the matching constant through registerAppProtocol. REST /api/catalog and the MCP catalog tool
|
|
6
|
+
* return the same text (never keep two copies). */
|
|
7
|
+
import { assertOpenFor, defaultKernelState } from './state.js'
|
|
8
|
+
|
|
9
|
+
const baseProtocol: readonly string[] = [
|
|
10
|
+
'Every write passes the 9-stage gate. A refusal is a result, not a failure: {ok:false, stage, stageName, reason, code, recovery} — judge by the stable identifier (code), not the sentence (reason); text may change but codes stay stable.',
|
|
11
|
+
'recovery.action classifies the next move: refresh = re-read the latest state via the query in recovery.query and retry · fix_input = correct the input and retry · reauthenticate = log in again / reissue the token, then retry · retry = resend the same request as-is (transient failures only) · stop = do not retry. retry never means force.',
|
|
12
|
+
'A refusal with canForce:true is a warning — resend the same input with force:true to execute it. Never try to force a refusal that lacks canForce.',
|
|
13
|
+
'Each command publishes output (the shape of a successful result) and errors (the business error codes it can raise) in the catalog — the full code dictionary, including gate-common codes, is in catalog.errorCodes.',
|
|
14
|
+
'Every change is recorded in the ledger (event log) — history is never rewritten or deleted.',
|
|
15
|
+
'If the [roles] in a command description differ from your role, or the target is outside your assigned scope, the gate refuses at stage 3 (policy). See the identity field for who you are.',
|
|
16
|
+
'Queries publish their params and output — check them before building screens or tools (no need to discover shapes by calling).',
|
|
17
|
+
'The catalog document carries a version (semver) — check it on connect; if it differs from what you learned, read the catalog again. On a MAJOR bump, re-check the fields of the commands you know.',
|
|
18
|
+
'Attach a requestKey to writes that may be retried — a resend with the same key returns the stored result (prevents double creation).',
|
|
19
|
+
'dryRun:true passes validation (stages 1-7) without executing.',
|
|
20
|
+
'Transition tables for stateful collections are in catalog.transitions — check which commands are legal from the current status (from) before executing.',
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
/** Optional protocol lines — true of this kernel, relevant only when the app opens the feature.
|
|
24
|
+
* Surface-owned values (HTTP paths, query names, parameter spellings) are deliberately absent; the app
|
|
25
|
+
* states them in its own registerAppProtocol lines beside the constant. */
|
|
26
|
+
|
|
27
|
+
/** For apps whose ledger query is sequenced and cursor-addressable (change detection by polling) */
|
|
28
|
+
export const PROTOCOL_EVENT_SUBSCRIPTION: string =
|
|
29
|
+
'Event subscription (polling): pass the last sequence you saw as the cursor parameter of the ledger query and you receive everything after it, in order — poll periodically and react.'
|
|
30
|
+
|
|
31
|
+
/** For apps that issue delegation tokens to their agents (the kernel supports them; issuing is an app decision) */
|
|
32
|
+
export const PROTOCOL_DELEGATION_TOKENS: string =
|
|
33
|
+
'Agents connect with delegation tokens — permissions are delegator permissions ∩ delegation scopes, and actions are recorded in audits as the actor. clientScoped queries return only rows inside the delegation scope (the surface filters the rest).'
|
|
34
|
+
|
|
35
|
+
/** For apps that expose an atomic multi-command batch surface (the kernel caps one batch at 20 items) */
|
|
36
|
+
export const PROTOCOL_BATCH: string =
|
|
37
|
+
'Atomic multi-command execution is available as a batch: all items execute or none do. Batch items carry no options — identify the whole batch with the top-level requestKey, and dry-run each command individually.'
|
|
38
|
+
|
|
39
|
+
/** For apps whose agents submit jobs larger than one batch */
|
|
40
|
+
export const PROTOCOL_LARGE_JOBS: string =
|
|
41
|
+
'Split large jobs into batches of 20 or fewer — only the refused batch is rolled back entirely, already-committed batches stay, and on retry invariants filter out already-registered items.'
|
|
42
|
+
|
|
43
|
+
/** App-specific guidance to append — the assembly layer calls this once at boot */
|
|
44
|
+
export function registerAppProtocol(lines: readonly string[]): void {
|
|
45
|
+
assertOpenFor(defaultKernelState, 'registerAppProtocol')
|
|
46
|
+
defaultKernelState.protocolLines = lines
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The full preamble — app guidance follows the common section (the common section alone is valid without additions) */
|
|
50
|
+
export const protocolPreamble = (): readonly string[] =>
|
|
51
|
+
defaultKernelState.protocolLines ? [...baseProtocol, ...defaultKernelState.protocolLines] : baseProtocol
|
package/src/queries.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import type { Identity, RecoveryHint } from './types.js'
|
|
3
|
+
import { unauthenticated } from './auth.js'
|
|
4
|
+
import { completeAssembly } from './registry.js'
|
|
5
|
+
import { assertOpenFor, defaultKernelState, frozenCopyOf } from './state.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Query (read) registry — as commands use the write registry (registry.ts), queries register here.
|
|
9
|
+
* The kernel knows neither table structures nor SQL: the app registers definitions and surfaces (REST·MCP) derive from the registry.
|
|
10
|
+
*
|
|
11
|
+
* Output contract: as commands carry an input contract (zod schema → catalog field docs),
|
|
12
|
+
* queries carry an output contract. The field shape is derived and published in the catalog,
|
|
13
|
+
* and smoke compares it against real results — when docs drift from code, it fails loudly instead of quietly going stale.
|
|
14
|
+
*/
|
|
15
|
+
export interface QueryDefinition {
|
|
16
|
+
name: string
|
|
17
|
+
description: string
|
|
18
|
+
/** Whether the handler must reflect the identity scope for delegation (agent) tokens (smoke enforces this contract) */
|
|
19
|
+
clientScoped: boolean
|
|
20
|
+
/** Callable without login (allowlist — only explicit true) */
|
|
21
|
+
public?: boolean
|
|
22
|
+
/** Query parameters — derived into MCP tool input and the catalog */
|
|
23
|
+
params?: Record<string, z.ZodTypeAny>
|
|
24
|
+
/** Output contract — smoke fails when a declared field is missing from real results or has a different type */
|
|
25
|
+
output: z.ZodTypeAny
|
|
26
|
+
handler: (params: Record<string, string>, identity?: Identity) => Promise<unknown>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Query registration — registering the same name twice fails the assembly. Copy-and-freeze (frozenCopyOf):
|
|
30
|
+
* the registrant's object stays untouched; what the registry stores is a frozen copy — flipping `public` (or
|
|
31
|
+
* anything else) on a returned definition throws TypeError immediately (ESM strict mode). */
|
|
32
|
+
export function registerQuery(def: QueryDefinition): void {
|
|
33
|
+
assertOpenFor(defaultKernelState, `registerQuery ${def.name}`)
|
|
34
|
+
if (defaultKernelState.queries.has(def.name)) throw new Error(`Query registered twice: ${def.name}`)
|
|
35
|
+
defaultKernelState.queries.set(def.name, frozenCopyOf({ ...def }))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const lookupQuery = (name: string): QueryDefinition | undefined => defaultKernelState.queries.get(name)
|
|
39
|
+
|
|
40
|
+
export const allQueries = (): QueryDefinition[] => [...defaultKernelState.queries.values()]
|
|
41
|
+
|
|
42
|
+
/** Output-contract violations — smoke compares real query results against them */
|
|
43
|
+
export function contractViolations(name: string, result: unknown): string[] {
|
|
44
|
+
const def = lookupQuery(name)
|
|
45
|
+
if (!def) return [`Unknown query: ${name}`]
|
|
46
|
+
const r = def.output.safeParse(result)
|
|
47
|
+
return r.success ? [] : r.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Query refusal — the same machine-usable shape as the gate's ExecutionRefusal (ok:false + stage·reason·code·recovery) */
|
|
51
|
+
export interface QueryRefusal {
|
|
52
|
+
ok: false
|
|
53
|
+
stage: number
|
|
54
|
+
stageName: string
|
|
55
|
+
reason: string
|
|
56
|
+
code: string
|
|
57
|
+
recovery?: RecoveryHint
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type QueryOutcome = { ok: true; result: unknown } | QueryRefusal
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Query execution — the read-side common entry beside the gate: params are parsed against the definition's
|
|
64
|
+
* contract, the public allowlist and identity requirement are enforced, and failures come back in the refusal
|
|
65
|
+
* shape (code·recovery) just like commands. Business row scoping (clientScoped filtering) stays with the app
|
|
66
|
+
* handler — the kernel does not know rows.
|
|
67
|
+
*/
|
|
68
|
+
export async function executeQuery(name: string, params: Record<string, unknown>, identity: Identity | null): Promise<QueryOutcome> {
|
|
69
|
+
completeAssembly() // the first call completes an unsealed assembly — same as the write entries
|
|
70
|
+
const def = lookupQuery(name)
|
|
71
|
+
if (!def)
|
|
72
|
+
return { ok: false, stage: 0, stageName: 'registry', reason: `Unknown query: ${name}`, code: 'query.unknown', recovery: { action: 'stop' } }
|
|
73
|
+
if (!def.public && !identity) return unauthenticated('Login required — this query is not public')
|
|
74
|
+
let parsed: Record<string, string>
|
|
75
|
+
try {
|
|
76
|
+
parsed = def.params ? (z.object(def.params).parse(params ?? {}) as Record<string, string>) : ({} as Record<string, string>)
|
|
77
|
+
} catch (err) {
|
|
78
|
+
const detail = err instanceof z.ZodError ? err.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ') : String(err)
|
|
79
|
+
return {
|
|
80
|
+
ok: false,
|
|
81
|
+
stage: 4,
|
|
82
|
+
stageName: 'schema',
|
|
83
|
+
reason: `Query params violate the contract: ${name} — ${detail}`,
|
|
84
|
+
code: 'query.params_invalid',
|
|
85
|
+
recovery: { action: 'fix_input' },
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
return { ok: true, result: await def.handler(parsed, identity ?? undefined) }
|
|
90
|
+
} catch (err) {
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
stage: 8,
|
|
94
|
+
stageName: 'execute',
|
|
95
|
+
reason: `Query failed: ${name} — ${err instanceof Error ? err.message : String(err)}`,
|
|
96
|
+
code: 'query.execution_failed',
|
|
97
|
+
recovery: { action: 'retry' },
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** zod schema → catalog shape doc. Same derivation as command input docs (never keep two copies) */
|
|
103
|
+
export function describeShape(s: any, depth = 0): unknown {
|
|
104
|
+
if (!s || depth > 8) return 'any'
|
|
105
|
+
const d = s._def ?? {}
|
|
106
|
+
switch (d.typeName) {
|
|
107
|
+
case 'ZodObject': {
|
|
108
|
+
const fields: Record<string, unknown> = {}
|
|
109
|
+
for (const [k, v] of Object.entries<any>(s.shape ?? d.shape ?? {}))
|
|
110
|
+
fields[k] = v?.description ? { shape: describeShape(v, depth + 1), desc: v.description } : describeShape(v, depth + 1)
|
|
111
|
+
return { fields }
|
|
112
|
+
}
|
|
113
|
+
case 'ZodArray':
|
|
114
|
+
return { arrayOf: describeShape(d.type ?? s.element, depth + 1) }
|
|
115
|
+
case 'ZodNullable':
|
|
116
|
+
return { nullable: true, shape: describeShape(d.innerType, depth + 1) }
|
|
117
|
+
case 'ZodOptional':
|
|
118
|
+
return { optional: true, shape: describeShape(d.innerType, depth + 1) }
|
|
119
|
+
case 'ZodEffects': // .refine()/.transform() wrapper — shows the inner schema shape (validation conditions themselves are not shown)
|
|
120
|
+
return describeShape(d.schema ?? d.innerType, depth + 1)
|
|
121
|
+
case 'ZodDefault':
|
|
122
|
+
case 'ZodReadonly':
|
|
123
|
+
case 'ZodCatch':
|
|
124
|
+
return describeShape(d.innerType, depth + 1)
|
|
125
|
+
case 'ZodRecord':
|
|
126
|
+
return { recordOf: describeShape(d.valueType ?? d.keyType, depth + 1) }
|
|
127
|
+
case 'ZodEnum':
|
|
128
|
+
return { enum: [...(d.values ?? [])] }
|
|
129
|
+
case 'ZodLiteral':
|
|
130
|
+
return { literal: String(d.value) }
|
|
131
|
+
case 'ZodUnion':
|
|
132
|
+
return { anyOf: (d.options ?? []).map((o: any) => describeShape(o, depth + 1)) }
|
|
133
|
+
case 'ZodString':
|
|
134
|
+
return 'string'
|
|
135
|
+
case 'ZodNumber':
|
|
136
|
+
return 'number'
|
|
137
|
+
case 'ZodBoolean':
|
|
138
|
+
return 'boolean'
|
|
139
|
+
case 'ZodDate':
|
|
140
|
+
return 'date'
|
|
141
|
+
case 'ZodAny':
|
|
142
|
+
case 'ZodUnknown':
|
|
143
|
+
return 'any'
|
|
144
|
+
default:
|
|
145
|
+
// Silently degrading an unhandled type to 'any' would make the catalog lie — surface the type name to admit it was not covered
|
|
146
|
+
return d.typeName ? `unsupported(${String(d.typeName).replace(/^Zod/, '')})` : 'any'
|
|
147
|
+
}
|
|
148
|
+
}
|