pi-braid 0.40.5 → 0.41.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 (95) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +128 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +89 -10
  13. package/dist/extensions/core/skills-tool/auto-inject.js +150 -21
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +47 -10
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +66 -23
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-MAP.md +1 -1
  49. package/docs/CONTEXT-POLICY.md +8 -0
  50. package/docs/FLEET.md +99 -0
  51. package/docs/LOCAL_DEV.md +0 -1
  52. package/docs/ROADMAP.md +5 -5
  53. package/docs/SETUP.md +19 -18
  54. package/package.json +5 -1
  55. package/scripts/fleet/cli.mjs +499 -0
  56. package/scripts/fleet/driver-rpc.mjs +376 -0
  57. package/scripts/fleet/driver-scripted.mjs +239 -0
  58. package/scripts/fleet/journal.mjs +994 -0
  59. package/scripts/fleet/procs.mjs +76 -0
  60. package/scripts/fleet/supervisor.mjs +1494 -0
  61. package/scripts/fleet/tool-guard.mjs +467 -0
  62. package/skills/herdr-topology/SKILL.md +6 -1
  63. package/skills/release-pipeline/SKILL.md +20 -4
  64. package/skills/research/SKILL.md +32 -0
  65. package/skills/subagent-orchestration/SKILL.md +2 -2
  66. package/src/extensions/core/agent-environment/index.ts +4 -3
  67. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  68. package/src/extensions/core/prompt-builder/index.ts +12 -7
  69. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  70. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  71. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  72. package/src/extensions/core/skills-tool/auto-inject.ts +196 -24
  73. package/src/extensions/core/skills-tool/index.ts +217 -15
  74. package/src/extensions/core/skills-tool/reach.ts +256 -0
  75. package/src/extensions/core/skills-tool/skill-triggers.ts +90 -20
  76. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  77. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  78. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  79. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  80. package/src/extensions/enforcement/resume-state.ts +127 -0
  81. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  82. package/src/extensions/enforcement/whisper.ts +21 -1
  83. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  84. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  85. package/src/extensions/memory/AGENTS.md +25 -1
  86. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  87. package/src/lib/config/braid-paths.ts +20 -0
  88. package/src/lib/config/braid-settings.ts +46 -0
  89. package/src/lib/detection/context-tiers.ts +186 -13
  90. package/src/lib/events/AGENTS.md +1 -0
  91. package/src/lib/events/turn-boundary.ts +115 -0
  92. package/src/lib/orchestrator/workers.ts +33 -12
  93. package/src/lib/state/global-state.ts +1 -0
  94. package/src/lib/utils/AGENTS.md +1 -1
  95. package/src/types/extension-context.d.ts +22 -79
