loopctl-mcp-server 3.37.0 → 3.39.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.
@@ -0,0 +1,1015 @@
1
+ /**
2
+ * US-52.62: the holder's offline journal. A session that loses loopctl keeps working its
3
+ * lease: its work-item notes and checkpoints go to a local file, the tool call answers
4
+ * `{queued: true, event_id}`, and the journal is replayed through `holder_replay` (US-52.61,
5
+ * lib/holder-replay.js) in the order the session wrote, the moment loopctl answers again.
6
+ *
7
+ * ## What is journaled, and what never is
8
+ *
9
+ * Only `work_item_note` and `work_item_checkpoint`, and only when the write got no answer
10
+ * (a network error or a timeout, `transportError` in lib/messages.js) or a 502/503/504. Every
11
+ * other answer, a 409 included, is the server's judgement and is returned as it is. Claim,
12
+ * start, report, escalate, renew, move and verify are never journaled: each needs a live
13
+ * answer that decides the session's next step. Their network errors carry
14
+ * `UNREACHABLE_NOTICE` instead (`withUnreachableNotice`).
15
+ *
16
+ * A write is journaled only while the session holds a holder credential, or while the journal
17
+ * already holds entries (a later write queues behind them, never ahead): the replay goes out
18
+ * on the session's CURRENT holder credential to its own holder id, and a process with no
19
+ * holder has nothing to replay under.
20
+ *
21
+ * ## The event id
22
+ *
23
+ * Every write carries a client UUIDv7 from its first attempt (`newEventId`): the note's
24
+ * `event_id`, the checkpoint's own `id`. The journaled copy keeps it, so a direct attempt that
25
+ * reached loopctl before the answer was lost is answered `replayed` instead of written twice.
26
+ *
27
+ * ## The file
28
+ *
29
+ * One JSON line per entry, `{event_id, seq, kind, story_id, claim_epoch, recorded_at,
30
+ * payload}`, in `LOOPCTL_JOURNAL_DIR` (default ~/.loopctl/journal, never the OS temp dir: a
31
+ * reboot must not drop it), named sha256(server URL + ":" + session_id), so the holder this
32
+ * session registers after a lapse finds the journal its ended holder left (AC-52.62.8). The
33
+ * directory is 0700 and the file 0600. An append is written and fsynced before the tool
34
+ * answers queued; a settle rewrites the remaining lines to a fresh temp file (`wx`, 0600),
35
+ * fsyncs it and renames it over the journal, the symlink-safe pattern of lib/witness-sth.js. A
36
+ * journal that is a symlink is refused, never read or written through. A torn last line (a
37
+ * crash mid-append) is skipped on read, and the next append starts on a new line.
38
+ *
39
+ * Two MCP processes of one session can overlap (a /mcp reconnect, an npx respawn) and name the
40
+ * same file, so every append and every settle holds `<file>.lock` from its read to its write:
41
+ * created O_CREAT|O_EXCL (never through a symlink, which is refused), 0600, holding the pid,
42
+ * the time and a token. A lock whose pid is gone, or older than `LOCK_STALE_MS`, is broken.
43
+ * Without it, an append between a settle's read and its rename was lost after answering
44
+ * queued, and two appends that read one last seq wrote the same seq. An append that cannot
45
+ * take the lock within `LOCK_WAIT_MS` answers an error saying loopctl is unreachable and the
46
+ * journal busy, never queued; a settle that cannot skips the round.
47
+ *
48
+ * `seq` is per journal, one past the highest seq in the file or seen by this process. A body
49
+ * goes out in strictly ascending seq even if the file repeats one (`ascending`).
50
+ *
51
+ * The journal is a copy, never the record: an entry leaves it only once loopctl answered a
52
+ * result for it (applied, replayed, fenced or refused), and its loss costs only what was not
53
+ * yet replayed.
54
+ *
55
+ * ## The replay
56
+ *
57
+ * `drain()` sends the entries in seq order, at most 200 (loopctl's bound) and about 1.5 MB (under
58
+ * its 2 MB body limit) per body, each body after the last one's answer. It runs before any new
59
+ * note or checkpoint is sent, on the next answered loopctl call (`kick`), and every 30 s while
60
+ * the journal is non-empty. A body that gets no answer leaves every entry in place. A body
61
+ * refused as a whole with a code a resend cannot change (403 holder_mismatch, 422
62
+ * replay_not_ordered, 422 replay_too_large, or a 413 for a single entry) settles each of its
63
+ * entries as refused, logged to stderr with the code, so no entry blocks later writes for
64
+ * ever. An entry refused `busy` stays: loopctl says to resend it. replay_not_ordered stays
65
+ * final because a body this module sends is always strictly ascending, so a resend would be
66
+ * refused the same way; a file that repeats a seq is renumbered before it is sent, never
67
+ * refused wholesale.
68
+ *
69
+ * Everything effectful is a parameter: the file system, the clock, the timers, the random
70
+ * bytes, the API call and the holder id.
71
+ */
72
+
73
+ import { createHash, randomBytes as nodeRandomBytes } from "node:crypto";
74
+ import * as nodeFs from "node:fs";
75
+ import nodePath from "node:path";
76
+
77
+ import { replayHolder } from "./holder-replay.js";
78
+ import { transportError } from "./messages.js";
79
+
80
+ export const JOURNAL_DIR_ENV = "LOOPCTL_JOURNAL_DIR";
81
+
82
+ /** The replay retry interval while the journal is non-empty (the story's default). */
83
+ export const REPLAY_INTERVAL_MS = 30_000;
84
+
85
+ /** loopctl's bound on one replay body (`Loopctl.Holders.Replay.max_replay_entries/0`). */
86
+ export const MAX_REPLAY_ENTRIES = 200;
87
+
88
+ /** Kept under loopctl's 2 MB request body limit, with room for the JSON around the entries. */
89
+ export const MAX_REPLAY_BODY_BYTES = 1_500_000;
90
+
91
+ /** How long an append or a settle waits for another process's journal lock before giving up. */
92
+ export const LOCK_WAIT_MS = 2_000;
93
+
94
+ /** The pause between two tries at the journal lock. */
95
+ export const LOCK_RETRY_MS = 10;
96
+
97
+ /**
98
+ * A lock older than this is a crashed or hung holder's, and is broken even when its pid is
99
+ * alive (the pid may since belong to another process). Every critical section is a few file
100
+ * operations, so a live holder never comes near it.
101
+ */
102
+ export const LOCK_STALE_MS = 30_000;
103
+
104
+ /** The `code` of the error an append or settle throws when another process holds the lock. */
105
+ export const JOURNAL_BUSY = "EJOURNALBUSY";
106
+
107
+ /** The answers that journal a write besides no answer at all. */
108
+ export const GATEWAY_STATUSES = Object.freeze([502, 503, 504]);
109
+
110
+ export const JOURNALED_KINDS = Object.freeze(["note", "checkpoint"]);
111
+
112
+ // A whole body refused with one of these is refused again on every resend.
113
+ const FINAL_BODY_CODES = new Set(["holder_mismatch", "replay_not_ordered", "replay_too_large"]);
114
+ const SETTLING_OUTCOMES = new Set(["applied", "replayed", "fenced", "refused"]);
115
+
116
+ export const UNREACHABLE_NOTICE =
117
+ "loopctl is unreachable. Work-item notes and checkpoints are being journaled locally " +
118
+ "and are sent, in order, when it answers; this call was NOT journaled, so make it again " +
119
+ "once loopctl answers.";
120
+
121
+ /** True when a write got no usable answer: no answer at all, a timeout, or a 502/503/504. */
122
+ export function unreachable(result) {
123
+ return (
124
+ transportError(result) ||
125
+ Boolean(result && result.error === true && GATEWAY_STATUSES.includes(result.status))
126
+ );
127
+ }
128
+
129
+ /**
130
+ * A control verb's network error, with the notice that loopctl is unreachable and that only
131
+ * notes and checkpoints are journaled. The body keeps its `Network error`/`Request timed out`
132
+ * prefix. Any other result passes through unchanged.
133
+ */
134
+ export function withUnreachableNotice(result) {
135
+ if (!transportError(result)) return result;
136
+ return { ...result, body: `${result.body}: ${UNREACHABLE_NOTICE}` };
137
+ }
138
+
139
+ /** The journal directory: `LOOPCTL_JOURNAL_DIR`, else ~/.loopctl/journal, else null. */
140
+ export function journalDir(env = {}, homedir = () => "") {
141
+ const override = env[JOURNAL_DIR_ENV];
142
+ if (typeof override === "string" && override.trim() !== "") return override;
143
+ let home = "";
144
+ try {
145
+ home = homedir() || "";
146
+ } catch {
147
+ home = "";
148
+ }
149
+ return home ? nodePath.join(home, ".loopctl", "journal") : null;
150
+ }
151
+
152
+ /** The journal's file name: sha256(server URL + ":" + session_id), hex. */
153
+ export function journalFileName(serverUrl, sessionId) {
154
+ return createHash("sha256").update(`${serverUrl}:${sessionId}`).digest("hex");
155
+ }
156
+
157
+ /** A UUIDv7 (RFC 9562): 48 bits of milliseconds, the version and variant, random bits. */
158
+ export function uuidv7(nowMs, randomBytes = nodeRandomBytes) {
159
+ const bytes = Buffer.from(randomBytes(16));
160
+ let ms = BigInt(Math.max(0, Math.floor(nowMs)));
161
+ for (let i = 5; i >= 0; i -= 1) {
162
+ bytes[i] = Number(ms & 0xffn);
163
+ ms >>= 8n;
164
+ }
165
+ bytes[6] = 0x70 | (bytes[6] & 0x0f);
166
+ bytes[8] = 0x80 | (bytes[8] & 0x3f);
167
+ const hex = bytes.toString("hex");
168
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
169
+ }
170
+
171
+ /** True unless signalling `pid` says it does not exist (EPERM is a live process of another user). */
172
+ export function processAlive(pid) {
173
+ try {
174
+ process.kill(pid, 0);
175
+ return true;
176
+ } catch (err) {
177
+ return !(err && err.code === "ESRCH");
178
+ }
179
+ }
180
+
181
+ const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
182
+
183
+ // A blocking pause: every journal critical section is synchronous, so the lock wait is too.
184
+ function sleepSync(ms) {
185
+ Atomics.wait(SLEEP_CELL, 0, 0, ms);
186
+ }
187
+
188
+ /** The `error.code` of a refusal body, parsed or raw. */
189
+ function errorCode(body) {
190
+ let parsed = body;
191
+ if (typeof body === "string") {
192
+ try {
193
+ parsed = JSON.parse(body);
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+ return (parsed && parsed.error && parsed.error.code) || null;
199
+ }
200
+
201
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
202
+
203
+ function entryShaped(e) {
204
+ return (
205
+ e !== null &&
206
+ typeof e === "object" &&
207
+ typeof e.event_id === "string" &&
208
+ Number.isInteger(e.seq) &&
209
+ JOURNALED_KINDS.includes(e.kind) &&
210
+ typeof e.story_id === "string" &&
211
+ Number.isInteger(e.claim_epoch) &&
212
+ typeof e.recorded_at === "string" &&
213
+ e.payload !== null &&
214
+ typeof e.payload === "object"
215
+ );
216
+ }
217
+
218
+ // The entry as the replay route takes it: exactly the seven fields.
219
+ function wire(e) {
220
+ return {
221
+ event_id: e.event_id,
222
+ seq: e.seq,
223
+ kind: e.kind,
224
+ story_id: e.story_id,
225
+ claim_epoch: e.claim_epoch,
226
+ recorded_at: e.recorded_at,
227
+ payload: e.payload,
228
+ };
229
+ }
230
+
231
+ // A story row, as get_story, claim and the work-item open return it: an id, its claim_epoch,
232
+ // and a field only a story has (so a checkpoint's own id is never taken for its story's).
233
+ function storyShaped(value) {
234
+ return (
235
+ value !== null &&
236
+ typeof value === "object" &&
237
+ typeof value.id === "string" &&
238
+ UUID_RE.test(value.id) &&
239
+ Number.isInteger(value.claim_epoch) &&
240
+ ("assigned_holder_id" in value || "agent_status" in value)
241
+ );
242
+ }
243
+
244
+ /**
245
+ * @param {{
246
+ * dir: string | null,
247
+ * serverUrl: string,
248
+ * sessionId: string,
249
+ * apiCall: Function,
250
+ * holderId: () => string | null,
251
+ * fs?: typeof nodeFs,
252
+ * now?: () => number,
253
+ * setInterval?: Function,
254
+ * clearInterval?: Function,
255
+ * randomBytes?: (n: number) => Buffer,
256
+ * log?: (line: string) => void,
257
+ * pid?: number,
258
+ * intervalMs?: number,
259
+ * maxEntries?: number,
260
+ * maxBodyBytes?: number,
261
+ * lockWaitMs?: number,
262
+ * lockRetryMs?: number,
263
+ * lockStaleMs?: number,
264
+ * sleep?: (ms: number) => void,
265
+ * pidAlive?: (pid: number) => boolean,
266
+ * testHooks?: {afterAppendRead?: () => void, afterSettleRead?: () => void, beforeBreak?: () => void},
267
+ * }} deps
268
+ */
269
+ export function createHolderJournal(deps) {
270
+ const {
271
+ dir,
272
+ serverUrl,
273
+ sessionId,
274
+ apiCall,
275
+ holderId,
276
+ fs = nodeFs,
277
+ now = () => Date.now(),
278
+ setInterval: setTimer = globalThis.setInterval,
279
+ clearInterval: clearTimer = globalThis.clearInterval,
280
+ randomBytes = nodeRandomBytes,
281
+ // stderr, never stdout: stdout is the MCP stream.
282
+ log = (line) => process.stderr.write(`${line}\n`),
283
+ pid = process.pid,
284
+ intervalMs = REPLAY_INTERVAL_MS,
285
+ maxEntries = MAX_REPLAY_ENTRIES,
286
+ maxBodyBytes = MAX_REPLAY_BODY_BYTES,
287
+ lockWaitMs = LOCK_WAIT_MS,
288
+ lockRetryMs = LOCK_RETRY_MS,
289
+ lockStaleMs = LOCK_STALE_MS,
290
+ sleep = sleepSync,
291
+ pidAlive = processAlive,
292
+ // Called inside a critical section, between its read and its write: the window a second
293
+ // process of the session would write into. Tests only.
294
+ testHooks = {},
295
+ } = deps;
296
+
297
+ const file = dir ? nodePath.join(dir, journalFileName(serverUrl, sessionId)) : null;
298
+ const lockFile = file ? `${file}.lock` : null;
299
+
300
+ let lastSeq = 0;
301
+ let pendingHint = 0;
302
+ let lastFenced = null;
303
+ let timer = null;
304
+ let draining = null;
305
+ const epochs = new Map();
306
+
307
+ // ---------------------------------------------------------------------------------------
308
+ // The file
309
+
310
+ function isMissing(err) {
311
+ return err && err.code === "ENOENT";
312
+ }
313
+
314
+ /** The entries in seq order; a torn or foreign line is skipped. Refuses a symlink. */
315
+ function read() {
316
+ if (!file) return [];
317
+ let st;
318
+ try {
319
+ st = fs.lstatSync(file);
320
+ } catch (err) {
321
+ if (isMissing(err)) return [];
322
+ throw err;
323
+ }
324
+ if (st.isSymbolicLink()) throw new Error(`the journal ${file} is a symlink; refusing it`);
325
+
326
+ const entries = [];
327
+ for (const line of fs.readFileSync(file, "utf8").split("\n")) {
328
+ if (line.trim() === "") continue;
329
+ try {
330
+ const entry = JSON.parse(line);
331
+ if (entryShaped(entry)) entries.push(entry);
332
+ } catch {
333
+ // A torn line from a crash mid-append: nothing loopctl was promised.
334
+ }
335
+ }
336
+ entries.sort((a, b) => a.seq - b.seq);
337
+ for (const e of entries) lastSeq = Math.max(lastSeq, e.seq);
338
+ pendingHint = entries.length;
339
+ return entries;
340
+ }
341
+
342
+ function readSafely() {
343
+ try {
344
+ return read();
345
+ } catch (err) {
346
+ log(`loopctl journal: cannot read ${file}: ${err.message}`);
347
+ return [];
348
+ }
349
+ }
350
+
351
+ function fsyncDir() {
352
+ let fd;
353
+ try {
354
+ fd = fs.openSync(dir, "r");
355
+ fs.fsyncSync(fd);
356
+ } catch {
357
+ // Not every platform fsyncs a directory; the file's own fsync still holds.
358
+ } finally {
359
+ if (fd !== undefined) {
360
+ try {
361
+ fs.closeSync(fd);
362
+ } catch {
363
+ /* ignore */
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ function appendFlags() {
370
+ const c = fs.constants || {};
371
+ if (Number.isInteger(c.O_WRONLY) && Number.isInteger(c.O_APPEND) && Number.isInteger(c.O_CREAT)) {
372
+ return c.O_WRONLY | c.O_APPEND | c.O_CREAT | (Number.isInteger(c.O_NOFOLLOW) ? c.O_NOFOLLOW : 0);
373
+ }
374
+ return "a";
375
+ }
376
+
377
+ // ---------------------------------------------------------------------------------------
378
+ // The lock: every read-modify-write of the journal holds it
379
+
380
+ function flagsOr(fallback, ...names) {
381
+ const c = fs.constants || {};
382
+ if (!names.every((n) => Number.isInteger(c[n]))) return fallback;
383
+ const nofollow = Number.isInteger(c.O_NOFOLLOW) ? c.O_NOFOLLOW : 0;
384
+ return names.reduce((acc, n) => acc | c[n], 0) | nofollow;
385
+ }
386
+
387
+ function busy(message) {
388
+ const err = new Error(message);
389
+ err.code = JOURNAL_BUSY;
390
+ return err;
391
+ }
392
+
393
+ function readNoFollow(path) {
394
+ const fd = fs.openSync(path, flagsOr("r", "O_RDONLY"));
395
+ try {
396
+ return fs.readFileSync(fd, "utf8");
397
+ } finally {
398
+ fs.closeSync(fd);
399
+ }
400
+ }
401
+
402
+ /** The lock as it is now: null when there is none. Refuses a symlink or any non-file. */
403
+ function readLock() {
404
+ let st;
405
+ try {
406
+ st = fs.lstatSync(lockFile);
407
+ } catch (err) {
408
+ if (isMissing(err)) return null;
409
+ throw err;
410
+ }
411
+ if (st.isSymbolicLink()) throw new Error(`the journal lock ${lockFile} is a symlink; refusing it`);
412
+ if (!st.isFile()) throw new Error(`the journal lock ${lockFile} is not a file; refusing it`);
413
+
414
+ let raw;
415
+ try {
416
+ raw = readNoFollow(lockFile);
417
+ } catch (err) {
418
+ if (isMissing(err)) return null;
419
+ throw err;
420
+ }
421
+ let owner = {};
422
+ try {
423
+ owner = JSON.parse(raw) || {};
424
+ } catch {
425
+ // Created but not yet written, or torn by a crash: judged by its mtime alone.
426
+ }
427
+ return { raw, pid: owner.pid, at: owner.at, token: owner.token, mtimeMs: st.mtimeMs };
428
+ }
429
+
430
+ function stale(held) {
431
+ const at = Number.isFinite(held.at) ? held.at : held.mtimeMs;
432
+ if (now() - at > lockStaleMs) return true;
433
+ return Number.isInteger(held.pid) && held.pid > 0 && !pidAlive(held.pid);
434
+ }
435
+
436
+ // Moves a stale lock aside, then checks it moved the lock it judged: another process may
437
+ // have broken it and taken a fresh one in between, and that one is put back (link never
438
+ // replaces a lock a third process took meanwhile).
439
+ // Breaking a stale lock never moves a lock it has not confirmed is the stale one. Breakers
440
+ // serialise on `${lockFile}.break` (O_EXCL, never followed); the one holding it re-reads the
441
+ // lock and unlinks it only while it still carries exactly the contents judged stale. A lock
442
+ // taken after that unlink can only be created by O_EXCL once the path is free, so no live
443
+ // lock is ever removed or put back by a breaker.
444
+ function breakStale(held) {
445
+ const breakFile = `${lockFile}.break`;
446
+ let fd;
447
+ try {
448
+ fd = fs.openSync(breakFile, flagsOr("wx", "O_WRONLY", "O_CREAT", "O_EXCL"), 0o600);
449
+ } catch (err) {
450
+ if (!err || err.code !== "EEXIST") throw err;
451
+ clearStaleBreak(breakFile);
452
+ return;
453
+ }
454
+ try {
455
+ fs.closeSync(fd);
456
+ if (testHooks.beforeBreak) testHooks.beforeBreak();
457
+ let current = null;
458
+ try {
459
+ current = readNoFollow(lockFile);
460
+ } catch {
461
+ current = null;
462
+ }
463
+ if (current !== null && current === held.raw) {
464
+ try {
465
+ fs.unlinkSync(lockFile);
466
+ log(`loopctl journal: broke a stale lock on ${file} (pid ${held.pid ?? "unknown"})`);
467
+ } catch (err) {
468
+ if (!isMissing(err)) throw err;
469
+ }
470
+ }
471
+ } finally {
472
+ try {
473
+ fs.unlinkSync(breakFile);
474
+ } catch {
475
+ /* ignore */
476
+ }
477
+ }
478
+ }
479
+
480
+ // A breaker that died holding the break file would stop every later break; its file is
481
+ // removed once it is older than the stale bound. A symlink there is never followed or removed.
482
+ function clearStaleBreak(breakFile) {
483
+ let st;
484
+ try {
485
+ st = fs.lstatSync(breakFile);
486
+ } catch {
487
+ return;
488
+ }
489
+ if (!st.isFile()) return;
490
+ if (now() - st.mtimeMs > lockStaleMs) {
491
+ try {
492
+ fs.unlinkSync(breakFile);
493
+ } catch {
494
+ /* another breaker removed it */
495
+ }
496
+ }
497
+ }
498
+
499
+ /**
500
+ * Takes the journal lock: `${file}.lock`, created O_CREAT|O_EXCL (which never follows a
501
+ * symlink), 0600, holding this process's pid, the time and a token. Waits up to
502
+ * `lockWaitMs` for a live holder; breaks a stale one. Throws JOURNAL_BUSY when the wait runs
503
+ * out, and refuses a lock path that is a symlink.
504
+ */
505
+ function lock() {
506
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
507
+ const token = Buffer.from(randomBytes(8)).toString("hex");
508
+ const deadline = now() + lockWaitMs;
509
+ // Bounds the tries that do not sleep (a lock released or broken under us), so a lock that
510
+ // reappears on every try cannot spin for ever.
511
+ let spins = 0;
512
+
513
+ for (;;) {
514
+ let fd;
515
+ try {
516
+ fd = fs.openSync(lockFile, flagsOr("wx", "O_WRONLY", "O_CREAT", "O_EXCL"), 0o600);
517
+ } catch (err) {
518
+ if (!err || err.code !== "EEXIST") throw err;
519
+ const held = readLock();
520
+ if (held !== null && !stale(held)) {
521
+ if (now() >= deadline) {
522
+ throw busy(
523
+ `the journal ${file} is busy: another process of this session (pid ${held.pid ?? "unknown"}) ` +
524
+ `has held its lock for more than ${lockWaitMs} ms`,
525
+ );
526
+ }
527
+ sleep(lockRetryMs);
528
+ continue;
529
+ }
530
+ spins += 1;
531
+ if (spins > 100) throw busy(`the journal ${file} is busy: its lock could not be taken`);
532
+ if (held !== null) breakStale(held);
533
+ continue;
534
+ }
535
+
536
+ try {
537
+ fs.writeSync(fd, JSON.stringify({ pid, at: now(), token }));
538
+ } catch (err) {
539
+ fs.closeSync(fd);
540
+ fd = undefined;
541
+ try {
542
+ fs.unlinkSync(lockFile);
543
+ } catch {
544
+ /* ignore */
545
+ }
546
+ throw err;
547
+ } finally {
548
+ if (fd !== undefined) fs.closeSync(fd);
549
+ }
550
+ return token;
551
+ }
552
+ }
553
+
554
+ /** Releases the lock, only if it is still this call's (a lock broken as stale is another's). */
555
+ function unlock(token) {
556
+ try {
557
+ const held = readLock();
558
+ if (held && held.token === token) fs.unlinkSync(lockFile);
559
+ else log(`loopctl journal: the lock on ${file} was taken from this process before it released it`);
560
+ } catch (err) {
561
+ log(`loopctl journal: cannot release the lock on ${file}: ${err.message}`);
562
+ }
563
+ }
564
+
565
+ function withLock(fn) {
566
+ const token = lock();
567
+ try {
568
+ return fn();
569
+ } finally {
570
+ unlock(token);
571
+ }
572
+ }
573
+
574
+ /** Appends one entry, fsynced, under the lock. Throws when it could not be made durable. */
575
+ function append(fields) {
576
+ return withLock(() => appendLocked(fields));
577
+ }
578
+
579
+ function appendLocked(fields) {
580
+ const entries = read();
581
+
582
+ let existed = true;
583
+ let tornTail = false;
584
+ try {
585
+ const text = fs.readFileSync(file, "utf8");
586
+ tornTail = text.length > 0 && !text.endsWith("\n");
587
+ } catch (err) {
588
+ if (!isMissing(err)) throw err;
589
+ existed = false;
590
+ }
591
+
592
+ if (testHooks.afterAppendRead) testHooks.afterAppendRead();
593
+
594
+ const entry = { ...fields, seq: lastSeq + 1 };
595
+ const line = `${tornTail ? "\n" : ""}${JSON.stringify(entry)}\n`;
596
+
597
+ const fd = fs.openSync(file, appendFlags(), 0o600);
598
+ try {
599
+ fs.writeSync(fd, line);
600
+ fs.fsyncSync(fd);
601
+ } finally {
602
+ fs.closeSync(fd);
603
+ }
604
+ if (!existed) fsyncDir();
605
+
606
+ lastSeq = entry.seq;
607
+ pendingHint = entries.length + 1;
608
+ ensureTimer();
609
+ return entry;
610
+ }
611
+
612
+ /**
613
+ * Rewrites the journal without `eventIds`, under the lock. Returns false when it could not,
614
+ * a busy lock included: the entries stay, and the next round (the 30 s timer) settles them.
615
+ */
616
+ function settle(eventIds) {
617
+ if (eventIds.size === 0) return true;
618
+ let token;
619
+ try {
620
+ token = lock();
621
+ } catch (err) {
622
+ log(`loopctl journal: cannot settle ${file}: ${err.message}; the next round retries`);
623
+ return false;
624
+ }
625
+ try {
626
+ return settleLocked(eventIds);
627
+ } finally {
628
+ unlock(token);
629
+ }
630
+ }
631
+
632
+ function settleLocked(eventIds) {
633
+ let remaining;
634
+ try {
635
+ remaining = read().filter((e) => !eventIds.has(e.event_id));
636
+ } catch (err) {
637
+ log(`loopctl journal: cannot settle ${file}: ${err.message}`);
638
+ return false;
639
+ }
640
+
641
+ if (testHooks.afterSettleRead) testHooks.afterSettleRead();
642
+
643
+ if (remaining.length === 0) {
644
+ try {
645
+ fs.unlinkSync(file);
646
+ } catch (err) {
647
+ if (!isMissing(err)) {
648
+ log(`loopctl journal: cannot remove ${file}: ${err.message}`);
649
+ return false;
650
+ }
651
+ }
652
+ fsyncDir();
653
+ pendingHint = 0;
654
+ return true;
655
+ }
656
+
657
+ const tmp = `${file}.${pid}.${Buffer.from(randomBytes(6)).toString("hex")}.tmp`;
658
+ try {
659
+ const fd = fs.openSync(tmp, "wx", 0o600);
660
+ try {
661
+ fs.writeSync(fd, remaining.map((e) => `${JSON.stringify(e)}\n`).join(""));
662
+ fs.fsyncSync(fd);
663
+ } finally {
664
+ fs.closeSync(fd);
665
+ }
666
+ fs.renameSync(tmp, file);
667
+ fsyncDir();
668
+ pendingHint = remaining.length;
669
+ return true;
670
+ } catch (err) {
671
+ try {
672
+ fs.unlinkSync(tmp);
673
+ } catch {
674
+ /* ignore */
675
+ }
676
+ log(`loopctl journal: cannot settle ${file}: ${err.message}`);
677
+ return false;
678
+ }
679
+ }
680
+
681
+ // ---------------------------------------------------------------------------------------
682
+ // The timer
683
+
684
+ function ensureTimer() {
685
+ if (timer !== null) return;
686
+ timer = setTimer(() => {
687
+ drain().catch(() => {});
688
+ }, intervalMs);
689
+ if (timer && typeof timer.unref === "function") timer.unref();
690
+ }
691
+
692
+ function stopTimer() {
693
+ if (timer !== null) {
694
+ clearTimer(timer);
695
+ timer = null;
696
+ }
697
+ }
698
+
699
+ // ---------------------------------------------------------------------------------------
700
+ // The replay
701
+
702
+ function body(entries, limit) {
703
+ const out = [];
704
+ let bytes = 0;
705
+ for (const e of entries) {
706
+ const size = Buffer.byteLength(JSON.stringify(wire(e)));
707
+ if (out.length > 0 && (out.length >= limit || bytes + size > maxBodyBytes)) break;
708
+ out.push(e);
709
+ bytes += size;
710
+ }
711
+ return out;
712
+ }
713
+
714
+ // The body as it goes out: each entry keeps its journal seq unless that is not greater than
715
+ // the one before it, which only a journal written without the lock can hold (two processes
716
+ // that read one last seq, or a process older than the lock). Such an entry goes out one past
717
+ // the one before it, in the order the file holds them (read() sorts stably, so the order
718
+ // written). loopctl orders a body by seq and nothing else, and settles by event_id, so the
719
+ // body is otherwise the one the file holds.
720
+ function ascending(entries) {
721
+ let previous = null;
722
+ let raised = 0;
723
+ const out = entries.map((e) => {
724
+ const seq = previous === null || e.seq > previous ? e.seq : previous + 1;
725
+ if (seq !== e.seq) raised += 1;
726
+ previous = seq;
727
+ return { ...wire(e), seq };
728
+ });
729
+ if (raised > 0) {
730
+ log(`loopctl journal: ${raised} entr${raised === 1 ? "y repeats" : "ies repeat"} a seq in ${file}; sent renumbered in the order written`);
731
+ }
732
+ return out;
733
+ }
734
+
735
+ function describe(e) {
736
+ return `entry ${e.event_id} (seq ${e.seq}, ${e.kind} on story ${e.story_id})`;
737
+ }
738
+
739
+ async function run() {
740
+ let limit = maxEntries;
741
+
742
+ for (;;) {
743
+ const entries = readSafely();
744
+ if (entries.length === 0) {
745
+ stopTimer();
746
+ return { pending: 0 };
747
+ }
748
+ ensureTimer();
749
+
750
+ const id = holderId();
751
+ if (typeof id !== "string" || id === "") {
752
+ return { pending: entries.length, waiting: "no holder credential to replay under" };
753
+ }
754
+
755
+ const sent = body(entries, limit);
756
+ const res = await replayHolder({ entries: ascending(sent) }, { apiCall, holderId: id });
757
+
758
+ if (res && res.error) {
759
+ if (unreachable(res) || res.status === 429) return { pending: entries.length };
760
+
761
+ const code = errorCode(res.body);
762
+ if (FINAL_BODY_CODES.has(code) || (res.status === 413 && sent.length === 1)) {
763
+ const why = code || `http_${res.status}`;
764
+ for (const e of sent) {
765
+ log(`loopctl journal: ${describe(e)} refused (${why}); dropped from the journal`);
766
+ }
767
+ if (!settle(new Set(sent.map((e) => e.event_id)))) return { pending: entries.length };
768
+ continue;
769
+ }
770
+
771
+ if (res.status === 413) {
772
+ limit = Math.max(1, Math.floor(sent.length / 2));
773
+ continue;
774
+ }
775
+
776
+ // holder_ended, an unknown holder, a refused key: the next holder or tick decides.
777
+ return { pending: entries.length, error: res };
778
+ }
779
+
780
+ const results = res && Array.isArray(res.results) ? res.results : [];
781
+ const byId = new Map(sent.map((e) => [e.event_id, e]));
782
+ const settled = new Set();
783
+ const fenced = [];
784
+
785
+ for (const r of results) {
786
+ if (!r || !byId.has(r.event_id) || !SETTLING_OUTCOMES.has(r.outcome)) continue;
787
+ const e = byId.get(r.event_id);
788
+ const code = r.error && r.error.code;
789
+
790
+ if (r.outcome === "refused" && code === "busy") continue;
791
+
792
+ settled.add(r.event_id);
793
+ if (r.outcome === "fenced") {
794
+ fenced.push({ event_id: e.event_id, seq: e.seq, kind: e.kind, story_id: e.story_id });
795
+ }
796
+ if (r.outcome === "refused") {
797
+ log(`loopctl journal: ${describe(e)} refused (${code || "refused"}); dropped from the journal`);
798
+ }
799
+ }
800
+
801
+ if (fenced.length > 0) {
802
+ lastFenced = { at: new Date(now()).toISOString(), entries: fenced };
803
+ }
804
+
805
+ if (settled.size === 0 || !settle(settled)) return { pending: entries.length };
806
+ limit = maxEntries;
807
+ }
808
+ }
809
+
810
+ /** Replays the journal now; one run at a time, a second caller shares the first's. */
811
+ function drain() {
812
+ if (!file) return Promise.resolve({ pending: 0 });
813
+ if (draining) return draining;
814
+ draining = run().finally(() => {
815
+ draining = null;
816
+ });
817
+ return draining;
818
+ }
819
+
820
+ /** After an answered loopctl call: replay what is owed, without waiting for it. */
821
+ function kick() {
822
+ if (!file || draining || pendingHint === 0) return;
823
+ drain().catch(() => {});
824
+ }
825
+
826
+ // ---------------------------------------------------------------------------------------
827
+ // The epochs a journaled entry is recorded at
828
+
829
+ function rememberEpoch(storyId, epoch) {
830
+ if (typeof storyId === "string" && Number.isInteger(epoch)) epochs.set(storyId, epoch);
831
+ }
832
+
833
+ /** Learns claim epochs from any answered body that carries a story row. */
834
+ function observe(responseBody) {
835
+ if (responseBody === null || typeof responseBody !== "object") return;
836
+ const candidates = [
837
+ responseBody,
838
+ responseBody.story,
839
+ responseBody.data,
840
+ responseBody.claim,
841
+ responseBody.claim && responseBody.claim.story,
842
+ ];
843
+ for (const c of candidates) {
844
+ if (storyShaped(c)) rememberEpoch(c.id, c.claim_epoch);
845
+ }
846
+ }
847
+
848
+ /** The epoch this session last saw for `storyId`, else its newest journaled entry's. */
849
+ function epochOf(storyId) {
850
+ if (epochs.has(storyId)) return epochs.get(storyId);
851
+ const own = readSafely().filter((e) => e.story_id === storyId);
852
+ return own.length > 0 ? own[own.length - 1].claim_epoch : null;
853
+ }
854
+
855
+ // ---------------------------------------------------------------------------------------
856
+ // The write
857
+
858
+ function newEventId() {
859
+ return uuidv7(now(), randomBytes);
860
+ }
861
+
862
+ /** True when a write now would be journaled on no answer. */
863
+ function active() {
864
+ if (!file) return false;
865
+ const id = holderId();
866
+ return (typeof id === "string" && id !== "") || pendingHint > 0;
867
+ }
868
+
869
+ function notJournaled(result, why) {
870
+ const base = result && typeof result.body === "string" ? result.body : "loopctl did not answer";
871
+ return { error: true, status: result ? result.status || 0 : 0, body: `${base}: ${why}` };
872
+ }
873
+
874
+ function record(fields, cause) {
875
+ let entry;
876
+ try {
877
+ entry = append(fields);
878
+ } catch (err) {
879
+ if (err && err.code === JOURNAL_BUSY) {
880
+ return notJournaled(
881
+ cause,
882
+ `loopctl is unreachable and ${err.message}, so this ${fields.kind} was NOT journaled; ` +
883
+ "make it again.",
884
+ );
885
+ }
886
+ return notJournaled(cause, `the write could not be journaled (${err.message}); make it again.`);
887
+ }
888
+
889
+ const pending = pendingHint;
890
+ const reason = cause ? `loopctl did not answer (${cause.body || `status ${cause.status}`})` : `${pending - 1} earlier journaled write(s) are not yet replayed`;
891
+ return {
892
+ queued: true,
893
+ event_id: entry.event_id,
894
+ seq: entry.seq,
895
+ pending,
896
+ message:
897
+ `${reason}; this ${entry.kind} is journaled and is sent, in the order written, when ` +
898
+ "loopctl answers. Keep working: nothing needs re-sending by hand.",
899
+ };
900
+ }
901
+
902
+ /**
903
+ * One note or checkpoint write. `send()` makes the direct attempt and answers apiCall's
904
+ * shape. The write is sent directly when nothing is owed; queued behind the journal when
905
+ * something is; and journaled when the direct attempt gets no answer.
906
+ *
907
+ * @param {{kind: "note"|"checkpoint", story_id: string, claim_epoch: number|null,
908
+ * event_id: string, payload: object, send: () => Promise<any>}} write
909
+ */
910
+ async function write({ kind, story_id, claim_epoch, event_id, payload, send }) {
911
+ if (!JOURNALED_KINDS.includes(kind)) throw new Error(`${kind} is never journaled`);
912
+ if (!active()) return send();
913
+
914
+ const fields = {
915
+ event_id,
916
+ kind,
917
+ story_id,
918
+ claim_epoch,
919
+ recorded_at: new Date(now()).toISOString(),
920
+ payload,
921
+ };
922
+ const tooLarge = Buffer.byteLength(JSON.stringify(fields)) > maxBodyBytes;
923
+ const noEpoch = !Number.isInteger(claim_epoch);
924
+
925
+ if (pendingHint > 0 || readSafely().length > 0) await drain();
926
+
927
+ if (pendingHint > 0) {
928
+ // Behind the journal, never ahead of it.
929
+ if (tooLarge) {
930
+ return notJournaled(
931
+ null,
932
+ `this ${kind} is too large to journal, and ${pendingHint} journaled write(s) must reach ` +
933
+ "loopctl before it; push the work to a wip/ branch and checkpoint with wip_branch.",
934
+ );
935
+ }
936
+ if (noEpoch) {
937
+ return notJournaled(
938
+ null,
939
+ `${pendingHint} journaled write(s) must reach loopctl first, and this session knows no ` +
940
+ `claim_epoch for story ${story_id}; pass claim_epoch.`,
941
+ );
942
+ }
943
+ return record(fields, null);
944
+ }
945
+
946
+ const result = await send();
947
+ if (!unreachable(result)) return result;
948
+
949
+ if (tooLarge) {
950
+ return notJournaled(
951
+ result,
952
+ `loopctl is unreachable and this ${kind} is too large to journal; push the work to a ` +
953
+ "wip/ branch and checkpoint with wip_branch.",
954
+ );
955
+ }
956
+ if (noEpoch) {
957
+ return notJournaled(
958
+ result,
959
+ `loopctl is unreachable and this session knows no claim_epoch for story ${story_id}, so ` +
960
+ "the write was not journaled; pass claim_epoch (the epoch your claim returned).",
961
+ );
962
+ }
963
+ return record(fields, result);
964
+ }
965
+
966
+ /** What the journal still owes: the `journal` block of the inbox tool's answer. */
967
+ function status() {
968
+ const entries = readSafely();
969
+ return {
970
+ pending: entries.length,
971
+ oldest_recorded_at: entries.length > 0 ? entries[0].recorded_at : null,
972
+ last_fenced: lastFenced,
973
+ };
974
+ }
975
+
976
+ /** Stops the retry timer (process shutdown). */
977
+ function stop() {
978
+ stopTimer();
979
+ }
980
+
981
+ // A journal an earlier process of this session left is replayed on the timer from the start.
982
+ if (readSafely().length > 0) ensureTimer();
983
+
984
+ return {
985
+ file,
986
+ lockFile,
987
+ write,
988
+ // The append behind write(), answering queued or why not. Exposed so a test can stand one
989
+ // journal in for a second process of the session inside another's critical section.
990
+ record,
991
+ drain,
992
+ // index.js's apiCall calls this after every answered request. It is exposed under its own
993
+ // name, not `kick`, because the tool-route trace (test/tool-surface.js) follows a called
994
+ // name to the function of that name: through `kick` it would credit the replay route to
995
+ // every tool that calls apiCall, when only a session with a journal ever sends it.
996
+ onAnswered: kick,
997
+ observe,
998
+ epochOf,
999
+ rememberEpoch,
1000
+ newEventId,
1001
+ active,
1002
+ status,
1003
+ stop,
1004
+ read: readSafely,
1005
+ };
1006
+ }
1007
+
1008
+ /** The inbox tool's answer with the journal block beside it (AC-52.62.6). */
1009
+ export function withJournal(result, journal) {
1010
+ const block = journal ? journal.status() : { pending: 0, oldest_recorded_at: null, last_fenced: null };
1011
+ if (result !== null && typeof result === "object" && !Array.isArray(result)) {
1012
+ return { ...result, journal: block };
1013
+ }
1014
+ return { result, journal: block };
1015
+ }