certal 0.0.0-stage → 0.1.1

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.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +56 -0
  3. package/LICENSE +21 -0
  4. package/README.md +289 -2
  5. package/SECURITY.md +36 -0
  6. package/bin/certal.mjs +12 -0
  7. package/certal.schema.json +156 -0
  8. package/dist/adapters/approval-channel.d.ts +44 -0
  9. package/dist/adapters/approval-channel.js +74 -0
  10. package/dist/adapters/commands.d.ts +77 -0
  11. package/dist/adapters/commands.js +209 -0
  12. package/dist/adapters/contracts.d.ts +59 -0
  13. package/dist/adapters/contracts.js +1 -0
  14. package/dist/adapters/file-watcher.d.ts +88 -0
  15. package/dist/adapters/file-watcher.js +297 -0
  16. package/dist/adapters/in-memory.d.ts +53 -0
  17. package/dist/adapters/in-memory.js +165 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +8 -0
  20. package/dist/adapters/manifest.d.ts +105 -0
  21. package/dist/adapters/manifest.js +465 -0
  22. package/dist/adapters/operator-auth.d.ts +53 -0
  23. package/dist/adapters/operator-auth.js +81 -0
  24. package/dist/adapters/tool-sdk.d.ts +150 -0
  25. package/dist/adapters/tool-sdk.js +336 -0
  26. package/dist/cli/index.d.ts +1 -0
  27. package/dist/cli/index.js +1 -0
  28. package/dist/cli/main.d.ts +1 -0
  29. package/dist/cli/main.js +384 -0
  30. package/dist/kernel/common.d.ts +46 -0
  31. package/dist/kernel/common.js +238 -0
  32. package/dist/kernel/crypto.d.ts +35 -0
  33. package/dist/kernel/crypto.js +54 -0
  34. package/dist/kernel/effects.d.ts +4 -0
  35. package/dist/kernel/effects.js +178 -0
  36. package/dist/kernel/index.d.ts +9 -0
  37. package/dist/kernel/index.js +9 -0
  38. package/dist/kernel/jcs.d.ts +24 -0
  39. package/dist/kernel/jcs.js +93 -0
  40. package/dist/kernel/leases.d.ts +11 -0
  41. package/dist/kernel/leases.js +86 -0
  42. package/dist/kernel/step.d.ts +10 -0
  43. package/dist/kernel/step.js +967 -0
  44. package/dist/kernel/types.d.ts +538 -0
  45. package/dist/kernel/types.js +1 -0
  46. package/dist/kernel/undo.d.ts +4 -0
  47. package/dist/kernel/undo.js +180 -0
  48. package/dist/kernel/validation.d.ts +13 -0
  49. package/dist/kernel/validation.js +307 -0
  50. package/dist/kernel/witness.d.ts +34 -0
  51. package/dist/kernel/witness.js +279 -0
  52. package/dist/mcp/host.d.ts +141 -0
  53. package/dist/mcp/host.js +517 -0
  54. package/dist/mcp/index.d.ts +2 -0
  55. package/dist/mcp/index.js +2 -0
  56. package/dist/mcp/server.d.ts +72 -0
  57. package/dist/mcp/server.js +549 -0
  58. package/dist/runtime/dp1.d.ts +48 -0
  59. package/dist/runtime/dp1.js +229 -0
  60. package/dist/runtime/engine.d.ts +86 -0
  61. package/dist/runtime/engine.js +320 -0
  62. package/dist/runtime/index.d.ts +4 -0
  63. package/dist/runtime/index.js +4 -0
  64. package/dist/runtime/outbox.d.ts +69 -0
  65. package/dist/runtime/outbox.js +238 -0
  66. package/dist/runtime/store.d.ts +214 -0
  67. package/dist/runtime/store.js +788 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +41 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +23 -0
  72. package/presets/vibeops.json +35 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,384 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { createKeyringSignatureVerifier } from '../kernel/index.js';