@@ -0,0 +1,994 @@
1
+ /**
2
+ * fleet journal: the single SQLite file a fleet supervisor and its nodes
3
+ * resume from, and the discovery record that says which file is the fleet's.
4
+ *
5
+ * The design constrains what a crash must survive; each of those constraints
6
+ * is a field here, and `FLEET_JOURNAL_FIELDS` names the field-to-column
7
+ * mapping next to the failure it prevents. Tests read that export and derive
8
+ * the schema census from it, so a column dropped from the DDL fails a test
9
+ * without anyone editing a second list.
10
+ *
11
+ * Two invariants the DDL enforces rather than documents:
12
+ *
13
+ * - An effect is recorded at `tool_execution_start`, before the tool runs,
14
+ * and settled at `tool_execution_end`. `attempted` without an end is the
15
+ * only legal state a crash can leave, and it is what makes an unknown
16
+ * effect visible to the next turn.
17
+ * - Effect identity is `(turn_id, tool_call_id)`, so a resumed turn can
18
+ * never write a second row for a call it already recorded.
19
+ *
20
+ * Every write is synchronous and durable (`journal_mode = WAL`,
21
+ * `synchronous = FULL`): a journal that can lose its last record across a
22
+ * power cut is not the durable half of anything.
23
+ */
24
+
25
+ import { createHash } from "node:crypto";
26
+ import { mkdirSync } from "node:fs";
27
+ import { dirname, isAbsolute, join, resolve } from "node:path";
28
+ import { DatabaseSync } from "node:sqlite";
29
+
30
+ export const SCHEMA_VERSION = 1;
31
+ export const JOURNAL_FILE = "fleet.sqlite";
32
+
33
+ /**
34
+ * How long one statement waits for the write lock before SQLite reports it
35
+ * busy, in milliseconds.
36
+ *
37
+ * 5000 was too small. Every write here commits with `synchronous = FULL`, so a
38
+ * single commit is an fsync, and a supervisor draining a few hundred overdue
39
+ * asks holds the lock for as long as that takes on a loaded box. A drainer that
40
+ * met contention therefore threw `database is locked` at five seconds - a
41
+ * legitimate drain under load, reported as a crash. Ten seconds is the wait
42
+ * that turns that class of contention into waiting, and it is also the ceiling
43
+ * a blocked statement may impose on a supervisor's tick: two of them plus the
44
+ * drain's backoff stay under the default 30s lease TTL, so a drain that is
45
+ * waiting cannot outlive the lease it holds and let a second supervisor claim
46
+ * the same node.
47
+ */
48
+ export const BUSY_TIMEOUT_MS = 10_000;
49
+
50
+ /**
51
+ * The twelve things the journal must hold, in the design's order. `columns`
52
+ * are `table.column`; `failure` is what breaks without the field, quoted so
53
+ * the reason survives independently of the design document.
54
+ */
55
+ export const FLEET_JOURNAL_FIELDS = [
56
+ {
57
+ n: 1,
58
+ what: "node id, parent id, project root, charter path",
59
+ columns: [
60
+ "nodes.node_id",
61
+ "nodes.parent_id",
62
+ "nodes.project_root",
63
+ "nodes.charter_path",
64
+ ],
65
+ failure: "a resumed fleet cannot say which nodes existed or where they belong",
66
+ },
67
+ {
68
+ n: 2,
69
+ what: "pi session id and session file path",
70
+ columns: ["nodes.session_id", "nodes.session_file", "turns.session_id"],
71
+ failure: "resume cannot reopen the same conversation, so it restarts the node",
72
+ },
73
+ {
74
+ n: 3,
75
+ what: "node state and attempt counter",
76
+ columns: ["nodes.state", "nodes.attempts", "nodes.turn_count"],
77
+ failure: "a crashed turn is indistinguishable from a finished one, and a lost node is silent",
78
+ },
79
+ {
80
+ n: 4,
81
+ what: "turn id, prompt ref, per-turn message history reference",
82
+ columns: [
83
+ "turns.turn_id",
84
+ "turns.node_id",
85
+ "turns.prompt_text",
86
+ "model_requests.turn_id",
87
+ "model_requests.seq",
88
+ "model_requests.message_count",
89
+ "model_requests.tool_count",
90
+ ],
91
+ failure: "the parent cannot tell in-flight work from queued work, or see what it sent",
92
+ },
93
+ {
94
+ n: 5,
95
+ what: "each completed effect, its idempotency key, its replay policy",
96
+ columns: [
97
+ "effects.tool_call_id",
98
+ "effects.tool_name",
99
+ "effects.idempotency_key",
100
+ "effects.replay",
101
+ "effects.state",
102
+ "effects.result_json",
103
+ ],
104
+ failure: "the resume repeats the effect",
105
+ },
106
+ {
107
+ n: 6,
108
+ what: "parked ask: token, priority, question, proposed default, deadline, answer, answer source",
109
+ columns: [
110
+ "asks.token",
111
+ "asks.priority",
112
+ "asks.question",
113
+ "asks.default_answer",
114
+ "asks.deadline_at",
115
+ "asks.state",
116
+ "asks.answer_text",
117
+ "asks.answer_source",
118
+ ],
119
+ failure: "a parked node's deadline passes with an answer no one can route",
120
+ },
121
+ {
122
+ n: 7,
123
+ what: "token and spend budget per node and per project",
124
+ columns: [
125
+ "nodes.token_cap",
126
+ "nodes.spend_cap_usd",
127
+ "nodes.tokens_in",
128
+ "nodes.tokens_out",
129
+ "nodes.spend_usd",
130
+ "projects.token_cap",
131
+ "projects.spend_cap_usd",
132
+ "projects.tokens_in",
133
+ "projects.tokens_out",
134
+ "projects.spend_usd",
135
+ ],
136
+ failure: "a queued fleet is a bill with no ceiling",
137
+ },
138
+ {
139
+ n: 8,
140
+ what: "the lock each node holds on its workspace paths",
141
+ columns: ["locks.path", "locks.owner_node", "locks.owner_epoch", "locks.acquired_at"],
142
+ failure: "two nodes write the same file after a restart",
143
+ },
144
+ {
145
+ n: 9,
146
+ what: "the child process id per turn, with its start time",
147
+ columns: ["turns.child_pid", "turns.child_pgid", "turns.started_at", "turns.supervisor_epoch"],
148
+ failure: "an orphaned node keeps writing after the supervisor died",
149
+ },
150
+ {
151
+ n: 10,
152
+ what: "the message id, the node it was routed to, its delivery state",
153
+ columns: [
154
+ "inbox.msg_id",
155
+ "inbox.node_id",
156
+ "inbox.state",
157
+ "inbox.delivered_tier",
158
+ "inbox.delivered_turn_id",
159
+ "routes.msg_id",
160
+ "routes.node_id",
161
+ "routes.delivery_state",
162
+ ],
163
+ failure: "a steered message is delivered twice or lost",
164
+ },
165
+ {
166
+ n: 11,
167
+ what: "the node lease: owner, epoch or start time, and its heartbeat",
168
+ columns: ["leases.node_id", "leases.owner_pid", "leases.epoch", "leases.heartbeat_at", "leases.state"],
169
+ failure: "two supervisors both believe they own one node",
170
+ },
171
+ {
172
+ n: 12,
173
+ what: "the supervisor's own epoch, so a restart can tell itself from a stale predecessor",
174
+ columns: ["supervisors.pid", "supervisors.epoch", "supervisors.state", "supervisors.heartbeat_at"],
175
+ failure: "a restarted supervisor waits on work its own dead predecessor still appears to hold",
176
+ },
177
+ ];
178
+
179
+ const DDL = `
180
+ CREATE TABLE IF NOT EXISTS fleet_meta (
181
+ key TEXT PRIMARY KEY,
182
+ value TEXT NOT NULL
183
+ );
184
+
185
+ CREATE TABLE IF NOT EXISTS projects (
186
+ project_root TEXT PRIMARY KEY,
187
+ created_at INTEGER NOT NULL,
188
+ tokens_in INTEGER NOT NULL DEFAULT 0,
189
+ tokens_out INTEGER NOT NULL DEFAULT 0,
190
+ spend_usd REAL NOT NULL DEFAULT 0,
191
+ token_cap INTEGER,
192
+ spend_cap_usd REAL
193
+ );
194
+
195
+ CREATE TABLE IF NOT EXISTS nodes (
196
+ node_id TEXT PRIMARY KEY,
197
+ parent_id TEXT,
198
+ project_root TEXT NOT NULL,
199
+ charter_path TEXT NOT NULL,
200
+ driver TEXT NOT NULL,
201
+ driver_config TEXT NOT NULL DEFAULT '{}',
202
+ state TEXT NOT NULL,
203
+ attempts INTEGER NOT NULL DEFAULT 0,
204
+ turn_count INTEGER NOT NULL DEFAULT 0,
205
+ session_id TEXT,
206
+ session_file TEXT,
207
+ tokens_in INTEGER NOT NULL DEFAULT 0,
208
+ tokens_out INTEGER NOT NULL DEFAULT 0,
209
+ spend_usd REAL NOT NULL DEFAULT 0,
210
+ token_cap INTEGER,
211
+ spend_cap_usd REAL,
212
+ done_reason TEXT,
213
+ state_changed_at INTEGER NOT NULL,
214
+ created_at INTEGER NOT NULL
215
+ );
216
+
217
+ CREATE TABLE IF NOT EXISTS turns (
218
+ turn_id INTEGER PRIMARY KEY AUTOINCREMENT,
219
+ node_id TEXT NOT NULL,
220
+ attempt INTEGER NOT NULL,
221
+ kind TEXT NOT NULL,
222
+ state TEXT NOT NULL,
223
+ prompt_text TEXT,
224
+ session_id TEXT,
225
+ child_pid INTEGER,
226
+ child_pgid INTEGER,
227
+ supervisor_epoch INTEGER,
228
+ model_requests INTEGER NOT NULL DEFAULT 0,
229
+ tokens_in INTEGER NOT NULL DEFAULT 0,
230
+ tokens_out INTEGER NOT NULL DEFAULT 0,
231
+ spend_usd REAL NOT NULL DEFAULT 0,
232
+ started_at INTEGER NOT NULL,
233
+ ended_at INTEGER
234
+ );
235
+
236
+ CREATE TABLE IF NOT EXISTS model_requests (
237
+ turn_id INTEGER NOT NULL,
238
+ seq INTEGER NOT NULL,
239
+ message_count INTEGER NOT NULL DEFAULT 0,
240
+ tool_count INTEGER NOT NULL DEFAULT 0,
241
+ tokens_in INTEGER NOT NULL DEFAULT 0,
242
+ tokens_out INTEGER NOT NULL DEFAULT 0,
243
+ at INTEGER NOT NULL,
244
+ PRIMARY KEY (turn_id, seq)
245
+ );
246
+
247
+ CREATE TABLE IF NOT EXISTS effects (
248
+ turn_id INTEGER NOT NULL,
249
+ node_id TEXT NOT NULL,
250
+ tool_call_id TEXT NOT NULL,
251
+ seq INTEGER NOT NULL,
252
+ tool_name TEXT NOT NULL,
253
+ args_json TEXT NOT NULL,
254
+ replay TEXT NOT NULL,
255
+ idempotency_key TEXT NOT NULL,
256
+ state TEXT NOT NULL,
257
+ result_json TEXT,
258
+ is_error INTEGER,
259
+ started_at INTEGER NOT NULL,
260
+ ended_at INTEGER,
261
+ PRIMARY KEY (turn_id, tool_call_id)
262
+ );
263
+ CREATE INDEX IF NOT EXISTS effects_idempotency_key ON effects(idempotency_key);
264
+ -- One node's calls to one tool, oldest turn first: the read the duplication
265
+ -- guard makes before every refusable call. Without it SQLite walks every effect
266
+ -- in the store and sorts the matches, so the refusal path costs more as the
267
+ -- project's history grows. The columns are the guard's own filters in its own
268
+ -- order - the node and tool are equalities, the turn is the range that bounds
269
+ -- its recovery window - so the ORDER BY ends on seq and is the index walk
270
+ -- rather than a temp b-tree. What is left (the state disjunction and is_error)
271
+ -- filters the handful of rows the window holds, which is why it is not in the
272
+ -- key: an equality-shaped index would leave the rows unordered by turn.
273
+ CREATE INDEX IF NOT EXISTS effects_call_history ON effects(node_id, tool_name, turn_id, seq);
274
+
275
+ CREATE TABLE IF NOT EXISTS asks (
276
+ token TEXT PRIMARY KEY,
277
+ node_id TEXT NOT NULL,
278
+ turn_id INTEGER,
279
+ priority INTEGER NOT NULL DEFAULT 0,
280
+ question TEXT NOT NULL,
281
+ default_answer TEXT NOT NULL,
282
+ deadline_at INTEGER NOT NULL,
283
+ state TEXT NOT NULL,
284
+ answer_text TEXT,
285
+ answer_source TEXT,
286
+ asked_at INTEGER NOT NULL,
287
+ answered_at INTEGER
288
+ );
289
+
290
+ CREATE TABLE IF NOT EXISTS inbox (
291
+ msg_id TEXT PRIMARY KEY,
292
+ node_id TEXT NOT NULL,
293
+ kind TEXT NOT NULL,
294
+ body TEXT NOT NULL,
295
+ state TEXT NOT NULL,
296
+ token TEXT,
297
+ recorded_at INTEGER NOT NULL,
298
+ delivered_at INTEGER,
299
+ delivered_tier TEXT,
300
+ delivered_turn_id INTEGER,
301
+ delivered_after_effect_seq INTEGER,
302
+ delivered_before_request_seq INTEGER
303
+ );
304
+ CREATE INDEX IF NOT EXISTS inbox_pending ON inbox(node_id, state);
305
+
306
+ CREATE TABLE IF NOT EXISTS routes (
307
+ msg_id TEXT PRIMARY KEY,
308
+ node_id TEXT NOT NULL,
309
+ token TEXT,
310
+ decided_at INTEGER NOT NULL,
311
+ delivery_state TEXT NOT NULL
312
+ );
313
+
314
+ CREATE TABLE IF NOT EXISTS leases (
315
+ lease_id TEXT PRIMARY KEY,
316
+ node_id TEXT NOT NULL,
317
+ owner_pid INTEGER NOT NULL,
318
+ epoch INTEGER NOT NULL,
319
+ acquired_at INTEGER NOT NULL,
320
+ heartbeat_at INTEGER NOT NULL,
321
+ expires_at INTEGER NOT NULL,
322
+ released_at INTEGER,
323
+ state TEXT NOT NULL
324
+ );
325
+ CREATE INDEX IF NOT EXISTS leases_node ON leases(node_id, state);
326
+
327
+ CREATE TABLE IF NOT EXISTS supervisors (
328
+ pid INTEGER PRIMARY KEY,
329
+ epoch INTEGER NOT NULL,
330
+ started_at INTEGER NOT NULL,
331
+ heartbeat_at INTEGER NOT NULL,
332
+ state TEXT NOT NULL,
333
+ driver TEXT NOT NULL,
334
+ child_args TEXT NOT NULL,
335
+ pi_version TEXT
336
+ );
337
+
338
+ CREATE TABLE IF NOT EXISTS locks (
339
+ path TEXT PRIMARY KEY,
340
+ owner_node TEXT NOT NULL,
341
+ owner_epoch INTEGER NOT NULL,
342
+ acquired_at INTEGER NOT NULL,
343
+ released_at INTEGER
344
+ );
345
+ `;
346
+
347
+ const now = () => Date.now();
348
+
349
+ /** A fleet root is an absolute directory; a relative one resolves against cwd. */
350
+ export function resolveFleetRoot(root) {
351
+ const absolute = resolve(root);
352
+ if (!isAbsolute(absolute)) throw new Error(`fleet root must be absolute: ${root}`);
353
+ return absolute;
354
+ }
355
+
356
+ export function journalPath(root) {
357
+ return join(resolveFleetRoot(root), JOURNAL_FILE);
358
+ }
359
+
360
+ /**
361
+ * Discovery: `<root>/fleet.sqlite` is the fleet's journal, and that path is
362
+ * recorded inside the file. A copy that travels without its root still says
363
+ * which root it came from; two roots are two fleets and never one store.
364
+ */
365
+ export function openJournal(root, options = {}) {
366
+ const fleetRoot = resolveFleetRoot(root);
367
+ mkdirSync(dirname(journalPath(fleetRoot)), { recursive: true });
368
+ const db = new DatabaseSync(journalPath(fleetRoot));
369
+ // The wait goes first. Every statement below can block on another process's
370
+ // write, and a busy handler installed after them never applies to them: setting
371
+ // the journal mode on a store another process is writing raises
372
+ // "database is locked" immediately, because at that point this connection has
373
+ // no handler and SQLite cannot wait. Measured: a two-drainer race failed about
374
+ // one run in twenty at this line, before the timeout was ever in force.
375
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
376
+ // The mode is a property of the file, not of this connection. Asking first
377
+ // means a reader never has to take the exclusive lock that changing the mode
378
+ // needs, and on a store that is already WAL the answer costs one pragma read.
379
+ // The mode is a property of the file, not of this connection, so ask before
380
+ // setting it: a reader never needs the exclusive lock that changing it takes.
381
+ const isWal = () => String(Object.values(db.prepare("PRAGMA journal_mode").get() ?? {})[0] ?? "").toLowerCase() === "wal";
382
+ if (!isWal()) {
383
+ // Setting the mode needs an exclusive lock, and SQLite answers SQLITE_BUSY
384
+ // for that statement without consulting the busy handler, so waiting on it is
385
+ // not available. Two processes initialising one fresh store therefore race
386
+ // and one of them throws. Retry a bounded number of times, and treat "someone
387
+ // else already made it WAL" as success.
388
+ const deadline = Date.now() + BUSY_TIMEOUT_MS;
389
+ for (let attempt = 0; ; attempt += 1) {
390
+ try {
391
+ db.exec("PRAGMA journal_mode = WAL");
392
+ break;
393
+ } catch (error) {
394
+ if (isWal()) break;
395
+ if (Date.now() >= deadline) throw error;
396
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(50 * (attempt + 1), 250));
397
+ }
398
+ }
399
+ }
400
+ db.exec("PRAGMA synchronous = FULL");
401
+ db.exec(DDL);
402
+ const projectRoot = options.projectRoot ? resolve(options.projectRoot) : fleetRoot;
403
+ const meta = {
404
+ store_path: journalPath(fleetRoot),
405
+ schema_version: String(SCHEMA_VERSION),
406
+ project_root: projectRoot,
407
+ driver: options.driver ?? "unset",
408
+ child_args: JSON.stringify(options.childArgs ?? []),
409
+ pi_version: options.piVersion ?? "unset",
410
+ created_at: String(now()),
411
+ };
412
+ const insertMeta = db.prepare("INSERT OR IGNORE INTO fleet_meta(key, value) VALUES (?, ?)");
413
+ for (const [key, value] of Object.entries(meta)) insertMeta.run(key, value);
414
+ db.prepare("INSERT OR IGNORE INTO projects(project_root, created_at) VALUES (?, ?)").run(projectRoot, now());
415
+ return new Journal(db, fleetRoot);
416
+ }
417
+
418
+ export class Journal {
419
+ constructor(db, root) {
420
+ this.db = db;
421
+ this.root = root;
422
+ this.path = journalPath(root);
423
+ this._cache = new Map();
424
+ this.busyTimeoutMs = BUSY_TIMEOUT_MS;
425
+ }
426
+
427
+ close() {
428
+ this.db.close();
429
+ }
430
+
431
+ /**
432
+ * Run `body` as one write transaction.
433
+ *
434
+ * `BEGIN IMMEDIATE` takes the write lock before the body reads, so two
435
+ * processes that both intend to act on the same rows serialize: the second
436
+ * one's read happens after the first one's commit, rather than against the
437
+ * state the first one was about to change. A body that throws is rolled back
438
+ * whole, which is what lets a caller treat several statements as one edit.
439
+ *
440
+ * `busyTimeoutMs` is the wait this transaction may spend acquiring that
441
+ * lock, and it is per-connection state, so it is restored afterwards: a
442
+ * caller with a bounded window of its own (the drain, whose retry loop is the
443
+ * policy) does not leave every later statement in the process with it.
444
+ */
445
+ transaction(body, { busyTimeoutMs } = {}) {
446
+ const previous = this.busyTimeoutMs;
447
+ if (busyTimeoutMs != null && busyTimeoutMs !== previous) {
448
+ this.db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(busyTimeoutMs))}`);
449
+ this.busyTimeoutMs = Math.max(0, Math.floor(busyTimeoutMs));
450
+ }
451
+ try {
452
+ this.db.exec("BEGIN IMMEDIATE");
453
+ try {
454
+ const result = body();
455
+ this.db.exec("COMMIT");
456
+ return result;
457
+ } catch (error) {
458
+ this.db.exec("ROLLBACK");
459
+ throw error;
460
+ }
461
+ } finally {
462
+ if (this.busyTimeoutMs !== previous) {
463
+ this.db.exec(`PRAGMA busy_timeout = ${previous}`);
464
+ this.busyTimeoutMs = previous;
465
+ }
466
+ }
467
+ }
468
+
469
+ _stmt(sql) {
470
+ let stmt = this._cache.get(sql);
471
+ if (!stmt) {
472
+ stmt = this.db.prepare(sql);
473
+ this._cache.set(sql, stmt);
474
+ }
475
+ return stmt;
476
+ }
477
+
478
+ meta() {
479
+ const rows = this._stmt("SELECT key, value FROM fleet_meta").all();
480
+ return Object.fromEntries(rows.map((row) => [row.key, row.value]));
481
+ }
482
+
483
+ setMeta(key, value) {
484
+ this._stmt("INSERT INTO fleet_meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(
485
+ key,
486
+ String(value),
487
+ );
488
+ }
489
+
490
+ /** Drop a meta key, for a fact that stops being true (a deferral that recovered). */
491
+ clearMeta(key) {
492
+ this._stmt("DELETE FROM fleet_meta WHERE key = ?").run(key);
493
+ }
494
+
495
+ // ── nodes ────────────────────────────────────────────────────────────────
496
+
497
+ addNode(node) {
498
+ this._stmt(
499
+ `INSERT INTO nodes (node_id, parent_id, project_root, charter_path, driver, driver_config,
500
+ state, attempts, turn_count, token_cap, spend_cap_usd, state_changed_at, created_at)
501
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?, ?, ?)`,
502
+ ).run(
503
+ node.nodeId,
504
+ node.parentId ?? null,
505
+ resolve(node.projectRoot),
506
+ node.charterPath,
507
+ node.driver ?? "rpc",
508
+ JSON.stringify(node.driverConfig ?? {}),
509
+ node.state ?? "settled",
510
+ node.tokenCap ?? null,
511
+ node.spendCapUsd ?? null,
512
+ now(),
513
+ now(),
514
+ );
515
+ return this.getNode(node.nodeId);
516
+ }
517
+
518
+ getNode(nodeId) {
519
+ return this._stmt("SELECT * FROM nodes WHERE node_id = ?").get(nodeId) ?? null;
520
+ }
521
+
522
+ listNodes() {
523
+ return this._stmt("SELECT * FROM nodes ORDER BY created_at, node_id").all();
524
+ }
525
+
526
+ setNodeState(nodeId, state, extra = {}) {
527
+ const fields = ["state = ?", "state_changed_at = ?"];
528
+ const values = [state, now()];
529
+ for (const [key, value] of Object.entries(extra)) {
530
+ fields.push(`${key} = ?`);
531
+ values.push(value);
532
+ }
533
+ values.push(nodeId);
534
+ this._stmt(`UPDATE nodes SET ${fields.join(", ")} WHERE node_id = ?`).run(...values);
535
+ }
536
+
537
+ setNodeSession(nodeId, { sessionId, sessionFile }) {
538
+ this._stmt("UPDATE nodes SET session_id = ?, session_file = ? WHERE node_id = ?").run(
539
+ sessionId,
540
+ sessionFile,
541
+ nodeId,
542
+ );
543
+ }
544
+
545
+ addNodeUsage(nodeId, { tokensIn = 0, tokensOut = 0, spendUsd = 0, projectRoot }) {
546
+ this._stmt(
547
+ "UPDATE nodes SET tokens_in = tokens_in + ?, tokens_out = tokens_out + ?, spend_usd = spend_usd + ? WHERE node_id = ?",
548
+ ).run(tokensIn, tokensOut, spendUsd, nodeId);
549
+ if (projectRoot) {
550
+ this._stmt(
551
+ "UPDATE projects SET tokens_in = tokens_in + ?, tokens_out = tokens_out + ?, spend_usd = spend_usd + ? WHERE project_root = ?",
552
+ ).run(tokensIn, tokensOut, spendUsd, projectRoot);
553
+ }
554
+ }
555
+
556
+ project(projectRoot) {
557
+ return (
558
+ this._stmt("SELECT * FROM projects WHERE project_root = ?").get(projectRoot) ?? {
559
+ project_root: projectRoot,
560
+ tokens_in: 0,
561
+ tokens_out: 0,
562
+ spend_usd: 0,
563
+ token_cap: null,
564
+ spend_cap_usd: null,
565
+ }
566
+ );
567
+ }
568
+
569
+ /** A budget refusal is a decision, so it reads both caps and returns a reason. */
570
+ budgetRefusal(projectRoot, nodeId) {
571
+ const node = this.getNode(nodeId);
572
+ const project = this.project(projectRoot);
573
+ const over = (used, cap, label) =>
574
+ cap != null && used >= cap ? `${label} spent ${Math.round(used)} of cap ${Math.round(cap)}` : null;
575
+ return (
576
+ over(node.tokens_in + node.tokens_out, node.token_cap, "node tokens") ??
577
+ over(node.spend_usd, node.spend_cap_usd, "node spend") ??
578
+ over(project.tokens_in + project.tokens_out, project.token_cap, "project tokens") ??
579
+ over(project.spend_usd, project.spend_cap_usd, "project spend")
580
+ );
581
+ }
582
+
583
+ // ── turns ────────────────────────────────────────────────────────────────
584
+
585
+ /**
586
+ * A turn is not an attempt. `attempts` counts recoveries and failures, so a
587
+ * node that works steadily never accumulates one; the turn carries the
588
+ * attempt number it was started under for the reader.
589
+ */
590
+ beginTurn(nodeId, { kind, promptText, sessionId, supervisorEpoch }) {
591
+ const node = this.getNode(nodeId);
592
+ const attempt = node?.attempts ?? 0;
593
+ this._stmt("UPDATE nodes SET turn_count = turn_count + 1 WHERE node_id = ?").run(nodeId);
594
+ const info = this._stmt(
595
+ `INSERT INTO turns (node_id, attempt, kind, state, prompt_text, session_id, supervisor_epoch, started_at)
596
+ VALUES (?, ?, ?, 'in_progress', ?, ?, ?, ?)`,
597
+ ).run(nodeId, attempt, kind, promptText, sessionId ?? null, supervisorEpoch ?? null, now());
598
+ return Number(info.lastInsertRowid);
599
+ }
600
+
601
+ turn(turnId) {
602
+ return this._stmt("SELECT * FROM turns WHERE turn_id = ?").get(turnId) ?? null;
603
+ }
604
+
605
+ turnsFor(nodeId) {
606
+ return this._stmt("SELECT * FROM turns WHERE node_id = ? ORDER BY turn_id").all(nodeId);
607
+ }
608
+
609
+ bumpAttempt(nodeId) {
610
+ this._stmt("UPDATE nodes SET attempts = attempts + 1 WHERE node_id = ?").run(nodeId);
611
+ }
612
+
613
+ openTurns(nodeId) {
614
+ return this._stmt("SELECT * FROM turns WHERE node_id = ? AND state = 'in_progress'").all(nodeId);
615
+ }
616
+
617
+ allOpenTurns() {
618
+ return this._stmt("SELECT * FROM turns WHERE state = 'in_progress'").all();
619
+ }
620
+
621
+ setTurnChild(turnId, { pid, pgid }) {
622
+ this._stmt("UPDATE turns SET child_pid = ?, child_pgid = ? WHERE turn_id = ?").run(pid, pgid, turnId);
623
+ }
624
+
625
+ endTurn(turnId, { state, tokensIn = 0, tokensOut = 0, spendUsd = 0, sessionId }) {
626
+ this._stmt(
627
+ `UPDATE turns SET state = ?, ended_at = ?, tokens_in = ?, tokens_out = ?, spend_usd = ?,
628
+ session_id = COALESCE(?, session_id) WHERE turn_id = ?`,
629
+ ).run(state, now(), tokensIn, tokensOut, spendUsd, sessionId ?? null, turnId);
630
+ }
631
+
632
+ recordModelRequest(turnId, { messageCount, toolCount, tokensIn = 0, tokensOut = 0 }) {
633
+ const row = this._stmt("SELECT model_requests AS n FROM turns WHERE turn_id = ?").get(turnId);
634
+ const seq = (row?.n ?? 0) + 1;
635
+ this._stmt(
636
+ "INSERT INTO model_requests (turn_id, seq, message_count, tool_count, tokens_in, tokens_out, at) VALUES (?, ?, ?, ?, ?, ?, ?)",
637
+ ).run(turnId, seq, messageCount, toolCount, tokensIn, tokensOut, now());
638
+ this._stmt("UPDATE turns SET model_requests = ? WHERE turn_id = ?").run(seq, turnId);
639
+ return seq;
640
+ }
641
+
642
+ modelRequests(turnId) {
643
+ return this._stmt("SELECT * FROM model_requests WHERE turn_id = ? ORDER BY seq").all(turnId);
644
+ }
645
+
646
+ // ── effects ──────────────────────────────────────────────────────────────
647
+
648
+ /**
649
+ * Record the attempt before the tool runs. Two calls with the same identity
650
+ * collapse into the first row (`INSERT OR IGNORE`): a replayed event stream
651
+ * cannot invent a second attempt.
652
+ */
653
+ effectAttempted({ turnId, nodeId, toolCallId, toolName, args, replay, seq }) {
654
+ const idempotencyKey = effectKey({ nodeId, turnId, toolCallId });
655
+ this._stmt(
656
+ `INSERT OR IGNORE INTO effects (turn_id, node_id, tool_call_id, seq, tool_name, args_json,
657
+ replay, idempotency_key, state, started_at)
658
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'attempted', ?)`,
659
+ ).run(
660
+ turnId,
661
+ nodeId,
662
+ toolCallId,
663
+ seq ?? 0,
664
+ toolName,
665
+ JSON.stringify(args ?? null),
666
+ replay,
667
+ idempotencyKey,
668
+ now(),
669
+ );
670
+ return idempotencyKey;
671
+ }
672
+
673
+ effectSettled({ turnId, toolCallId, result, isError }) {
674
+ this._stmt(
675
+ "UPDATE effects SET state = 'completed', result_json = ?, is_error = ?, ended_at = ? WHERE turn_id = ? AND tool_call_id = ? AND state = 'attempted'",
676
+ ).run(JSON.stringify(result ?? null), isError ? 1 : 0, now(), turnId, toolCallId);
677
+ }
678
+
679
+ /**
680
+ * An attempt with no end is the crash residue: the effect may or may not
681
+ * have reached the world. It stays visible with `state = 'unknown'` so the
682
+ * next turn is told about it instead of quietly repeating it.
683
+ *
684
+ * This state is inside the duplication guard, and the note says so. An
685
+ * `unknown` row counts as history: a call it matches is refused before it
686
+ * runs, because an effect that may have reached the world is the one class
687
+ * where repeating is dangerous and the record cannot settle it. The guard's
688
+ * window is the run being resumed - its current turn back to the last turn
689
+ * that ended normally - so this is not "never again": a turn that finished its
690
+ * work retires the run, and an operator retires a single row.
691
+ *
692
+ * Two instruments cover this class and they must agree: the guard refuses the
693
+ * call, and `recoveryPrompt` in supervisor.mjs names every unknown effect with
694
+ * the idempotency key that identifies it and tells the node the guard will
695
+ * refuse a repeat. The interrupted turn this row belongs to is never a settled
696
+ * turn, so it is inside the window of the turn that resumes it by
697
+ * construction; a note that promised a refusal the guard does not make, or a
698
+ * guard that refused without the note naming why, would each be half a fact.
699
+ */
700
+ markUnknownEffects(turnId) {
701
+ const rows = this.attemptedEffects(turnId);
702
+ this._stmt("UPDATE effects SET state = 'unknown' WHERE turn_id = ? AND state = 'attempted'").run(turnId);
703
+ return rows;
704
+ }
705
+
706
+ attemptedEffects(turnId) {
707
+ return this._stmt("SELECT * FROM effects WHERE turn_id = ? AND state = 'attempted' ORDER BY seq").all(turnId);
708
+ }
709
+
710
+ effects(turnId) {
711
+ return this._stmt("SELECT * FROM effects WHERE turn_id = ? ORDER BY seq").all(turnId);
712
+ }
713
+
714
+ /** Effects a resumed turn must know about, in journal order. */
715
+ settledEffects(turnId) {
716
+ return this._stmt(
717
+ "SELECT * FROM effects WHERE turn_id = ? AND state = 'completed' ORDER BY seq",
718
+ ).all(turnId);
719
+ }
720
+
721
+ effectsByKey(idempotencyKey) {
722
+ return this._stmt("SELECT * FROM effects WHERE idempotency_key = ? ORDER BY turn_id").all(idempotencyKey);
723
+ }
724
+
725
+ // ── asks and inbox ───────────────────────────────────────────────────────
726
+
727
+ recordAsk(ask) {
728
+ this._stmt(
729
+ `INSERT INTO asks (token, node_id, turn_id, priority, question, default_answer, deadline_at, state, asked_at)
730
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?)`,
731
+ ).run(
732
+ ask.token,
733
+ ask.nodeId,
734
+ ask.turnId ?? null,
735
+ Number(ask.priority ?? 0),
736
+ ask.question,
737
+ ask.defaultAnswer,
738
+ ask.deadlineAt,
739
+ now(),
740
+ );
741
+ return this.getAsk(ask.token);
742
+ }
743
+
744
+ getAsk(token) {
745
+ return this._stmt("SELECT * FROM asks WHERE token = ?").get(token) ?? null;
746
+ }
747
+
748
+ /**
749
+ * Open asks, most urgent first. Priority orders the head's attention; it
750
+ * never changes the deadline, because a high priority that postponed the
751
+ * default would be a park with extra steps.
752
+ */
753
+ openAsks(nodeId) {
754
+ return nodeId
755
+ ? this._stmt("SELECT * FROM asks WHERE node_id = ? AND state = 'open' ORDER BY priority DESC, asked_at").all(nodeId)
756
+ : this._stmt("SELECT * FROM asks WHERE state = 'open' ORDER BY priority DESC, asked_at").all();
757
+ }
758
+
759
+ resolveAsk(token, { answerText, answerSource }) {
760
+ this._stmt(
761
+ "UPDATE asks SET state = 'answered', answer_text = ?, answer_source = ?, answered_at = ? WHERE token = ? AND state = 'open'",
762
+ ).run(answerText, answerSource, now(), token);
763
+ return this.getAsk(token);
764
+ }
765
+
766
+ /**
767
+ * Parked work whose deadline passed takes its default. This is what keeps a
768
+ * deadline from being decoration: the answer source says nobody answered.
769
+ *
770
+ * Returns only the asks THIS call claimed, and the claim is the conditional
771
+ * UPDATE rather than the read. Two supervisors that both read the same
772
+ * overdue rows must not both report them: each caller queues one message per
773
+ * returned row, so a shared read set gives a parked node two copies of its
774
+ * default in one prompt. `changes` is what decides, so the loser of the race
775
+ * returns nothing and queues nothing.
776
+ */
777
+ expireAsks(at = now()) {
778
+ const claimed = [];
779
+ for (const ask of this.openAsks().filter((ask) => ask.deadline_at <= at)) {
780
+ const result = this._stmt(
781
+ "UPDATE asks SET state = 'answered', answer_text = ?, answer_source = ?, answered_at = ? WHERE token = ? AND state = 'open'",
782
+ ).run(ask.default_answer, "deadline-default", now(), ask.token);
783
+ if (result.changes > 0) {
784
+ claimed.push({
785
+ ...ask,
786
+ state: "answered",
787
+ answer_text: ask.default_answer,
788
+ answer_source: "deadline-default",
789
+ });
790
+ }
791
+ }
792
+ return claimed;
793
+ }
794
+
795
+ addMessage(msg) {
796
+ this._stmt(
797
+ `INSERT INTO inbox (msg_id, node_id, kind, body, state, token, recorded_at)
798
+ VALUES (?, ?, ?, ?, 'recorded', ?, ?)`,
799
+ ).run(msg.msgId, msg.nodeId, msg.kind, msg.body, msg.token ?? null, now());
800
+ this._stmt("INSERT OR REPLACE INTO routes (msg_id, node_id, token, decided_at, delivery_state) VALUES (?, ?, ?, ?, 'pending')").run(
801
+ msg.msgId,
802
+ msg.nodeId,
803
+ msg.token ?? null,
804
+ now(),
805
+ );
806
+ return this.getMessage(msg.msgId);
807
+ }
808
+
809
+ getMessage(msgId) {
810
+ return this._stmt("SELECT * FROM inbox WHERE msg_id = ?").get(msgId) ?? null;
811
+ }
812
+
813
+ pendingMessages(nodeId) {
814
+ return this._stmt(
815
+ "SELECT * FROM inbox WHERE node_id = ? AND state = 'recorded' ORDER BY recorded_at, msg_id",
816
+ ).all(nodeId);
817
+ }
818
+
819
+ markMessageDelivered(msgId, { tier, turnId, afterEffectSeq, beforeRequestSeq }) {
820
+ this._stmt(
821
+ `UPDATE inbox SET state = 'delivered', delivered_at = ?, delivered_tier = ?, delivered_turn_id = ?,
822
+ delivered_after_effect_seq = ?, delivered_before_request_seq = ? WHERE msg_id = ?`,
823
+ ).run(now(), tier, turnId ?? null, afterEffectSeq ?? null, beforeRequestSeq ?? null, msgId);
824
+ this._stmt("UPDATE routes SET delivery_state = ? WHERE msg_id = ?").run(tier === "A" ? "steered" : "delivered", msgId);
825
+ }
826
+
827
+ /**
828
+ * Retire every delivered row a node holds.
829
+ *
830
+ * Node-wide, so it cannot tell a message a prompt carried from one it did
831
+ * not: the settle gate uses `consumeMessages` with the turn's own list, and
832
+ * this remains the blunt instrument for callers that mean all of them.
833
+ */
834
+ markMessagesConsumed(nodeId) {
835
+ this._stmt("UPDATE inbox SET state = 'consumed' WHERE node_id = ? AND state = 'delivered'").run(nodeId);
836
+ }
837
+
838
+ /**
839
+ * Retire exactly the messages a turn carried.
840
+ *
841
+ * The ids are the turn's own account of what its prompt contained, so this
842
+ * consumes what a model read and nothing else: a row that reached `delivered`
843
+ * another way stays where it is, for the next turn that actually carries it.
844
+ */
845
+ consumeMessages(msgIds) {
846
+ let consumed = 0;
847
+ for (const msgId of msgIds) {
848
+ consumed += this._stmt("UPDATE inbox SET state = 'consumed' WHERE msg_id = ? AND state = 'delivered'").run(msgId).changes;
849
+ }
850
+ return consumed;
851
+ }
852
+
853
+ /**
854
+ * Put delivered messages back in the queue.
855
+ *
856
+ * A turn that never settled sent its prompt and did not finish: the body
857
+ * reached a model and nothing acted on it, so the delivery columns are
858
+ * cleared and the next turn carries it again. For an operator's instruction
859
+ * the safe side to err on is at-least-once, and the recovery prompt is the
860
+ * instrument that keeps the repetition visible.
861
+ */
862
+ releaseMessages(msgIds) {
863
+ let released = 0;
864
+ for (const msgId of msgIds) {
865
+ released += this._stmt(
866
+ `UPDATE inbox SET state = 'recorded', delivered_at = NULL, delivered_tier = NULL, delivered_turn_id = NULL,
867
+ delivered_after_effect_seq = NULL, delivered_before_request_seq = NULL
868
+ WHERE msg_id = ? AND state = 'delivered'`,
869
+ ).run(msgId).changes;
870
+ }
871
+ return released;
872
+ }
873
+
874
+ /**
875
+ * The terminal state for a message no turn will ever carry: the node it was
876
+ * routed to is finished, or failed at its attempt bound, so the promise a
877
+ * `recorded` row makes cannot be kept. Only the rows this call transitions
878
+ * are returned, so two sweepers do not both report the same message.
879
+ */
880
+ markMessagesUndeliverable(nodeId) {
881
+ const claimed = [];
882
+ for (const message of this.pendingMessages(nodeId)) {
883
+ const result = this._stmt("UPDATE inbox SET state = 'undeliverable' WHERE msg_id = ? AND state = 'recorded'").run(
884
+ message.msg_id,
885
+ );
886
+ if (result.changes > 0) claimed.push({ ...message, state: "undeliverable" });
887
+ }
888
+ return claimed;
889
+ }
890
+
891
+ messages(nodeId) {
892
+ return nodeId
893
+ ? this._stmt("SELECT * FROM inbox WHERE node_id = ? ORDER BY recorded_at, msg_id").all(nodeId)
894
+ : this._stmt("SELECT * FROM inbox ORDER BY recorded_at, msg_id").all();
895
+ }
896
+
897
+ // ── leases, supervisors, locks ───────────────────────────────────────────
898
+
899
+ nextEpoch() {
900
+ const row = this._stmt("SELECT MAX(epoch) AS epoch FROM supervisors").get();
901
+ return Number(row?.epoch ?? 0) + 1;
902
+ }
903
+
904
+ registerSupervisor({ pid, driver, childArgs, piVersion }) {
905
+ const epoch = this.nextEpoch();
906
+ this._stmt(
907
+ "INSERT INTO supervisors (pid, epoch, started_at, heartbeat_at, state, driver, child_args, pi_version) VALUES (?, ?, ?, ?, 'live', ?, ?, ?)",
908
+ ).run(pid, epoch, now(), now(), driver, JSON.stringify(childArgs ?? []), piVersion ?? null);
909
+ return epoch;
910
+ }
911
+
912
+ heartbeatSupervisor(pid) {
913
+ this._stmt("UPDATE supervisors SET heartbeat_at = ? WHERE pid = ?").run(now(), pid);
914
+ }
915
+
916
+ setSupervisorState(pid, state) {
917
+ this._stmt("UPDATE supervisors SET state = ? WHERE pid = ?").run(state, pid);
918
+ }
919
+
920
+ supervisors() {
921
+ return this._stmt("SELECT * FROM supervisors ORDER BY epoch").all();
922
+ }
923
+
924
+ acquireLease({ nodeId, ownerPid, epoch, ttlMs }) {
925
+ const existing = this.liveLease(nodeId);
926
+ if (existing && existing.epoch !== epoch) return null;
927
+ const leaseId = `${nodeId}:${epoch}`;
928
+ this._stmt(
929
+ `INSERT INTO leases (lease_id, node_id, owner_pid, epoch, acquired_at, heartbeat_at, expires_at, state)
930
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'live')
931
+ ON CONFLICT(lease_id) DO UPDATE SET heartbeat_at = excluded.heartbeat_at, expires_at = excluded.expires_at, state = 'live'`,
932
+ ).run(leaseId, nodeId, ownerPid, epoch, now(), now(), now() + ttlMs);
933
+ return this._stmt("SELECT * FROM leases WHERE lease_id = ?").get(leaseId);
934
+ }
935
+
936
+ liveLease(nodeId) {
937
+ return (
938
+ this._stmt("SELECT * FROM leases WHERE node_id = ? AND state = 'live' ORDER BY epoch DESC LIMIT 1").get(nodeId) ??
939
+ null
940
+ );
941
+ }
942
+
943
+ liveLeases() {
944
+ return this._stmt("SELECT * FROM leases WHERE state = 'live' ORDER BY node_id").all();
945
+ }
946
+
947
+ releaseLease(nodeId, epoch) {
948
+ this._stmt("UPDATE leases SET state = 'released', released_at = ? WHERE lease_id = ?").run(now(), `${nodeId}:${epoch}`);
949
+ }
950
+
951
+ expireLease(leaseId) {
952
+ this._stmt("UPDATE leases SET state = 'expired', released_at = ? WHERE lease_id = ?").run(now(), leaseId);
953
+ }
954
+
955
+ acquireLock({ path, ownerNode, ownerEpoch }) {
956
+ const held = this._stmt("SELECT * FROM locks WHERE path = ? AND released_at IS NULL").get(path);
957
+ if (held && held.owner_node !== ownerNode) return null;
958
+ this._stmt(
959
+ `INSERT INTO locks (path, owner_node, owner_epoch, acquired_at) VALUES (?, ?, ?, ?)
960
+ ON CONFLICT(path) DO UPDATE SET owner_node = excluded.owner_node, owner_epoch = excluded.owner_epoch,
961
+ acquired_at = excluded.acquired_at, released_at = NULL`,
962
+ ).run(path, ownerNode, ownerEpoch, now());
963
+ return this._stmt("SELECT * FROM locks WHERE path = ?").get(path);
964
+ }
965
+
966
+ releaseLocks(ownerNode) {
967
+ this._stmt("UPDATE locks SET released_at = ? WHERE owner_node = ? AND released_at IS NULL").run(now(), ownerNode);
968
+ }
969
+
970
+ locks() {
971
+ return this._stmt("SELECT * FROM locks ORDER BY path").all();
972
+ }
973
+ }
974
+
975
+ /**
976
+ * The effect's identity across a crash. A resumed turn that re-issues the same
977
+ * tool call inside the same turn produces this key again, and the world can
978
+ * dedupe on it; a naive resume that starts a fresh turn gets a different key,
979
+ * which is exactly why the journal cannot be the only instrument measuring
980
+ * duplication and the drill counts the world file too.
981
+ */
982
+ export function effectKey({ nodeId, turnId, toolCallId }) {
983
+ return createHash("sha256").update(`${nodeId}\n${turnId}\n${toolCallId}`).digest("hex").slice(0, 32);
984
+ }
985
+
986
+ /**
987
+ * Replay policy per tool name, recorded before the attempt. `safe` means the
988
+ * call can be run again without a second effect; everything else is `never`
989
+ * until its end event lands, because the journal observed the effect rather
990
+ * than owning it.
991
+ */
992
+ export function replayPolicy(toolName) {
993
+ return /^(read|ls|find|grep|glob|list|view|get_state|get_messages)$/i.test(toolName ?? "") ? "safe" : "never";
994
+ }