certal 0.0.0-stage → 0.1.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.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +32 -0
  3. package/LICENSE +21 -0
  4. package/README.md +277 -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 +73 -0
  11. package/dist/adapters/commands.js +185 -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 +53 -0
  15. package/dist/adapters/file-watcher.js +142 -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 +438 -0
  22. package/dist/adapters/operator-auth.d.ts +47 -0
  23. package/dist/adapters/operator-auth.js +72 -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 +386 -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 +70 -0
  57. package/dist/mcp/server.js +508 -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 +204 -0
  67. package/dist/runtime/store.js +746 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +40 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +22 -0
  72. package/presets/vibeops.json +34 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,746 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { HASH_ALG, computeStateHash, createInitialState, hashCanonical, jcs, step, } from '../kernel/index.js';
3
+ function intentsToOutboxRecords(intents, nowMs) {
4
+ const out = [];
5
+ for (const intent of intents) {
6
+ if (intent.kind === 'Deliver') {
7
+ out.push({
8
+ effectId: intent.effectId,
9
+ effectKind: 'Deliver',
10
+ batchId: intent.batchId,
11
+ scopeId: intent.scopeId,
12
+ classId: intent.classId,
13
+ recipientId: intent.recipientId,
14
+ supportsCas: intent.supportsCas,
15
+ payloadJson: jcs(intent.payload),
16
+ scopeHash: intent.postCommitScopeHash,
17
+ approvalExpiresAtMs: intent.approvalExpiresAtMs,
18
+ status: 'INTENT',
19
+ attempts: 0,
20
+ nextRetryAtMs: nowMs,
21
+ updatedAtMs: nowMs,
22
+ });
23
+ }
24
+ else if (intent.kind === 'Compensate') {
25
+ out.push({
26
+ effectId: intent.compensationId,
27
+ effectKind: 'Compensate',
28
+ batchId: intent.originalEffectId,
29
+ scopeId: '*',
30
+ classId: '*',
31
+ recipientId: intent.recipientId,
32
+ supportsCas: intent.supportsCas,
33
+ payloadJson: jcs(intent.inversePayload),
34
+ scopeHash: null,
35
+ approvalExpiresAtMs: null,
36
+ status: 'INTENT',
37
+ attempts: 0,
38
+ nextRetryAtMs: nowMs,
39
+ updatedAtMs: nowMs,
40
+ });
41
+ }
42
+ }
43
+ return out;
44
+ }
45
+ function resolveOutboxStatusFromStep(entry, envelope, effectStatusAfter) {
46
+ if (envelope.event.kind !== 'EffectTransition')
47
+ return null;
48
+ const effId = envelope.event.effectId;
49
+ if (effectStatusAfter !== undefined && effectStatusAfter !== null) {
50
+ switch (effectStatusAfter) {
51
+ case 'RECONCILE_EXHAUSTED':
52
+ return { effectId: effId, status: 'RECONCILE_EXHAUSTED' };
53
+ case 'UNKNOWN':
54
+ case 'COMP_UNKNOWN':
55
+ return { effectId: effId, status: 'UNKNOWN' };
56
+ case 'APPLIED':
57
+ case 'COMPENSATED':
58
+ return { effectId: effId, status: 'APPLIED' };
59
+ case 'DELIVERY_FAILED':
60
+ case 'COMP_FAILED':
61
+ case 'MANUAL_COMPENSATION_REQUIRED':
62
+ return { effectId: effId, status: 'REFUSED' };
63
+ case 'ABORTED_EXPIRED':
64
+ return { effectId: effId, status: 'EXPIRED_BEFORE_SEND' };
65
+ default:
66
+ return null;
67
+ }
68
+ }
69
+ if (entry.decision.reason === 'RECONCILE_EXHAUSTED') {
70
+ return { effectId: effId, status: 'RECONCILE_EXHAUSTED' };
71
+ }
72
+ if (entry.decision.reason === 'APPROVAL_EXPIRED_BEFORE_SEND') {
73
+ return { effectId: effId, status: 'EXPIRED_BEFORE_SEND' };
74
+ }
75
+ if (!entry.applied)
76
+ return null;
77
+ switch (envelope.event.outcome) {
78
+ case 'APPLIED':
79
+ return { effectId: effId, status: 'APPLIED' };
80
+ case 'REFUSED':
81
+ return { effectId: effId, status: 'REFUSED' };
82
+ case 'UNKNOWN':
83
+ return { effectId: effId, status: 'UNKNOWN' };
84
+ case 'EXPIRED_BEFORE_SEND':
85
+ return { effectId: effId, status: 'EXPIRED_BEFORE_SEND' };
86
+ default:
87
+ return null;
88
+ }
89
+ }
90
+ function toOpIndexRecord(entry) {
91
+ return {
92
+ opId: entry.opId,
93
+ payloadHash: entry.payloadHash,
94
+ decision: entry.decision,
95
+ applied: entry.applied,
96
+ serverSeq: entry.serverSeq,
97
+ ...(entry.undoReport !== undefined ? { undoReport: entry.undoReport } : {}),
98
+ };
99
+ }
100
+ /**
101
+ * In-memory EventStore + OutboxStore + BlobStore for fast tests and interleaving search.
102
+ */
103
+ export class InMemoryStore {
104
+ lastNowMs = 0;
105
+ logs = [];
106
+ opIndex = new Map();
107
+ spentApprovals = new Map();
108
+ clustersIndex = new Map();
109
+ outbox = new Map();
110
+ checkpoints = [];
111
+ blobs = new Map();
112
+ getLastPersistedNowMs() {
113
+ return this.lastNowMs;
114
+ }
115
+ getLastServerSeq() {
116
+ const last = this.logs[this.logs.length - 1];
117
+ return last ? last.entry.serverSeq : 0;
118
+ }
119
+ lookupOpId(opId) {
120
+ return this.opIndex.get(opId) ?? null;
121
+ }
122
+ isApprovalSpent(approvalId) {
123
+ return this.spentApprovals.has(approvalId);
124
+ }
125
+ lookupClusterOutcome(toolId, clusterId) {
126
+ const rec = this.clustersIndex.get(`${toolId}\0${clusterId}`);
127
+ if (!rec)
128
+ return null;
129
+ return rec.firstViolationSeq !== null ? 'VIOLATION' : 'CLEAN';
130
+ }
131
+ readOpIndexUpTo(maxSeq) {
132
+ const out = [];
133
+ for (const rec of this.opIndex.values()) {
134
+ if (rec.serverSeq <= maxSeq)
135
+ out.push(rec);
136
+ }
137
+ return out;
138
+ }
139
+ readSpentApprovalsUpTo(maxSeq) {
140
+ const out = [];
141
+ for (const [id, seq] of this.spentApprovals.entries()) {
142
+ if (seq <= maxSeq)
143
+ out.push(id);
144
+ }
145
+ return out;
146
+ }
147
+ readClustersUpTo(maxSeq) {
148
+ const out = [];
149
+ for (const rec of this.clustersIndex.values()) {
150
+ const hasViolation = rec.firstViolationSeq !== null && rec.firstViolationSeq <= maxSeq;
151
+ const hasClean = rec.firstCleanSeq !== null && rec.firstCleanSeq <= maxSeq;
152
+ if (hasViolation) {
153
+ out.push({ toolId: rec.toolId, clusterId: rec.clusterId, outcome: 'VIOLATION' });
154
+ }
155
+ else if (hasClean) {
156
+ out.push({ toolId: rec.toolId, clusterId: rec.clusterId, outcome: 'CLEAN' });
157
+ }
158
+ }
159
+ return out;
160
+ }
161
+ commitStep(entry, envelope, intents, nowMs, extras) {
162
+ this.logs.push({ entry, envelope });
163
+ if (!this.opIndex.has(entry.opId)) {
164
+ this.opIndex.set(entry.opId, toOpIndexRecord(entry));
165
+ }
166
+ if (extras?.spentApprovalId) {
167
+ this.spentApprovals.set(extras.spentApprovalId, entry.serverSeq);
168
+ }
169
+ if (extras?.clusterUpdate) {
170
+ const cu = extras.clusterUpdate;
171
+ const key = `${cu.toolId}\0${cu.clusterId}`;
172
+ const existing = this.clustersIndex.get(key);
173
+ if (cu.outcome === 'CLEAN') {
174
+ if (!existing) {
175
+ this.clustersIndex.set(key, {
176
+ toolId: cu.toolId,
177
+ clusterId: cu.clusterId,
178
+ firstCleanSeq: entry.serverSeq,
179
+ firstViolationSeq: null,
180
+ });
181
+ }
182
+ }
183
+ else {
184
+ this.clustersIndex.set(key, {
185
+ toolId: cu.toolId,
186
+ clusterId: cu.clusterId,
187
+ firstCleanSeq: existing?.firstCleanSeq ?? null,
188
+ firstViolationSeq: existing?.firstViolationSeq ?? entry.serverSeq,
189
+ });
190
+ }
191
+ }
192
+ if (entry.applied && extras?.pendingBlobs) {
193
+ for (const blob of extras.pendingBlobs) {
194
+ if (!this.blobs.has(blob.blobHash)) {
195
+ this.blobs.set(blob.blobHash, blob.payloadJson);
196
+ }
197
+ }
198
+ }
199
+ if (nowMs > this.lastNowMs) {
200
+ this.lastNowMs = nowMs;
201
+ }
202
+ const outboxStatusUpdate = resolveOutboxStatusFromStep(entry, envelope, extras?.effectStatusAfter);
203
+ if (outboxStatusUpdate) {
204
+ const existing = this.outbox.get(outboxStatusUpdate.effectId);
205
+ if (existing) {
206
+ this.outbox.set(outboxStatusUpdate.effectId, {
207
+ ...existing,
208
+ status: outboxStatusUpdate.status,
209
+ updatedAtMs: nowMs,
210
+ });
211
+ }
212
+ }
213
+ for (const rec of intentsToOutboxRecords(intents, nowMs)) {
214
+ if (!this.outbox.has(rec.effectId)) {
215
+ this.outbox.set(rec.effectId, rec);
216
+ }
217
+ }
218
+ }
219
+ readLogFrom(fromSeqExclusive) {
220
+ return this.logs.filter((row) => row.entry.serverSeq > fromSeqExclusive);
221
+ }
222
+ saveCheckpoint(snapshot) {
223
+ this.checkpoints.push(snapshot);
224
+ }
225
+ loadLatestCheckpoint() {
226
+ return this.checkpoints[this.checkpoints.length - 1] ?? null;
227
+ }
228
+ listActionable(nowMs) {
229
+ const out = [];
230
+ for (const rec of this.outbox.values()) {
231
+ if ((rec.status === 'INTENT' || rec.status === 'UNKNOWN') && rec.nextRetryAtMs <= nowMs) {
232
+ out.push(rec);
233
+ }
234
+ }
235
+ return out.sort((a, b) => a.effectId.localeCompare(b.effectId));
236
+ }
237
+ getOutboxRecord(effectId) {
238
+ return this.outbox.get(effectId) ?? null;
239
+ }
240
+ recoverInFlight(nowMs) {
241
+ const recovered = [];
242
+ for (const [id, rec] of this.outbox.entries()) {
243
+ if (rec.status === 'IN_FLIGHT') {
244
+ const updated = {
245
+ ...rec,
246
+ status: 'UNKNOWN',
247
+ nextRetryAtMs: nowMs,
248
+ updatedAtMs: nowMs,
249
+ };
250
+ this.outbox.set(id, updated);
251
+ recovered.push(updated);
252
+ }
253
+ }
254
+ return recovered.sort((a, b) => a.effectId.localeCompare(b.effectId));
255
+ }
256
+ transitionToInFlight(effectId, nowMs) {
257
+ const rec = this.outbox.get(effectId);
258
+ if (!rec || (rec.status !== 'INTENT' && rec.status !== 'UNKNOWN')) {
259
+ return null;
260
+ }
261
+ const updated = {
262
+ ...rec,
263
+ status: 'IN_FLIGHT',
264
+ attempts: rec.attempts + 1,
265
+ updatedAtMs: nowMs,
266
+ };
267
+ this.outbox.set(effectId, updated);
268
+ if (nowMs > this.lastNowMs) {
269
+ this.lastNowMs = nowMs;
270
+ }
271
+ return updated;
272
+ }
273
+ setNextRetryAt(effectId, nextRetryAtMs, nowMs) {
274
+ const rec = this.outbox.get(effectId);
275
+ if (!rec)
276
+ return;
277
+ this.outbox.set(effectId, { ...rec, nextRetryAtMs, updatedAtMs: nowMs });
278
+ }
279
+ putBlob(data) {
280
+ const serialized = jcs(data);
281
+ const blobHash = hashCanonical('blob', 1, data);
282
+ const byteSize = Buffer.byteLength(serialized, 'utf8');
283
+ this.blobs.set(blobHash, serialized);
284
+ return { blobHash, byteSize };
285
+ }
286
+ getBlob(blobHash) {
287
+ const raw = this.blobs.get(blobHash);
288
+ return raw !== undefined ? JSON.parse(raw) : null;
289
+ }
290
+ replay(hooks) {
291
+ return replayFromStore(this, hooks);
292
+ }
293
+ close() {
294
+ // Nothing to release
295
+ }
296
+ }
297
+ /**
298
+ * EventStore + OutboxStore + BlobStore on the built-in `node:sqlite` in WAL mode.
299
+ * Statements are prepared once in the constructor. One writer, PRAGMA busy_timeout = 5000.
300
+ */
301
+ export class SQLiteStore {
302
+ db;
303
+ closed = false;
304
+ cachedLastNowMs;
305
+ stmtGetLastSeq;
306
+ stmtLookupOpId;
307
+ stmtIsApprovalSpent;
308
+ stmtLookupCluster;
309
+ stmtReadOpIndexUpTo;
310
+ stmtReadSpentUpTo;
311
+ stmtReadClustersUpTo;
312
+ stmtInsertLog;
313
+ stmtInsertOpIndex;
314
+ stmtInsertSpentApproval;
315
+ stmtUpsertClusterClean;
316
+ stmtUpsertClusterViolation;
317
+ stmtInsertBlob;
318
+ stmtGetBlob;
319
+ stmtUpdateMetaNow;
320
+ stmtInsertOutboxIgnore;
321
+ stmtUpdateOutboxStatus;
322
+ stmtUpdateOutboxRetry;
323
+ stmtReadLogFrom;
324
+ stmtSaveCheckpoint;
325
+ stmtLoadLatestCheckpoint;
326
+ stmtListActionable;
327
+ stmtGetOutbox;
328
+ stmtSelectInFlight;
329
+ stmtRecoverInFlight;
330
+ stmtMarkInFlight;
331
+ constructor(dbPath) {
332
+ this.db = new DatabaseSync(dbPath);
333
+ // The busy timeout comes first: the statements below need a lock, and a second process that opens
334
+ // the file while the writer is busy must wait instead of failing with "database is locked".
335
+ this.db.exec(`
336
+ PRAGMA busy_timeout = 5000;
337
+ PRAGMA journal_mode = WAL;
338
+ PRAGMA synchronous = FULL;
339
+ PRAGMA foreign_keys = ON;
340
+
341
+ CREATE TABLE IF NOT EXISTS meta (
342
+ key TEXT PRIMARY KEY,
343
+ value TEXT NOT NULL
344
+ );
345
+
346
+ CREATE TABLE IF NOT EXISTS log_entries (
347
+ server_seq INTEGER PRIMARY KEY,
348
+ op_id TEXT NOT NULL,
349
+ entry_hash TEXT NOT NULL,
350
+ prev_entry_hash TEXT NOT NULL,
351
+ entry_json TEXT NOT NULL,
352
+ envelope_json TEXT NOT NULL
353
+ );
354
+
355
+ CREATE TABLE IF NOT EXISTS op_index (
356
+ op_id TEXT PRIMARY KEY,
357
+ payload_hash TEXT NOT NULL,
358
+ decision_json TEXT NOT NULL,
359
+ applied INTEGER NOT NULL,
360
+ server_seq INTEGER NOT NULL,
361
+ undo_report_json TEXT
362
+ );
363
+ CREATE INDEX IF NOT EXISTS idx_op_index_seq ON op_index (server_seq);
364
+
365
+ CREATE TABLE IF NOT EXISTS spent_approvals (
366
+ approval_id TEXT PRIMARY KEY,
367
+ server_seq INTEGER NOT NULL
368
+ );
369
+ CREATE INDEX IF NOT EXISTS idx_spent_approvals_seq ON spent_approvals (server_seq);
370
+
371
+ CREATE TABLE IF NOT EXISTS clusters_index (
372
+ tool_id TEXT NOT NULL,
373
+ cluster_id TEXT NOT NULL,
374
+ first_clean_seq INTEGER,
375
+ first_violation_seq INTEGER,
376
+ PRIMARY KEY (tool_id, cluster_id)
377
+ );
378
+
379
+ CREATE TABLE IF NOT EXISTS outbox_intents (
380
+ effect_id TEXT PRIMARY KEY,
381
+ effect_kind TEXT NOT NULL,
382
+ batch_id TEXT NOT NULL,
383
+ scope_id TEXT NOT NULL,
384
+ class_id TEXT NOT NULL,
385
+ recipient_id TEXT NOT NULL,
386
+ supports_cas INTEGER NOT NULL,
387
+ payload_json TEXT NOT NULL,
388
+ scope_hash TEXT,
389
+ approval_expires_at_ms INTEGER,
390
+ status TEXT NOT NULL,
391
+ attempts INTEGER NOT NULL,
392
+ next_retry_at_ms INTEGER NOT NULL,
393
+ updated_at_ms INTEGER NOT NULL
394
+ );
395
+
396
+ CREATE TABLE IF NOT EXISTS checkpoints (
397
+ server_seq INTEGER PRIMARY KEY,
398
+ state_hash TEXT NOT NULL,
399
+ snapshot_json TEXT NOT NULL,
400
+ created_at_ms INTEGER NOT NULL
401
+ );
402
+
403
+ CREATE TABLE IF NOT EXISTS blobs (
404
+ blob_hash TEXT PRIMARY KEY,
405
+ byte_size INTEGER NOT NULL,
406
+ payload_json TEXT NOT NULL
407
+ );
408
+
409
+ INSERT OR IGNORE INTO meta (key, value) VALUES ('last_persisted_now_ms', '0');
410
+ `);
411
+ const rowNow = this.db
412
+ .prepare("SELECT value FROM meta WHERE key = 'last_persisted_now_ms'")
413
+ .get();
414
+ this.cachedLastNowMs = rowNow ? Number(rowNow.value) : 0;
415
+ this.stmtGetLastSeq = this.db.prepare('SELECT COALESCE(MAX(server_seq), 0) AS seq FROM log_entries');
416
+ this.stmtLookupOpId = this.db.prepare('SELECT op_id, payload_hash, decision_json, applied, server_seq, undo_report_json FROM op_index WHERE op_id = ?');
417
+ this.stmtIsApprovalSpent = this.db.prepare('SELECT 1 AS found FROM spent_approvals WHERE approval_id = ?');
418
+ this.stmtLookupCluster = this.db.prepare('SELECT first_clean_seq, first_violation_seq FROM clusters_index WHERE tool_id = ? AND cluster_id = ?');
419
+ this.stmtReadOpIndexUpTo = this.db.prepare('SELECT op_id, payload_hash, decision_json, applied, server_seq, undo_report_json FROM op_index WHERE server_seq <= ?');
420
+ this.stmtReadSpentUpTo = this.db.prepare('SELECT approval_id FROM spent_approvals WHERE server_seq <= ?');
421
+ this.stmtReadClustersUpTo = this.db.prepare(`SELECT tool_id, cluster_id, first_clean_seq, first_violation_seq
422
+ FROM clusters_index
423
+ WHERE (first_clean_seq IS NOT NULL AND first_clean_seq <= ?)
424
+ OR (first_violation_seq IS NOT NULL AND first_violation_seq <= ?)`);
425
+ this.stmtInsertLog = this.db.prepare(`INSERT INTO log_entries (server_seq, op_id, entry_hash, prev_entry_hash, entry_json, envelope_json)
426
+ VALUES (?, ?, ?, ?, ?, ?)`);
427
+ this.stmtInsertOpIndex = this.db.prepare(`INSERT OR IGNORE INTO op_index (op_id, payload_hash, decision_json, applied, server_seq, undo_report_json)
428
+ VALUES (?, ?, ?, ?, ?, ?)`);
429
+ this.stmtInsertSpentApproval = this.db.prepare('INSERT OR IGNORE INTO spent_approvals (approval_id, server_seq) VALUES (?, ?)');
430
+ this.stmtUpsertClusterClean = this.db.prepare(`INSERT INTO clusters_index (tool_id, cluster_id, first_clean_seq, first_violation_seq)
431
+ VALUES (?, ?, ?, NULL)
432
+ ON CONFLICT(tool_id, cluster_id) DO NOTHING`);
433
+ this.stmtUpsertClusterViolation = this.db.prepare(`INSERT INTO clusters_index (tool_id, cluster_id, first_clean_seq, first_violation_seq)
434
+ VALUES (?, ?, NULL, ?)
435
+ ON CONFLICT(tool_id, cluster_id) DO UPDATE SET
436
+ first_violation_seq = COALESCE(clusters_index.first_violation_seq, excluded.first_violation_seq)`);
437
+ this.stmtInsertBlob = this.db.prepare('INSERT OR IGNORE INTO blobs (blob_hash, byte_size, payload_json) VALUES (?, ?, ?)');
438
+ this.stmtGetBlob = this.db.prepare('SELECT payload_json FROM blobs WHERE blob_hash = ?');
439
+ this.stmtUpdateMetaNow = this.db.prepare("UPDATE meta SET value = ? WHERE key = 'last_persisted_now_ms'");
440
+ this.stmtInsertOutboxIgnore = this.db.prepare(`INSERT OR IGNORE INTO outbox_intents (
441
+ effect_id, effect_kind, batch_id, scope_id, class_id, recipient_id, supports_cas, payload_json,
442
+ scope_hash, approval_expires_at_ms, status, attempts, next_retry_at_ms, updated_at_ms
443
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
444
+ this.stmtUpdateOutboxStatus = this.db.prepare('UPDATE outbox_intents SET status = ?, updated_at_ms = ? WHERE effect_id = ?');
445
+ this.stmtUpdateOutboxRetry = this.db.prepare('UPDATE outbox_intents SET next_retry_at_ms = ?, updated_at_ms = ? WHERE effect_id = ?');
446
+ this.stmtReadLogFrom = this.db.prepare('SELECT entry_json, envelope_json FROM log_entries WHERE server_seq > ? ORDER BY server_seq ASC');
447
+ this.stmtSaveCheckpoint = this.db.prepare(`INSERT OR REPLACE INTO checkpoints (server_seq, state_hash, snapshot_json, created_at_ms)
448
+ VALUES (?, ?, ?, ?)`);
449
+ this.stmtLoadLatestCheckpoint = this.db.prepare('SELECT snapshot_json FROM checkpoints ORDER BY server_seq DESC LIMIT 1');
450
+ this.stmtListActionable = this.db.prepare(`SELECT * FROM outbox_intents
451
+ WHERE (status = 'INTENT' OR status = 'UNKNOWN') AND next_retry_at_ms <= ?
452
+ ORDER BY effect_id ASC`);
453
+ this.stmtGetOutbox = this.db.prepare('SELECT * FROM outbox_intents WHERE effect_id = ?');
454
+ this.stmtSelectInFlight = this.db.prepare("SELECT * FROM outbox_intents WHERE status = 'IN_FLIGHT' ORDER BY effect_id ASC");
455
+ this.stmtRecoverInFlight = this.db.prepare(`UPDATE outbox_intents
456
+ SET status = 'UNKNOWN', next_retry_at_ms = ?, updated_at_ms = ?
457
+ WHERE status = 'IN_FLIGHT'`);
458
+ this.stmtMarkInFlight = this.db.prepare(`UPDATE outbox_intents
459
+ SET status = 'IN_FLIGHT', attempts = ?, updated_at_ms = ?
460
+ WHERE effect_id = ?`);
461
+ }
462
+ getLastPersistedNowMs() {
463
+ return this.cachedLastNowMs;
464
+ }
465
+ getLastServerSeq() {
466
+ const row = this.stmtGetLastSeq.get();
467
+ return row.seq;
468
+ }
469
+ mapOpIndexRow(row) {
470
+ const undoReport = row.undo_report_json !== null ? JSON.parse(row.undo_report_json) : undefined;
471
+ return {
472
+ opId: row.op_id,
473
+ payloadHash: row.payload_hash,
474
+ decision: JSON.parse(row.decision_json),
475
+ applied: row.applied === 1,
476
+ serverSeq: row.server_seq,
477
+ ...(undoReport !== undefined ? { undoReport } : {}),
478
+ };
479
+ }
480
+ lookupOpId(opId) {
481
+ const row = this.stmtLookupOpId.get(opId);
482
+ return row ? this.mapOpIndexRow(row) : null;
483
+ }
484
+ isApprovalSpent(approvalId) {
485
+ const row = this.stmtIsApprovalSpent.get(approvalId);
486
+ return row !== undefined;
487
+ }
488
+ lookupClusterOutcome(toolId, clusterId) {
489
+ const row = this.stmtLookupCluster.get(toolId, clusterId);
490
+ if (!row)
491
+ return null;
492
+ return row.first_violation_seq !== null ? 'VIOLATION' : 'CLEAN';
493
+ }
494
+ readOpIndexUpTo(maxSeq) {
495
+ const rows = this.stmtReadOpIndexUpTo.all(maxSeq);
496
+ return rows.map((r) => this.mapOpIndexRow(r));
497
+ }
498
+ readSpentApprovalsUpTo(maxSeq) {
499
+ const rows = this.stmtReadSpentUpTo.all(maxSeq);
500
+ return rows.map((r) => r.approval_id);
501
+ }
502
+ readClustersUpTo(maxSeq) {
503
+ const rows = this.stmtReadClustersUpTo.all(maxSeq, maxSeq);
504
+ return rows.map((r) => ({
505
+ toolId: r.tool_id,
506
+ clusterId: r.cluster_id,
507
+ outcome: r.first_violation_seq !== null && r.first_violation_seq <= maxSeq ? 'VIOLATION' : 'CLEAN',
508
+ }));
509
+ }
510
+ commitStep(entry, envelope, intents, nowMs, extras) {
511
+ this.db.exec('BEGIN IMMEDIATE');
512
+ try {
513
+ this.stmtInsertLog.run(entry.serverSeq, entry.opId, entry.entryHash, entry.prevEntryHash, jcs(entry), jcs(envelope));
514
+ this.stmtInsertOpIndex.run(entry.opId, entry.payloadHash, jcs(entry.decision), entry.applied ? 1 : 0, entry.serverSeq, entry.undoReport !== undefined ? jcs(entry.undoReport) : null);
515
+ if (extras?.spentApprovalId) {
516
+ this.stmtInsertSpentApproval.run(extras.spentApprovalId, entry.serverSeq);
517
+ }
518
+ if (extras?.clusterUpdate) {
519
+ const cu = extras.clusterUpdate;
520
+ if (cu.outcome === 'CLEAN') {
521
+ this.stmtUpsertClusterClean.run(cu.toolId, cu.clusterId, entry.serverSeq);
522
+ }
523
+ else {
524
+ this.stmtUpsertClusterViolation.run(cu.toolId, cu.clusterId, entry.serverSeq);
525
+ }
526
+ }
527
+ if (entry.applied && extras?.pendingBlobs) {
528
+ for (const blob of extras.pendingBlobs) {
529
+ this.stmtInsertBlob.run(blob.blobHash, blob.byteSize, blob.payloadJson);
530
+ }
531
+ }
532
+ if (nowMs > this.cachedLastNowMs) {
533
+ this.stmtUpdateMetaNow.run(String(nowMs));
534
+ this.cachedLastNowMs = nowMs;
535
+ }
536
+ const outboxStatusUpdate = resolveOutboxStatusFromStep(entry, envelope, extras?.effectStatusAfter);
537
+ if (outboxStatusUpdate) {
538
+ this.stmtUpdateOutboxStatus.run(outboxStatusUpdate.status, nowMs, outboxStatusUpdate.effectId);
539
+ }
540
+ for (const rec of intentsToOutboxRecords(intents, nowMs)) {
541
+ this.stmtInsertOutboxIgnore.run(rec.effectId, rec.effectKind, rec.batchId, rec.scopeId, rec.classId, rec.recipientId, rec.supportsCas ? 1 : 0, rec.payloadJson, rec.scopeHash, rec.approvalExpiresAtMs, rec.status, rec.attempts, rec.nextRetryAtMs, rec.updatedAtMs);
542
+ }
543
+ this.db.exec('COMMIT');
544
+ }
545
+ catch (err) {
546
+ this.db.exec('ROLLBACK');
547
+ throw err;
548
+ }
549
+ }
550
+ readLogFrom(fromSeqExclusive) {
551
+ const rows = this.stmtReadLogFrom.all(fromSeqExclusive);
552
+ return rows.map((r) => ({
553
+ entry: JSON.parse(r.entry_json),
554
+ envelope: JSON.parse(r.envelope_json),
555
+ }));
556
+ }
557
+ saveCheckpoint(snapshot) {
558
+ this.stmtSaveCheckpoint.run(snapshot.serverSeq, snapshot.stateHash, jcs(snapshot), snapshot.createdAtMs);
559
+ }
560
+ loadLatestCheckpoint() {
561
+ const row = this.stmtLoadLatestCheckpoint.get();
562
+ return row ? JSON.parse(row.snapshot_json) : null;
563
+ }
564
+ mapOutboxRow(row) {
565
+ return {
566
+ effectId: String(row.effect_id),
567
+ effectKind: row.effect_kind,
568
+ batchId: String(row.batch_id),
569
+ scopeId: String(row.scope_id),
570
+ classId: String(row.class_id),
571
+ recipientId: String(row.recipient_id),
572
+ supportsCas: Number(row.supports_cas) === 1,
573
+ payloadJson: String(row.payload_json),
574
+ scopeHash: row.scope_hash === null ? null : String(row.scope_hash),
575
+ approvalExpiresAtMs: row.approval_expires_at_ms === null ? null : Number(row.approval_expires_at_ms),
576
+ status: row.status,
577
+ attempts: Number(row.attempts),
578
+ nextRetryAtMs: Number(row.next_retry_at_ms),
579
+ updatedAtMs: Number(row.updated_at_ms),
580
+ };
581
+ }
582
+ listActionable(nowMs) {
583
+ const rows = this.stmtListActionable.all(nowMs);
584
+ return rows.map((r) => this.mapOutboxRow(r));
585
+ }
586
+ getOutboxRecord(effectId) {
587
+ const row = this.stmtGetOutbox.get(effectId);
588
+ return row ? this.mapOutboxRow(row) : null;
589
+ }
590
+ recoverInFlight(nowMs) {
591
+ this.db.exec('BEGIN IMMEDIATE');
592
+ try {
593
+ const rows = this.stmtSelectInFlight.all();
594
+ if (rows.length === 0) {
595
+ this.db.exec('COMMIT');
596
+ return [];
597
+ }
598
+ this.stmtRecoverInFlight.run(nowMs, nowMs);
599
+ this.db.exec('COMMIT');
600
+ return rows.map((r) => ({
601
+ ...this.mapOutboxRow(r),
602
+ status: 'UNKNOWN',
603
+ nextRetryAtMs: nowMs,
604
+ updatedAtMs: nowMs,
605
+ }));
606
+ }
607
+ catch (err) {
608
+ this.db.exec('ROLLBACK');
609
+ throw err;
610
+ }
611
+ }
612
+ transitionToInFlight(effectId, nowMs) {
613
+ this.db.exec('BEGIN IMMEDIATE');
614
+ try {
615
+ const row = this.stmtGetOutbox.get(effectId);
616
+ if (!row) {
617
+ this.db.exec('COMMIT');
618
+ return null;
619
+ }
620
+ const mapped = this.mapOutboxRow(row);
621
+ if (mapped.status !== 'INTENT' && mapped.status !== 'UNKNOWN') {
622
+ this.db.exec('COMMIT');
623
+ return null;
624
+ }
625
+ const nextAttempts = mapped.attempts + 1;
626
+ this.stmtMarkInFlight.run(nextAttempts, nowMs, effectId);
627
+ if (nowMs > this.cachedLastNowMs) {
628
+ this.stmtUpdateMetaNow.run(String(nowMs));
629
+ this.cachedLastNowMs = nowMs;
630
+ }
631
+ this.db.exec('COMMIT');
632
+ return {
633
+ ...mapped,
634
+ status: 'IN_FLIGHT',
635
+ attempts: nextAttempts,
636
+ updatedAtMs: nowMs,
637
+ };
638
+ }
639
+ catch (err) {
640
+ this.db.exec('ROLLBACK');
641
+ throw err;
642
+ }
643
+ }
644
+ setNextRetryAt(effectId, nextRetryAtMs, nowMs) {
645
+ this.stmtUpdateOutboxRetry.run(nextRetryAtMs, nowMs, effectId);
646
+ }
647
+ putBlob(data) {
648
+ const serialized = jcs(data);
649
+ const blobHash = hashCanonical('blob', 1, data);
650
+ const byteSize = Buffer.byteLength(serialized, 'utf8');
651
+ this.stmtInsertBlob.run(blobHash, byteSize, serialized);
652
+ return { blobHash, byteSize };
653
+ }
654
+ getBlob(blobHash) {
655
+ const row = this.stmtGetBlob.get(blobHash);
656
+ return row ? JSON.parse(row.payload_json) : null;
657
+ }
658
+ replay(hooks) {
659
+ return replayFromStore(this, hooks);
660
+ }
661
+ close() {
662
+ if (!this.closed) {
663
+ this.closed = true;
664
+ try {
665
+ this.db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
666
+ }
667
+ catch {
668
+ // Best effort while closing
669
+ }
670
+ this.db.close();
671
+ }
672
+ }
673
+ }
674
+ /**
675
+ * Rebuilds the kernel state from the store alone. The log starts from the default policy, and any
676
+ * other starting policy is the first log entry (see CertalRuntime), so a replay needs no configuration.
677
+ */
678
+ export function replayFromStore(store, hooks, options) {
679
+ const checkpoint = options?.fromGenesis ? null : store.loadLatestCheckpoint();
680
+ let state = checkpoint ? checkpoint.state : createInitialState();
681
+ const seenOps = new Map();
682
+ const spentSet = new Set();
683
+ const clusterMap = new Map();
684
+ if (checkpoint) {
685
+ if (checkpoint.hashAlg !== HASH_ALG) {
686
+ throw new Error(`UNSUPPORTED_HASH_ALG: ${String(checkpoint.hashAlg)}`);
687
+ }
688
+ const actualCpHash = computeStateHash(checkpoint.state);
689
+ if (actualCpHash !== checkpoint.stateHash) {
690
+ throw new Error('CHECKPOINT_HASH_MISMATCH');
691
+ }
692
+ // Read straight from the op_index, spent_approvals and clusters_index tables. No readLogFrom(0).
693
+ for (const rec of store.readOpIndexUpTo(checkpoint.serverSeq)) {
694
+ seenOps.set(rec.opId, rec);
695
+ }
696
+ for (const appId of store.readSpentApprovalsUpTo(checkpoint.serverSeq)) {
697
+ spentSet.add(appId);
698
+ }
699
+ for (const cl of store.readClustersUpTo(checkpoint.serverSeq)) {
700
+ clusterMap.set(`${cl.toolId}\0${cl.clusterId}`, cl.outcome);
701
+ }
702
+ }
703
+ const replayHooks = {
704
+ ...hooks,
705
+ lookupOpId: (opId) => seenOps.get(opId) ?? null,
706
+ isApprovalSpent: (approvalId) => spentSet.has(approvalId),
707
+ lookupClusterOutcome: (toolId, clusterId) => clusterMap.get(`${toolId}\0${clusterId}`) ?? null,
708
+ };
709
+ const rows = store.readLogFrom(state.serverSeq);
710
+ for (const row of rows) {
711
+ if (row.entry.hashAlg !== HASH_ALG) {
712
+ throw new Error(`UNSUPPORTED_HASH_ALG at seq=${row.entry.serverSeq}`);
713
+ }
714
+ if (row.entry.prevEntryHash !== state.lastEntryHash) {
715
+ throw new Error(`LOG_CHAIN_BROKEN at seq=${row.entry.serverSeq}: expected ${state.lastEntryHash}, got ${row.entry.prevEntryHash}`);
716
+ }
717
+ const res = step(state, row.envelope, replayHooks);
718
+ if (!res.logEntry) {
719
+ throw new Error(`REPLAY_MISSING_LOG_ENTRY at seq=${row.entry.serverSeq}`);
720
+ }
721
+ if (res.logEntry.entryHash !== row.entry.entryHash) {
722
+ throw new Error(`REPLAY_ENTRY_HASH_MISMATCH at seq=${row.entry.serverSeq}: expected ${row.entry.entryHash}, got ${res.logEntry.entryHash}`);
723
+ }
724
+ if (!seenOps.has(row.entry.opId)) {
725
+ seenOps.set(row.entry.opId, toOpIndexRecord(row.entry));
726
+ }
727
+ if (row.entry.kind === 'FinalizeBatch' && row.entry.applied && res.state.spentApprovals.length > 0) {
728
+ for (const appId of res.state.spentApprovals) {
729
+ spentSet.add(appId);
730
+ }
731
+ }
732
+ if (res.state.clusters !== state.clusters) {
733
+ const lastCluster = res.state.clusters[res.state.clusters.length - 1];
734
+ if (lastCluster) {
735
+ clusterMap.set(`${lastCluster.toolId}\0${lastCluster.clusterId}`, lastCluster.outcome);
736
+ }
737
+ }
738
+ state = res.state;
739
+ }
740
+ return {
741
+ state,
742
+ stateHash: computeStateHash(state),
743
+ lastEntryHash: state.lastEntryHash,
744
+ replayedEntries: rows.length,
745
+ };
746
+ }