6
+ import { SQLiteStore, replayFromStore } from '../runtime/index.js';
7
+ import { MANIFEST_FILE, ManifestError, loadManifest } from '../adapters/manifest.js';
8
+ import { agentTokenDir, ensureOperatorKey, loadOperatorKey, operatorKeyPath, signApprovalToken, signOperatorCommand } from '../adapters/operator-auth.js';
9
+ import { CertalHost, DB_FILE, readRuntimeInfo, readStatus, readStoredOperatorKeys } from '../mcp/host.js';
10
+ import { AGENT_ID_PATTERN, McpGateway, packageVersion, serveHttp, serveStdio } from '../mcp/server.js';
11
+ /**
12
+ * The `certal` command line. Operator commands (`approve`, `undo`, `halt`, `reset`, `resume`)
13
+ * go to the running server as requests signed with the operator key, or run in this process
14
+ * when no server owns the state directory. With `--agent` every command prints one JSON line.
15
+ */
16
+ const PRESETS = { sdk: 'sdk.json', exchange: 'exchange-firewall.json', vibeops: 'vibeops.json', solver: 'solver.json' };
17
+ const UNDO_POLICIES = { abort: 'ABORT_ON_CONFLICT', 'all-reverted': 'COMPENSATE_ONLY_IF_ALL_REVERTED', force: 'FORCE_COMPENSATE' };
18
+ const HELP = `certal ${packageVersion()}
19
+
20
+ certal init [--preset sdk|exchange|vibeops|solver] [--force]
21
+ certal mcp [--transport stdio] [--agent-id <id>] [--watch]
22
+ certal mcp --transport http [--listen 127.0.0.1:7391] [--agents a,b] [--watch]
23
+ certal status
24
+ certal approve <attemptId> [--ttl 300s]
25
+ certal undo <batchId> [--policy abort|all-reverted|force] [--reason "..."]
26
+ certal halt <scopeId> --reason "..."
27
+ certal reset <scopeId> --reason "..."
28
+ certal resume <scopeId>
29
+ certal stop
30
+ certal verify --offline <dbPath>
31
+
32
+ Options for every command: --agent (one JSON line per answer), --cwd <dir>, --help`;
33
+ const BOOLEAN_FLAGS = new Set(['agent', 'force', 'watch', 'help']);
34
+ function parseArgs(argv) {
35
+ const positional = [];
36
+ const flags = {};
37
+ for (let i = 0; i < argv.length; i += 1) {
38
+ const arg = argv[i];
39
+ if (!arg.startsWith('--')) {
40
+ positional.push(arg);
41
+ continue;
42
+ }
43
+ const eq = arg.indexOf('=');
44
+ const name = eq > 0 ? arg.slice(2, eq) : arg.slice(2);
45
+ if (eq > 0)
46
+ flags[name] = arg.slice(eq + 1);
47
+ else if (BOOLEAN_FLAGS.has(name) || i + 1 >= argv.length)
48
+ flags[name] = true;
49
+ else {
50
+ flags[name] = argv[i + 1];
51
+ i += 1;
52
+ }
53
+ }
54
+ return { command: positional[0] ?? '', positional: positional.slice(1), flags };
55
+ }
56
+ class UsageError extends Error {
57
+ }
58
+ function parseDuration(text) {
59
+ const match = /^(\d+)(ms|s|m|h)?$/.exec(text);
60
+ if (!match)
61
+ throw new UsageError(`bad duration: ${text} (use 300s, 5m, 1h or milliseconds)`);
62
+ const unit = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[match[2] ?? 's'];
63
+ return Number(match[1]) * unit;
64
+ }
65
+ /** Sends one operator command: signed to the running server, or in this process when none runs. */
66
+ async function operatorCall(cwd, command, args) {
67
+ const manifest = loadManifest(cwd);
68
+ let live = readRuntimeInfo(manifest.stateDir);
69
+ // Port 0 means that the owner has no operator endpoint yet: a server that is starting, or another CLI command.
70
+ for (let waited = 0; live && live.operatorPort === 0 && waited < 50; waited += 1) {
71
+ await new Promise((resolve) => setTimeout(resolve, 100));
72
+ live = readRuntimeInfo(manifest.stateDir);
73
+ }
74
+ if (live && live.operatorPort === 0)
75
+ throw new UsageError(`another certal process (pid ${live.pid}) holds the state directory. Try again.`);
76
+ if (!live) {
77
+ const host = await CertalHost.open({ cwd, serveOperator: false, watch: false });
78
+ try {
79
+ return await host.operatorCommand(command, args);
80
+ }
81
+ finally {
82
+ host.close();
83
+ }
84
+ }
85
+ const key = loadOperatorKey();
86
+ if (!key)
87
+ throw new UsageError(`no operator key at ${operatorKeyPath()}. Run \`certal init\` as the operator.`);
88
+ const response = await fetch(`http://127.0.0.1:${live.operatorPort}/operator`, {
89
+ method: 'POST',
90
+ headers: { 'content-type': 'application/json' },
91
+ body: JSON.stringify(signOperatorCommand(key, command, args, Date.now())),
92
+ });
93
+ return (await response.json());
94
+ }
95
+ function agentLine(reply, scopeId, scopeEpoch, onAllow) {
96
+ const decision = reply.decision ?? (reply.ok ? 'ALLOW' : 'REJECT');
97
+ return {
98
+ decision,
99
+ reason: reply.reason ?? (reply.ok ? 'OK' : 'FAILED'),
100
+ scopeId,
101
+ scopeEpoch,
102
+ nextLegalAction: decision === 'ALLOW' ? onAllow : decision === 'PAUSE' ? 'wait_for_operator' : 'stop',
103
+ retryable: decision === 'PAUSE',
104
+ };
105
+ }
106
+ function printReply(out, reply, cwd, scopeId, onAllow, extra = {}) {
107
+ if (out.agent) {
108
+ const epochs = readStatus(cwd).status.scopeEpochs;
109
+ out.json({ ...agentLine(reply, scopeId, epochs[scopeId] ?? 0, onAllow), ...extra });
110
+ }
111
+ else {
112
+ out.line(`${reply.decision ?? (reply.ok ? 'OK' : 'FAILED')}${reply.reason ? `: ${reply.reason}` : ''}`);
113
+ for (const [key, value] of Object.entries(extra))
114
+ out.line(`${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`);
115
+ }
116
+ return reply.ok ? 0 : 1;
117
+ }
118
+ function cmdInit(cwd, flags, out) {
119
+ const preset = typeof flags.preset === 'string' ? flags.preset : 'sdk';
120
+ const presetFile = PRESETS[preset];
121
+ if (!presetFile)
122
+ throw new UsageError(`unknown preset: ${preset} (use ${Object.keys(PRESETS).join(', ')})`);
123
+ const target = path.join(cwd, MANIFEST_FILE);
124
+ if (fs.existsSync(target) && flags.force !== true)
125
+ throw new UsageError(`${MANIFEST_FILE} already exists. Use --force to replace it.`);
126
+ const packageRoot = path.join(import.meta.dirname, '..', '..');
127
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageRoot, 'presets', presetFile), 'utf8'));
128
+ const { key, created } = ensureOperatorKey();
129
+ manifest.operator = { humanId: os.userInfo().username || 'operator', publicKeys: { [key.keyId]: key.publicKeyPem } };
130
+ fs.writeFileSync(target, `${JSON.stringify({ $schema: 'https://raw.githubusercontent.com/polszewski-pl/certal/main/certal.schema.json', ...manifest }, null, 2)}\n`);
131
+ const mcpFile = path.join(cwd, '.mcp.json');
132
+ const wroteMcp = !fs.existsSync(mcpFile);
133
+ if (wroteMcp)
134
+ fs.writeFileSync(mcpFile, `${JSON.stringify({ mcpServers: { certal: { command: 'npx', args: ['--no-install', 'certal', 'mcp'] } } }, null, 2)}\n`);
135
+ if (out.agent)
136
+ out.json({ decision: 'ALLOW', reason: 'INITIALISED', preset, operatorKeyId: key.keyId, keyCreated: created, mcpConfigWritten: wroteMcp });
137
+ else {
138
+ out.line(`Wrote ${MANIFEST_FILE} (preset ${preset}).`);
139
+ out.line(created ? `Created the operator key ${key.keyId} at ${operatorKeyPath()}. Keep this file out of every repository.` : `Using the operator key ${key.keyId}.`);
140
+ out.line(wroteMcp ? 'Wrote .mcp.json.' : '.mcp.json exists and was left as it is.');
141
+ out.line('Add .certal/ to .gitignore. Commands in the preset are templates: point them at your own checks.');
142
+ if (preset === 'sdk')
143
+ out.line('The sdk preset accepts every batch at stage L0 without a check. Declare a witness command before you rely on it.');
144
+ }
145
+ return 0;
146
+ }
147
+ /** Reads `--listen`. Only a loopback address with a real port is accepted. */
148
+ function parseListen(text) {
149
+ const split = text.lastIndexOf(':');
150
+ const host = split > 0 ? text.slice(0, split) : '';
151
+ const portText = split > 0 ? text.slice(split + 1) : '';
152
+ const port = /^\d{1,5}$/.test(portText) ? Number(portText) : -1;
153
+ if (host === '' || port < 0 || port > 65535)
154
+ throw new UsageError('--listen must look like 127.0.0.1:7391, with a port from 0 to 65535');
155
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1')
156
+ throw new UsageError('--listen accepts a loopback address only');
157
+ return { host, port };
158
+ }
159
+ async function cmdMcp(cwd, flags) {
160
+ // Every flag is checked before the host opens, so a bad flag cannot leave a claimed state directory behind.
161
+ const transport = typeof flags.transport === 'string' ? flags.transport : 'stdio';
162
+ if (transport !== 'stdio' && transport !== 'http')
163
+ throw new UsageError('--transport must be stdio or http');
164
+ const agentId = typeof flags['agent-id'] === 'string' ? flags['agent-id'] : `agent-${process.pid}`;
165
+ if (!AGENT_ID_PATTERN.test(agentId))
166
+ throw new UsageError('--agent-id may hold letters, digits, dot, dash and underscore (64 at most)');
167
+ const agents = (typeof flags.agents === 'string' ? flags.agents : 'agent-1').split(',').map((name) => name.trim());
168
+ if (transport === 'http' && (agents.some((name) => !AGENT_ID_PATTERN.test(name)) || new Set(agents).size !== agents.length)) {
169
+ throw new UsageError('--agents is a comma-separated list of different agent ids (letters, digits, dot, dash and underscore)');
170
+ }
171
+ const listen = transport === 'http' ? parseListen(typeof flags.listen === 'string' ? flags.listen : '127.0.0.1:7391') : null;
172
+ const host = await CertalHost.open({ cwd, ...(flags.watch === true ? { watch: true } : {}) });
173
+ const gateway = new McpGateway(host);
174
+ const log = (text) => void process.stderr.write(`${text}\n`);
175
+ if (listen === null) {
176
+ const stop = () => { host.close(); process.exit(0); };
177
+ host.onShutdown = stop;
178
+ process.on('SIGINT', stop);
179
+ process.on('SIGTERM', stop);
180
+ log(`certal mcp: stdio, agent ${agentId}, state ${host.manifest.stateDir}`);
181
+ await serveStdio(gateway, agentId, process.stdin, process.stdout);
182
+ host.close();
183
+ return 0;
184
+ }
185
+ const tokenDir = agentTokenDir(host.manifest.baseDir);
186
+ let served;
187
+ try {
188
+ served = await serveHttp(gateway, listen.host, listen.port, agents);
189
+ fs.rmSync(tokenDir, { recursive: true, force: true });
190
+ fs.mkdirSync(tokenDir, { recursive: true, mode: 0o700 });
191
+ for (const [name, token] of Object.entries(served.tokens))
192
+ fs.writeFileSync(path.join(tokenDir, `${name}.token`), token, { mode: 0o600 });
193
+ }
194
+ catch (err) {
195
+ // A port that is taken, or a token directory that cannot be written: give the state directory back.
196
+ host.close();
197
+ log(`certal mcp: cannot serve on ${listen.host}:${listen.port}: ${String(err.message ?? err)}`);
198
+ return 1;
199
+ }
200
+ log(`certal mcp: http://${listen.host}:${served.port}/mcp`);
201
+ log(`certal mcp: agent tokens are in ${tokenDir} (${agents.join(', ')})`);
202
+ await new Promise((resolve) => {
203
+ const stop = () => {
204
+ served.server.close();
205
+ served.server.closeAllConnections();
206
+ fs.rmSync(path.dirname(tokenDir), { recursive: true, force: true });
207
+ host.close();
208
+ resolve();
209
+ };
210
+ host.onShutdown = stop;
211
+ process.on('SIGINT', stop);
212
+ process.on('SIGTERM', stop);
213
+ });
214
+ return 0;
215
+ }
216
+ function cmdStatus(cwd, out) {
217
+ const { status, live } = readStatus(cwd);
218
+ if (out.agent) {
219
+ const decision = status.taskStatus === 'ACTIVE' ? 'ALLOW' : status.taskStatus === 'PAUSED' ? 'PAUSE' : 'HALT';
220
+ out.json({
221
+ decision,
222
+ reason: status.pauseReason ?? status.haltReason ?? 'ACTIVE',
223
+ scopeId: '*',
224
+ scopeEpoch: status.scopeEpochs['*'] ?? 0,
225
+ nextLegalAction: decision === 'ALLOW' ? 'certal_lease_acquire' : decision === 'PAUSE' ? 'wait_for_operator' : 'stop',
226
+ retryable: decision === 'PAUSE',
227
+ scopeEpochs: status.scopeEpochs,
228
+ leases: status.leases.map((l) => `${l.scopeId}/${l.classId}:${l.ownerId}`),
229
+ pendingApprovals: status.pendingApprovals.map((p) => p.attemptId),
230
+ });
231
+ return 0;
232
+ }
233
+ printStatus(status, live, out);
234
+ return 0;
235
+ }
236
+ function printStatus(status, live, out) {
237
+ out.line(`task ${status.taskStatus}${status.pauseReason ? ` (${status.pauseReason})` : ''}${status.haltReason ? ` (${status.haltReason})` : ''}`);
238
+ out.line(`server ${live ? 'running' : 'not running'}, log entries ${status.serverSeq}`);
239
+ const epochs = Object.entries(status.scopeEpochs);
240
+ out.line(`epochs ${epochs.length === 0 ? 'none yet' : epochs.map(([scope, n]) => `${scope}=${n}`).join(' ')}`);
241
+ out.line(`leases ${status.leases.length === 0 ? 'none' : ''}`);
242
+ for (const l of status.leases)
243
+ out.line(` ${l.scopeId}/${l.classId} owner ${l.ownerId} attempt ${l.attemptId} epoch ${l.leaseEpoch} expires in ${Math.ceil(l.expiresInMs / 1000)} s`);
244
+ out.line(`autonomy ${status.autonomy.length === 0 ? 'no tools' : ''}`);
245
+ for (const a of status.autonomy)
246
+ out.line(` ${a.toolId} ${a.tier} to APPROVAL ${a.toApproval} to AUTO ${a.toAuto} violations ${a.violations}`);
247
+ out.line(`approvals ${status.pendingApprovals.length === 0 ? 'none waiting' : ''}`);
248
+ for (const p of status.pendingApprovals)
249
+ out.line(` ${p.attemptId} scope ${p.scopeId} tool ${p.toolId} ${p.reason ?? 'APPROVAL_REQUIRED'} [${p.diffSummary.join(', ')}]`);
250
+ }
251
+ async function cmdApprove(cwd, parsed, out) {
252
+ const attemptId = parsed.positional[0];
253
+ if (!attemptId)
254
+ throw new UsageError('usage: certal approve <attemptId> [--ttl 300s]');
255
+ const ttlMs = parseDuration(typeof parsed.flags.ttl === 'string' ? parsed.flags.ttl : '300s');
256
+ const key = loadOperatorKey();
257
+ if (!key)
258
+ throw new UsageError(`no operator key at ${operatorKeyPath()}. Run \`certal init\` as the operator.`);
259
+ const manifest = loadManifest(cwd);
260
+ const state = await operatorCall(cwd, 'status', {});
261
+ if (!state.ok || !state.data)
262
+ return printReply(out, { ok: false, decision: 'REJECT', reason: state.reason ?? 'STATUS_UNAVAILABLE' }, cwd, '*', '');
263
+ const pending = state.data.pendingApprovals.find((p) => p.attemptId === attemptId);
264
+ if (!pending)
265
+ return printReply(out, { ok: false, decision: 'REJECT', reason: 'NO_PENDING_APPROVAL' }, cwd, '*', '');
266
+ const token = signApprovalToken(key, {
267
+ approvalId: `appr-${attemptId}-${randomBytes(4).toString('hex')}`,
268
+ humanId: manifest.operator?.humanId ?? 'operator',
269
+ attemptId,
270
+ binding: pending.binding,
271
+ expiresAtMs: Date.now() + ttlMs,
272
+ });
273
+ const reply = await operatorCall(cwd, 'grant', { token });
274
+ return printReply(out, reply, cwd, pending.scopeId, 'certal_finalize_batch', { attemptId, approvalId: token.approvalId });
275
+ }
276
+ async function cmdUndo(cwd, parsed, out) {
277
+ const batchId = parsed.positional[0];
278
+ if (!batchId)
279
+ throw new UsageError('usage: certal undo <batchId> [--policy abort|all-reverted|force]');
280
+ const policyName = typeof parsed.flags.policy === 'string' ? parsed.flags.policy : 'all-reverted';
281
+ const compensationPolicy = UNDO_POLICIES[policyName];
282
+ if (!compensationPolicy)
283
+ throw new UsageError(`unknown undo policy: ${policyName} (use ${Object.keys(UNDO_POLICIES).join(', ')})`);
284
+ const reply = await operatorCall(cwd, 'undo', { batchId, compensationPolicy, reason: typeof parsed.flags.reason === 'string' ? parsed.flags.reason : '' });
285
+ const report = (reply.data ?? null);
286
+ return printReply(out, reply, cwd, '*', 'done', report
287
+ ? { appliedFields: report.appliedFields.map((f) => `${f.objectId}.${f.field}`), skippedConflicts: report.skippedConflicts, compensationMode: report.compensationMode }
288
+ : {});
289
+ }
290
+ async function cmdScope(cwd, command, parsed, out) {
291
+ const scopeId = parsed.positional[0];
292
+ const reason = typeof parsed.flags.reason === 'string' ? parsed.flags.reason : '';
293
+ if (!scopeId || (command !== 'resume' && !reason))
294
+ throw new UsageError(`usage: certal ${command} <scopeId>${command === 'resume' ? '' : ' --reason "..."'}`);
295
+ return printReply(out, await operatorCall(cwd, command, { scopeId, reason }), cwd, scopeId, 'done');
296
+ }
297
+ /**
298
+ * Audits a database file on its own: the hash chain of the log and a full replay from the first
299
+ * entry. It reads a private copy, so the audited file is not touched, and it needs no manifest:
300
+ * the operator public keys come from the database.
301
+ */
302
+ function cmdVerify(parsed, out) {
303
+ const dbPath = typeof parsed.flags.offline === 'string' ? parsed.flags.offline : parsed.positional[0];
304
+ if (!dbPath)
305
+ throw new UsageError('usage: certal verify --offline <dbPath>');
306
+ if (!fs.existsSync(dbPath))
307
+ throw new UsageError(`no such file: ${dbPath}`);
308
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'certal-verify-'));
309
+ try {
310
+ const copy = path.join(work, DB_FILE);
311
+ for (const suffix of ['', '-wal', '-shm']) {
312
+ if (fs.existsSync(dbPath + suffix))
313
+ fs.copyFileSync(dbPath + suffix, copy + suffix);
314
+ }
315
+ const keys = readStoredOperatorKeys(copy);
316
+ const store = new SQLiteStore(copy);
317
+ try {
318
+ const replayed = replayFromStore(store, { signatureVerifier: createKeyringSignatureVerifier({ ed25519PublicKeysPem: keys }) }, { fromGenesis: true, audit: true });
319
+ const report = { entries: replayed.replayedEntries, lastEntryHash: replayed.lastEntryHash, stateHash: replayed.stateHash, taskStatus: replayed.state.taskStatus, operatorKeys: Object.keys(keys) };
320
+ if (out.agent)
321
+ out.json({ decision: 'ALLOW', reason: 'LOG_VERIFIED', ...report });
322
+ else {
323
+ out.line(`OK: ${report.entries} log entries, hash chain intact, replay matches every entry, every checkpoint and both indexes.`);
324
+ out.line(`last entry hash ${report.lastEntryHash}`);
325
+ out.line(`state hash ${report.stateHash}`);
326
+ out.line(`task status ${report.taskStatus}`);
327
+ out.line(`operator keys ${report.operatorKeys.join(', ') || 'none'}`);
328
+ out.line('Compare the last entry hash and the key ids with values you hold elsewhere: a file rewritten from scratch is consistent with itself.');
329
+ }
330
+ return 0;
331
+ }
332
+ catch (err) {
333
+ const reason = String(err.message ?? err);
334
+ if (out.agent)
335
+ out.json({ decision: 'REJECT', reason: reason.split(/[ :]/)[0], detail: reason });
336
+ else
337
+ out.line(`FAILED: ${reason}`);
338
+ return 1;
339
+ }
340
+ finally {
341
+ store.close();
342
+ }
343
+ }
344
+ finally {
345
+ fs.rmSync(work, { recursive: true, force: true });
346
+ }
347
+ }
348
+ export async function main(argv) {
349
+ const parsed = parseArgs(argv);
350
+ const agent = parsed.flags.agent === true;
351
+ const out = {
352
+ agent,
353
+ line: (text) => void process.stdout.write(`${text}\n`),
354
+ json: (value) => void process.stdout.write(`${JSON.stringify(value)}\n`),
355
+ };
356
+ const cwd = path.resolve(typeof parsed.flags.cwd === 'string' ? parsed.flags.cwd : process.cwd());
357
+ try {
358
+ if (parsed.flags.help === true || parsed.command === '' || parsed.command === 'help') {
359
+ out.line(HELP);
360
+ return 0;
361
+ }
362
+ switch (parsed.command) {
363
+ case 'init': return cmdInit(cwd, parsed.flags, out);
364
+ case 'mcp': return await cmdMcp(cwd, parsed.flags);
365
+ case 'status': return cmdStatus(cwd, out);
366
+ case 'approve': return await cmdApprove(cwd, parsed, out);
367
+ case 'undo': return await cmdUndo(cwd, parsed, out);
368
+ case 'halt':
369
+ case 'reset':
370
+ case 'resume': return await cmdScope(cwd, parsed.command, parsed, out);
371
+ case 'stop': return printReply(out, await operatorCall(cwd, 'shutdown', {}), cwd, '*', 'done');
372
+ case 'verify': return cmdVerify(parsed, out);
373
+ default: throw new UsageError(`unknown command: ${parsed.command}\n\n${HELP}`);
374
+ }
375
+ }
376
+ catch (err) {
377
+ const message = err instanceof UsageError || err instanceof ManifestError ? err.message : String(err.stack ?? err);
378
+ if (agent)
379
+ out.json({ decision: 'REJECT', reason: err instanceof ManifestError ? 'MANIFEST_INVALID' : err instanceof UsageError ? 'USAGE' : 'ERROR', scopeId: '*', scopeEpoch: 0, nextLegalAction: 'stop', retryable: false, detail: message.split('\n')[0], ...(err instanceof ManifestError ? { errors: err.problems } : {}) });
380
+ else
381
+ process.stderr.write(`${message}\n`);
382
+ return 1;
383
+ }
384
+ }
@@ -0,0 +1,46 @@
1
+ import type { AttemptState, Decision, EffectRecord, EventEnvelope, Intent, KernelState, Lease2D, PinPolicy, PolicyConfig, StepResult, UndoReport } from './types.ts';
2
+ export declare const DEFAULT_POLICY: PolicyConfig;
3
+ export declare const GENESIS_HASH: string;
4
+ export declare const EMPTY_SNAPSHOT_HASH: string;
5
+ export declare const GLOBAL_SCOPE_HASH: string;
6
+ export declare const RECENT_OPS_LIMIT = 64;
7
+ export declare const RECENT_ARCHIVED_ATTEMPTS_LIMIT = 32;
8
+ export declare const RECENT_SPENT_APPROVALS_LIMIT = 64;
9
+ export declare const RECENT_CLUSTERS_LIMIT = 64;
10
+ export declare const MAX_RETAINED_BATCHES = 128;
11
+ export declare const MAX_RETAINED_EFFECTS = 256;
12
+ export declare function slotKey(scopeId: string, classId: string, objectId: string, field: string): string;
13
+ export declare function computePolicyHash(policy: PolicyConfig): string;
14
+ export declare function pinMatches(pin: PinPolicy, scopeId: string, classId: string): boolean;
15
+ export declare function leaseMatches(lease: Lease2D, scopeId: string, classId: string): boolean;
16
+ export declare function activeLeasesAt(leases: readonly Lease2D[], nowMs: number): readonly Lease2D[];
17
+ export declare function activePinsAt(pins: readonly PinPolicy[], nowMs: number): readonly PinPolicy[];
18
+ export declare function computeScopeHash(state: KernelState, scopeId: string, classId: string, atNowMs?: number): string;
19
+ /**
20
+ * Epoch that decides whether agent work in a scope is still valid.
21
+ * Scope `*` depends on every human action, so it uses the global epoch.
22
+ * Any other scope counts its own human actions plus the global ones (key `*`).
23
+ */
24
+ export declare function scopeEpochOf(state: KernelState, scopeId: string): number;
25
+ export declare function bumpScopeEpoch(scopeEpochs: Readonly<Record<string, number>>, scopeId: string): Readonly<Record<string, number>>;
26
+ export declare function pauseUnlessHalted(status: KernelState['taskStatus']): KernelState['taskStatus'];
27
+ export declare function sortIntents(intents: readonly Intent[]): readonly Intent[];
28
+ export declare function commitEntry(prevState: KernelState, nextStateDraft: KernelState, envelope: EventEnvelope, payloadHash: string, applied: boolean, decision: Decision, intents: readonly Intent[], scopeId: string, classId: string, diffHash: string | null, inputSnapshotHash: string, undoReport?: UndoReport, skipOpIndex?: boolean): StepResult;
29
+ export declare function recordFailStreak(state: KernelState, reason: string): {
30
+ nextState: KernelState;
31
+ decision: Decision;
32
+ };
33
+ export declare function recordConflictStreak(state: KernelState, reason: string): {
34
+ nextState: KernelState;
35
+ decision: Decision;
36
+ };
37
+ export declare function replaceAttempt(attempts: readonly AttemptState[], updated: AttemptState): readonly AttemptState[];
38
+ /**
39
+ * Removes a finished or aborted attempt from activeAttempts and keeps it in a bounded archive window.
40
+ */
41
+ export declare function archiveAttempt(state: KernelState, archived: AttemptState): {
42
+ readonly activeAttempts: readonly AttemptState[];
43
+ readonly recentArchivedAttempts: readonly AttemptState[];
44
+ };
45
+ export declare function replaceEffect(effects: readonly EffectRecord[], updated: EffectRecord): readonly EffectRecord[];
46
+ export declare function isPauseApprovalReason(reason: string | null): boolean;
@@ -0,0 +1,238 @@
1
+ import { HASH_ALG, compareUtf16, hashCanonical, sortDeterministically } from './jcs.js';
2
+ export const DEFAULT_POLICY = {
3
+ schemaVersion: 1,
4
+ maxAttempts: 20,
5
+ maxFailStreak: 3,
6
+ maxConflictStreak: 5,
7
+ maxCpuMs: 60_000,
8
+ maxCostMicroUnits: 10_000_000,
9
+ maxReconcileAttempts: 3,
10
+ undoWindowTtlMs: 3_600_000,
11
+ defaultLeaseTtlMs: 30_000,
12
+ maxConcurrentPerScope: 4,
13
+ resourcePoolCapacity: {
14
+ inferenceSlots: 4,
15
+ witnessSlots: 4,
16
+ mutationSlots: 6,
17
+ },
18
+ minImprovementMicroUnits: 1,
19
+ escalatePartialToC2: true,
20
+ denyPartial: false,
21
+ escalateSoftPinToC2: false,
22
+ enforceApprovalSignature: true,
23
+ enforceAutonomyLadder: true,
24
+ maxEventBytes: 65_536,
25
+ requiredWitnessStages: ['L0', 'L1', 'L2', 'L3'],
26
+ };
27
+ export const GENESIS_HASH = '0'.repeat(64);
28
+ export const EMPTY_SNAPSHOT_HASH = hashCanonical('empty_snapshot', 1, null);
29
+ export const GLOBAL_SCOPE_HASH = hashCanonical('scope_global', 1, '*');
30
+ export const RECENT_OPS_LIMIT = 64;
31
+ export const RECENT_ARCHIVED_ATTEMPTS_LIMIT = 32;
32
+ export const RECENT_SPENT_APPROVALS_LIMIT = 64;
33
+ export const RECENT_CLUSTERS_LIMIT = 64;
34
+ export const MAX_RETAINED_BATCHES = 128;
35
+ export const MAX_RETAINED_EFFECTS = 256;
36
+ export function slotKey(scopeId, classId, objectId, field) {
37
+ return `${scopeId}\0${classId}\0${objectId}\0${field}`;
38
+ }
39
+ export function computePolicyHash(policy) {
40
+ return hashCanonical('policy', policy.schemaVersion, policy);
41
+ }
42
+ export function pinMatches(pin, scopeId, classId) {
43
+ const scopeOk = pin.scopeId === scopeId || pin.scopeId === '*';
44
+ const classOk = pin.classId === classId || pin.classId === '*';
45
+ return scopeOk && classOk;
46
+ }
47
+ export function leaseMatches(lease, scopeId, classId) {
48
+ if (lease.scopeId !== scopeId)
49
+ return false;
50
+ return lease.classId === '*' || classId === '*' || lease.classId === classId;
51
+ }
52
+ export function activeLeasesAt(leases, nowMs) {
53
+ return leases.filter((l) => l.expiresAtMs > nowMs);
54
+ }
55
+ export function activePinsAt(pins, nowMs) {
56
+ return pins.filter((p) => p.expiresAtMs === undefined || nowMs < p.expiresAtMs);
57
+ }
58
+ export function computeScopeHash(state, scopeId, classId, atNowMs = state.lastNowMs) {
59
+ if (scopeId === '*') {
60
+ return GLOBAL_SCOPE_HASH;
61
+ }
62
+ const relevantKeys = [];
63
+ const slotPrefix = `${scopeId}\0`;
64
+ for (const key of Object.keys(state.slots)) {
65
+ if (key.startsWith(slotPrefix)) {
66
+ relevantKeys.push(key);
67
+ }
68
+ }
69
+ relevantKeys.sort(compareUtf16);
70
+ const relevantSlots = [];
71
+ for (const key of relevantKeys) {
72
+ const slot = state.slots[key];
73
+ if (!slot)
74
+ continue;
75
+ if (classId === '*' || slot.classId === classId) {
76
+ relevantSlots.push(slot);
77
+ }
78
+ }
79
+ const relevantPins = sortDeterministically(activePinsAt(state.pins, atNowMs).filter((p) => pinMatches(p, scopeId, classId)), (p) => p.pinId);
80
+ return hashCanonical('scope', 1, { scopeId, classId, relevantSlots, relevantPins });
81
+ }
82
+ /**
83
+ * Epoch that decides whether agent work in a scope is still valid.
84
+ * Scope `*` depends on every human action, so it uses the global epoch.
85
+ * Any other scope counts its own human actions plus the global ones (key `*`).
86
+ */
87
+ export function scopeEpochOf(state, scopeId) {
88
+ if (scopeId === '*')
89
+ return state.epoch;
90
+ return (state.scopeEpochs[scopeId] ?? 0) + (state.scopeEpochs['*'] ?? 0);
91
+ }
92
+ export function bumpScopeEpoch(scopeEpochs, scopeId) {
93
+ return { ...scopeEpochs, [scopeId]: (scopeEpochs[scopeId] ?? 0) + 1 };
94
+ }
95
+ export function pauseUnlessHalted(status) {
96
+ return status === 'HALTED' ? 'HALTED' : 'PAUSED';
97
+ }
98
+ export function sortIntents(intents) {
99
+ return sortDeterministically(intents, (intent) => {
100
+ switch (intent.kind) {
101
+ case 'Verify':
102
+ return `0:${intent.verifyId}`;
103
+ case 'Deliver':
104
+ return `1:${intent.effectId}`;
105
+ case 'Reconcile':
106
+ return `2:${intent.effectId}`;
107
+ case 'Compensate':
108
+ return `3:${intent.compensationId}`;
109
+ }
110
+ });
111
+ }
112
+ function appendRecentOp(recentOps, record) {
113
+ const next = [...recentOps, record];
114
+ return next.length > RECENT_OPS_LIMIT ? next.slice(next.length - RECENT_OPS_LIMIT) : next;
115
+ }
116
+ export function commitEntry(prevState, nextStateDraft, envelope, payloadHash, applied, decision, intents, scopeId, classId, diffHash, inputSnapshotHash, undoReport, skipOpIndex = false) {
117
+ const nextSeq = prevState.serverSeq + 1;
118
+ const scopeHash = computeScopeHash(nextStateDraft, scopeId, classId, envelope.nowMs);
119
+ const entryWithoutHash = {
120
+ schemaVersion: 1,
121
+ hashAlg: HASH_ALG,
122
+ serverSeq: nextSeq,
123
+ opId: envelope.opId,
124
+ payloadHash,
125
+ timestampMs: envelope.nowMs,
126
+ origin: envelope.auth.origin,
127
+ scopeId,
128
+ classId,
129
+ epoch: nextStateDraft.epoch,
130
+ scopeHash,
131
+ inputSnapshotHash,
132
+ diffHash,
133
+ kind: envelope.event.kind,
134
+ applied,
135
+ decision,
136
+ prevEntryHash: prevState.lastEntryHash,
137
+ ...(undoReport !== undefined ? { undoReport } : {}),
138
+ };
139
+ const entryHash = hashCanonical('log_entry', 1, entryWithoutHash);
140
+ const logEntry = {
141
+ ...entryWithoutHash,
142
+ entryHash,
143
+ };
144
+ const nextRecentOps = skipOpIndex
145
+ ? nextStateDraft.recentOps
146
+ : appendRecentOp(nextStateDraft.recentOps, {
147
+ opId: envelope.opId,
148
+ payloadHash,
149
+ decision,
150
+ applied,
151
+ serverSeq: nextSeq,
152
+ ...(undoReport !== undefined ? { undoReport } : {}),
153
+ });
154
+ const finalState = {
155
+ ...nextStateDraft,
156
+ serverSeq: nextSeq,
157
+ lastNowMs: Math.max(prevState.lastNowMs, envelope.nowMs),
158
+ lastEntryHash: entryHash,
159
+ recentOps: nextRecentOps,
160
+ metrics: {
161
+ ...nextStateDraft.metrics,
162
+ rejectedCount: nextStateDraft.metrics.rejectedCount + (applied ? 0 : 1),
163
+ },
164
+ };
165
+ return {
166
+ state: finalState,
167
+ decision,
168
+ intents: sortIntents(intents),
169
+ logEntry,
170
+ idempotentReplay: false,
171
+ schemaRejected: false,
172
+ ...(undoReport !== undefined ? { undoReport } : {}),
173
+ };
174
+ }
175
+ export function recordFailStreak(state, reason) {
176
+ const nextFail = state.budgets.failStreak + 1;
177
+ const shouldHalt = nextFail >= state.policy.maxFailStreak;
178
+ const decision = shouldHalt
179
+ ? { code: 'HALT', reason: `FAIL_STREAK_EXCEEDED:${reason}` }
180
+ : { code: 'REJECT', reason };
181
+ return {
182
+ decision,
183
+ nextState: {
184
+ ...state,
185
+ taskStatus: shouldHalt ? 'HALTED' : state.taskStatus,
186
+ haltReason: shouldHalt ? `FAIL_STREAK_EXCEEDED:${reason}` : state.haltReason,
187
+ budgets: {
188
+ ...state.budgets,
189
+ failStreak: nextFail,
190
+ },
191
+ },
192
+ };
193
+ }
194
+ export function recordConflictStreak(state, reason) {
195
+ const nextConflict = state.budgets.conflictStreak + 1;
196
+ const shouldPause = nextConflict >= state.policy.maxConflictStreak;
197
+ const decision = shouldPause
198
+ ? { code: 'PAUSE', reason: `CONTENTION_LIMIT:${reason}` }
199
+ : { code: 'REJECT', reason };
200
+ return {
201
+ decision,
202
+ nextState: {
203
+ ...state,
204
+ taskStatus: shouldPause && state.taskStatus === 'ACTIVE' ? 'PAUSED' : state.taskStatus,
205
+ pauseReason: shouldPause && state.taskStatus === 'ACTIVE'
206
+ ? `CONTENTION_LIMIT:${reason}`
207
+ : state.pauseReason,
208
+ budgets: {
209
+ ...state.budgets,
210
+ conflictStreak: nextConflict,
211
+ },
212
+ },
213
+ };
214
+ }
215
+ export function replaceAttempt(attempts, updated) {
216
+ return attempts.map((a) => (a.attemptId === updated.attemptId ? updated : a));
217
+ }
218
+ /**
219
+ * Removes a finished or aborted attempt from activeAttempts and keeps it in a bounded archive window.
220
+ */
221
+ export function archiveAttempt(state, archived) {
222
+ const activeAttempts = state.activeAttempts.filter((a) => a.attemptId !== archived.attemptId);
223
+ const appended = [...state.recentArchivedAttempts, archived];
224
+ const recentArchivedAttempts = appended.length > RECENT_ARCHIVED_ATTEMPTS_LIMIT
225
+ ? appended.slice(appended.length - RECENT_ARCHIVED_ATTEMPTS_LIMIT)
226
+ : appended;
227
+ return { activeAttempts, recentArchivedAttempts };
228
+ }
229
+ export function replaceEffect(effects, updated) {
230
+ return effects.map((e) => (e.effectId === updated.effectId ? updated : e));
231
+ }
232
+ export function isPauseApprovalReason(reason) {
233
+ return (reason === 'APPROVAL_REQUIRED' ||
234
+ reason === 'PARTIAL_INPUT_APPROVAL' ||
235
+ reason === 'COST_REGRESSION_APPROVAL' ||
236
+ reason === 'IRREVERSIBLE_APPROVAL' ||
237
+ reason === 'SOFT_PIN_APPROVAL');
238
+ }