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.
@@ -57,12 +57,18 @@ export function holderKeyDir(env) {
57
57
  return home ? path.join(home, ".claude", "loopctl-holders") : null;
58
58
  }
59
59
 
60
- const NOOP = Object.freeze({ path: null, write: () => false, holds: () => false, remove: () => {} });
60
+ const NOOP = Object.freeze({
61
+ path: null,
62
+ write: () => false,
63
+ holds: () => false,
64
+ read: () => null,
65
+ remove: () => {},
66
+ });
61
67
 
62
68
  /**
63
69
  * @param {{ dir: string|null, sessionId: string|null, fsImpl?: typeof fs, getuid?: () => number }} opts
64
70
  * @returns {{ path: string|null, write: (key: string) => boolean, holds: (key: string) => boolean,
65
- * remove: (onlyIf?: string) => void }}
71
+ * read: () => string|null, remove: (onlyIf?: string) => void }}
66
72
  */
67
73
  export function createHolderKeyFile({ dir, sessionId, fsImpl = fs, getuid = process.getuid }) {
68
74
  const id = safeSessionId(sessionId);
@@ -110,6 +116,22 @@ export function createHolderKeyFile({ dir, sessionId, fsImpl = fs, getuid = proc
110
116
  }
111
117
  }
112
118
 
119
+ /**
120
+ * The key the file holds, or null when there is no regular, non-empty file at the key path.
121
+ * Another MCP process of the same session writes here when it rotates the holder's
122
+ * credential, so a process whose key was revoked by that rotation reads its successor here
123
+ * (lib/holder.js, "Two processes of one session").
124
+ */
125
+ function read() {
126
+ try {
127
+ if (fsImpl.lstatSync(target).isSymbolicLink()) return null;
128
+ const key = fsImpl.readFileSync(target, "utf8");
129
+ return key === "" ? null : key;
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+
113
135
  /**
114
136
  * Deletes the file; a missing one is fine. Synchronous, so it is safe in an exit handler.
115
137
  *
@@ -131,5 +153,5 @@ export function createHolderKeyFile({ dir, sessionId, fsImpl = fs, getuid = proc
131
153
  }
132
154
  }
133
155
 
134
- return { path: target, write, holds, remove };
156
+ return { path: target, write, holds, read, remove };
135
157
  }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * US-52.61: `holder_replay`, POST /api/v1/holders/:id/replay.
3
+ *
4
+ * A session that lost loopctl kept its notes and checkpoints in a local journal; this sends
5
+ * them, in the order it wrote them, on the session's own holder credential. loopctl answers
6
+ * one result per entry: applied, replayed (already applied), fenced (recorded after the claim
7
+ * ended, kept as history) or refused.
8
+ *
9
+ * The holder id is the session's own and is never taken from the caller: loopctl refuses
10
+ * 403 holder_mismatch for a key whose holder is not the path's, so a holder id passed in could
11
+ * only ever fail. The bound on a body is loopctl's (422 replay_too_large); this module checks
12
+ * only what it can say without that number: a non-empty list in strictly ascending seq.
13
+ * Everything an entry carries is judged per entry by loopctl, so one bad entry is refused
14
+ * there without holding back the others.
15
+ */
16
+
17
+ import { HOLDERS_PATH } from "./holder.js";
18
+
19
+ function refuse(body) {
20
+ return { error: true, status: 0, body };
21
+ }
22
+
23
+ /** @param {string} id */
24
+ export function replayPath(id) {
25
+ return `${HOLDERS_PATH}/${encodeURIComponent(id)}/replay`;
26
+ }
27
+
28
+ /**
29
+ * @param {{entries?: unknown}} args
30
+ * @param {{apiCall: Function, holderId: string | null | undefined}} deps
31
+ */
32
+ export async function replayHolder({ entries } = {}, { apiCall, holderId } = {}) {
33
+ if (typeof holderId !== "string" || holderId === "") {
34
+ return refuse(
35
+ "This session holds no live holder credential, so it has nothing to replay under. " +
36
+ "Call holder_register first; entries of an earlier holder of this session come back fenced.",
37
+ );
38
+ }
39
+
40
+ if (!Array.isArray(entries) || entries.length === 0) {
41
+ return refuse("`entries` is a non-empty list of journal entries.");
42
+ }
43
+
44
+ let previous = null;
45
+ for (const [i, entry] of entries.entries()) {
46
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
47
+ return refuse(`entries[${i}] is not an object.`);
48
+ }
49
+ if (!Number.isInteger(entry.seq)) {
50
+ return refuse(`entries[${i}].seq is not an integer.`);
51
+ }
52
+ if (previous !== null && entry.seq <= previous) {
53
+ return refuse(
54
+ `entries[${i}].seq (${entry.seq}) is not greater than the one before it (${previous}); ` +
55
+ "send the journal in the order it was written.",
56
+ );
57
+ }
58
+ previous = entry.seq;
59
+ }
60
+
61
+ return apiCall("POST", replayPath(holderId), { entries });
62
+ }
package/lib/holder.js CHANGED
@@ -12,11 +12,13 @@
12
12
  * register fails for any reason (an older server answering 404, an agent-rooted tenant
13
13
  * answering 403, a network error, the startup timeout), `agentKey()` keeps answering
14
14
  * LOOPCTL_AGENT_KEY and the session works exactly as it did before. A heartbeat refused
15
- * 401/404/409 means the credential or holder is gone (a laptop slept past the lease, the
16
- * holder was ended): the next tick registers again, which loopctl answers with the SAME
17
- * holder while it is live. A heartbeat refused 409 holder_lease_expired (US-52.19) ended the
18
- * holder and released its claims, so the register makes a NEW holder, and the lapse is
19
- * logged to stderr. A network error leaves the credential in place for the next tick. A
15
+ * 401/404/409 means the credential or holder is gone (another process of the session rotated
16
+ * it, a laptop slept past the lease, the holder was ended): the heartbeat first takes up the
17
+ * key file's credential when it holds one other than the refused key and beats once with it,
18
+ * and registers only when there is none or that beat is refused too ("Two processes of one
19
+ * session"); loopctl answers a register with the SAME holder while it is live. A heartbeat
20
+ * refused 409 holder_lease_expired (US-52.19) ended the holder and released its claims, so
21
+ * the register makes a NEW holder, and the lapse is logged to stderr. A network error leaves the credential in place for the next tick. A
20
22
  * register that fails TRANSIENTLY (no answer, a timeout, 429 or 5xx, at startup or after a
21
23
  * refused heartbeat) arms the timer anyway, so the session registers once loopctl answers
22
24
  * (US-52.13's partition answer). A refusal (any other 4xx: an older server's 404, 403
@@ -38,9 +40,58 @@
38
40
  * The raw credential is never returned by a tool. Outside this process's memory it exists in
39
41
  * one place: the holder credential file (US-52.28, lib/holder-key-file.js),
40
42
  * $HOME/.claude/loopctl-holders/<session_id>.key, mode 0600, which a hook of the same session
41
- * reads to call the inbox as this holder. It is written whenever this process adopts a
42
- * credential (register, every rotation) and deleted the moment it stops holding one (end, a
43
- * heartbeat refused as gone, process exit). A process with no session marker writes none.
43
+ * reads to call the inbox as this holder. The file belongs to the process that wrote it last:
44
+ * - a register (startup, every rotation) writes it, over whatever it held;
45
+ * - a successful heartbeat writes it only when it is missing, never over another key;
46
+ * - a key adopted from the file is never written while the file is there. When the file is
47
+ * gone (the process that wrote it crashed and its exit handler deleted it), the next
48
+ * heartbeat writes it, and from then on this process owns it, and the holder, as if it had
49
+ * minted the key;
50
+ * - only the process that wrote it deletes it, and only while it still holds that process's
51
+ * key: when this process stops holding a credential (end, a recovery that could not
52
+ * register, process exit).
53
+ * end() ends the holder only when this process owns it. When another process does (the file
54
+ * holds another key, or this process adopted the key and never wrote the file), end() sends
55
+ * nothing and drops its own state. A process with no session marker writes no file.
56
+ *
57
+ * ## Two processes of one session
58
+ *
59
+ * A register naming a session whose holder is still live ROTATES that holder's credential and
60
+ * revokes every earlier key (loopctl's `Holders.rotate_holder/3`). So two MCP processes of one
61
+ * session (the old and the new one across an `/mcp` reconnect, or any other duplicate) revoke
62
+ * each other's key: each register kills the other's credential, and an end by either kills
63
+ * both. Before this section the dead process kept sending its revoked key, every call 401
64
+ * "Invalid API key", until its next heartbeat re-registered and revoked the other one's
65
+ * (2026-11-23, minis and mac-mini). Three rules make them converge on one key instead:
66
+ *
67
+ * - **A 401 on the holder credential recovers once and retries once** (`withHolderRecovery`,
68
+ * wrapped around index.js's one request function). The recovery adopts the key file's
69
+ * credential when it holds one other than the refused key (a sibling rotated and wrote it),
70
+ * and otherwise registers, which rotates. A 401 applied nothing, so the retry is safe.
71
+ * Concurrent 401s share one recovery, so ten parallel calls rotate once. A request pinned
72
+ * with `exactKey` recovers too when the key it pinned is the holder credential (the journal's
73
+ * replay, holder_replay). Only the holder's own register, heartbeat and end are never
74
+ * retried: they are sent with `noRecover: true`, which keeps the recovery from recursing
75
+ * into itself. A request on LOOPCTL_AGENT_KEY or any other key is a real bad key, and its
76
+ * 401 is returned unchanged.
77
+ * - **A heartbeat refused 401/404/409 takes the file's newer credential before it registers**,
78
+ * and beats once more with it; only when there is none, or that beat is refused too, does it
79
+ * register. Registering would revoke the sibling and start the ping-pong.
80
+ * - **An end never ends a holder another process holds.** When the key file holds a key other
81
+ * than this process's, or this process adopted its key from the file and has not written the
82
+ * file since, the holder belongs to the process that wrote the file: end() drops this
83
+ * process's own state and sends nothing. Ending it would revoke the live process's
84
+ * credential and release its claims.
85
+ *
86
+ * Ownership follows the file (the list under "The session id"). An adopted key's file is the
87
+ * writer's: this process never deletes it, and writes it only when it is missing, which makes
88
+ * this process the owner, so its end() ends the holder rather than leaving the claims held
89
+ * until the lease runs out. A heartbeat never overwrites a key file holding another key: a
90
+ * heartbeat that succeeded and finds a foreign key raced a newer rotation, and the next 401
91
+ * adopts it. Only a register, which just revoked every other key, overwrites. The holder id is
92
+ * kept across an adoption; a key file names no holder, and when
93
+ * the sibling's key belongs to another holder (the old one ended in between), the next beat is
94
+ * refused 404 and the session registers.
44
95
  *
45
96
  * ## A runner session registers nothing
46
97
  *
@@ -70,6 +121,10 @@ export function endPath(id) {
70
121
 
71
122
  const GONE = new Set([401, 404, 409]);
72
123
 
124
+ // The options of the holder's own register, heartbeat and end: the key sent verbatim, and
125
+ // never recovered by withHolderRecovery, whose recovery IS these requests (it would recurse).
126
+ const OWN_REQUEST = Object.freeze({ exactKey: true, noRecover: true });
127
+
73
128
  // The retry interval before loopctl has named one: the server's own heartbeat interval
74
129
  // (HOLDER_HEARTBEAT_SECONDS' default), so an unregistered session retries no faster than a
75
130
  // registered one beats.
@@ -122,6 +177,8 @@ export function createHolderSession(deps) {
122
177
  // US-52.28: where the holder credential file goes; $HOME/.claude/loopctl-holders by
123
178
  // default, nothing without a HOME.
124
179
  keyFileDir = holderKeyDir(env),
180
+ // The key file itself, for a test; built from keyFileDir and the session marker otherwise.
181
+ keyFile: injectedKeyFile = null,
125
182
  } = deps;
126
183
 
127
184
  async function beat(result) {
@@ -145,24 +202,61 @@ export function createHolderSession(deps) {
145
202
 
146
203
  // US-52.28: named by the session's own marker only. A generated uuid names a file no hook
147
204
  // can find, so a process without a marker gets a no-op file.
148
- const keyFile = createHolderKeyFile({ dir: keyFileDir, sessionId: envLockSessionId(env) });
205
+ const keyFile =
206
+ injectedKeyFile || createHolderKeyFile({ dir: keyFileDir, sessionId: envLockSessionId(env) });
149
207
  // The key this process last wrote, so a remove deletes only its own file.
150
208
  let writtenKey = null;
209
+ // True while the credential was taken from the key file rather than minted by this process's
210
+ // own register: the process that minted it owns the holder ("Two processes of one session").
211
+ let adopted = false;
212
+ // The one recovery in flight, shared by every 401 that arrives while it runs.
213
+ let recovering = null;
151
214
 
152
215
  /**
153
216
  * Makes the file match the credential held: written when one is, gone when none is. It reads
154
217
  * the file rather than trusting `writtenKey`: an old process of the same session can delete
155
218
  * this one's file in a race (lib/holder-key-file.js remove), and the next sync rewrites it.
219
+ *
220
+ * `minted` (a register just returned the credential, revoking every other key) overwrites
221
+ * whatever the file holds. Otherwise a file holding ANOTHER key is left alone: that key is a
222
+ * sibling process's newer rotation, and overwriting it with this process's soon-dead key is
223
+ * what made two processes ping-pong.
156
224
  */
157
- function syncKeyFile() {
225
+ function syncKeyFile({ minted = false } = {}) {
158
226
  if (credential) {
159
- if (keyFile.holds(credential) || keyFile.write(credential)) writtenKey = credential;
227
+ if (keyFile.holds(credential)) {
228
+ if (!adopted) writtenKey = credential;
229
+ } else if (minted || keyFile.read() === null) {
230
+ if (keyFile.write(credential)) {
231
+ writtenKey = credential;
232
+ // This process wrote the file, so it owns the holder now: the process it adopted the
233
+ // key from is gone (its exit deleted the file), and nobody else would end it.
234
+ adopted = false;
235
+ }
236
+ }
160
237
  } else if (writtenKey !== null) {
161
238
  keyFile.remove(writtenKey);
162
239
  writtenKey = null;
163
240
  }
164
241
  }
165
242
 
243
+ /**
244
+ * The key file's credential when it is not the one just refused (this process's own). A key
245
+ * adopted and then refused is the credential itself by the time it is refused, so it is never
246
+ * taken up twice; and every register overwrites the file, so no older dead key comes back.
247
+ */
248
+ function siblingKey() {
249
+ const key = keyFile.read();
250
+ return key && key !== credential ? key : null;
251
+ }
252
+
253
+ function adopt(key) {
254
+ credential = key;
255
+ adopted = true;
256
+ // The sibling wrote the file; this process deletes only a file it wrote itself.
257
+ writtenKey = null;
258
+ }
259
+
166
260
  function plainKey() {
167
261
  return env.LOOPCTL_AGENT_KEY;
168
262
  }
@@ -189,6 +283,11 @@ export function createHolderSession(deps) {
189
283
  }
190
284
 
191
285
  async function register() {
286
+ return beat(await registerOnly());
287
+ }
288
+
289
+ /** register() without the after-beat hook: the recovery holds every waiting 401 until it ends. */
290
+ async function registerOnly() {
192
291
  // A runner session (loopctl-runner sets LOOP_MODE) is already a holder, placed with its
193
292
  // dispatch (US-52.15). Registering it as interactive made its branch a new work item on
194
293
  // every heartbeat's open, which the factory then placed again (2026-11-21).
@@ -205,7 +304,7 @@ export function createHolderSession(deps) {
205
304
  HOLDERS_PATH,
206
305
  { kind: "interactive", session_id: sessionId, host: hostname(), worktree: worktree() },
207
306
  key,
208
- { exactKey: true },
307
+ OWN_REQUEST,
209
308
  );
210
309
 
211
310
  if (gen !== generation) return result;
@@ -213,8 +312,12 @@ export function createHolderSession(deps) {
213
312
  if (result && !result.error && result.holder) {
214
313
  holder = result.holder;
215
314
  // `credential: null` means the key we sent is already this holder's; keep what we hold.
216
- if (result.credential && result.credential.raw_key) credential = result.credential.raw_key;
217
- syncKeyFile();
315
+ const minted = Boolean(result.credential && result.credential.raw_key);
316
+ if (minted) {
317
+ credential = result.credential.raw_key;
318
+ adopted = false;
319
+ }
320
+ syncKeyFile({ minted });
218
321
  ended = false;
219
322
  arm(result.heartbeat_seconds);
220
323
  } else if (transient(result)) {
@@ -225,16 +328,64 @@ export function createHolderSession(deps) {
225
328
  stopTimer();
226
329
  }
227
330
 
228
- return beat(result);
331
+ return result;
332
+ }
333
+
334
+ /**
335
+ * Replaces `staleKey`, a credential loopctl just refused, once per refusal however many
336
+ * requests saw it ("Two processes of one session"). Resolves to `{ key, adoptedKey, result }`:
337
+ * `key` is the credential to retry with (null when there is none), `adoptedKey` is true when
338
+ * it came from the key file, and `result` is the register's answer when one was sent.
339
+ *
340
+ * @param {string} staleKey
341
+ */
342
+ function recoverCredential(staleKey) {
343
+ if (!staleKey) return Promise.resolve({ key: null });
344
+ // Already replaced (a recovery finished, or a heartbeat adopted) or already dropped.
345
+ if (credential !== staleKey) return Promise.resolve({ key: credential || null });
346
+ if (!recovering) {
347
+ recovering = renew(staleKey).finally(() => {
348
+ recovering = null;
349
+ });
350
+ }
351
+ return recovering;
352
+ }
353
+
354
+ async function renew(staleKey) {
355
+ const sibling = siblingKey();
356
+ if (sibling) {
357
+ adopt(sibling);
358
+ return { key: sibling, adoptedKey: true };
359
+ }
360
+
361
+ const gen = generation;
362
+ const result = await registerOnly();
363
+ if (gen !== generation) return { key: null, result };
364
+
365
+ if (credential !== staleKey) return { key: credential || null, result };
366
+
367
+ if (!result || result.error) {
368
+ // Not registered: the refused credential is dead, so the session falls back to
369
+ // LOOPCTL_AGENT_KEY (and a transient failure's timer registers on its next tick).
370
+ credential = null;
371
+ holder = null;
372
+ adopted = false;
373
+ syncKeyFile();
374
+ }
375
+ return { key: null, result };
376
+ }
377
+
378
+ /** True when `key` is the holder credential this process sends right now. */
379
+ function holdsCredential(key) {
380
+ return Boolean(key) && key === credential;
229
381
  }
230
382
 
231
- async function heartbeat() {
383
+ async function heartbeat({ retried = false } = {}) {
232
384
  if (!holder || !credential) return register();
233
385
 
234
386
  const gen = generation;
235
- const result = await apiCall("POST", heartbeatPath(holder.id), null, credential, {
236
- exactKey: true,
237
- });
387
+ const key = credential;
388
+ const result = await apiCall("POST", heartbeatPath(holder.id), null, key, OWN_REQUEST);
238
389
 
239
390
  if (gen !== generation) return result;
240
391
 
@@ -244,13 +395,16 @@ export function createHolderSession(deps) {
244
395
  if (errorCode(result.body) === "holder_lease_expired") {
245
396
  log(
246
397
  `loopctl: holder ${holder.id} lapsed (its lease ran out before this heartbeat); ` +
247
- "its claims were released. Registering a new holder.",
398
+ "its claims were released. Taking up a newer credential or registering a new holder.",
248
399
  );
249
400
  }
250
- credential = null;
251
- holder = null;
252
- syncKeyFile();
253
- return register();
401
+
402
+ // A sibling's newer key in the file is taken up and beaten once; only without one, or
403
+ // when that beat is refused too, does the session register (and revoke the sibling's).
404
+ const recovered = await recoverCredential(key);
405
+ if (recovered.result) return beat(recovered.result);
406
+ if (recovered.key && !retried) return heartbeat({ retried: true });
407
+ return result;
254
408
  }
255
409
 
256
410
  if (result && !result.error && result.lease_until) {
@@ -270,12 +424,27 @@ export function createHolderSession(deps) {
270
424
 
271
425
  const id = holder.id;
272
426
  const key = credential;
427
+ const fileKey = keyFile.read();
428
+ // Another live process of this session holds the holder: it minted the key in the file, or
429
+ // this process only adopted its key from there. Ending the holder would revoke that
430
+ // process's credential and release its claims, so this one drops its own state only.
431
+ const heldElsewhere = adopted || (fileKey !== null && fileKey !== key);
432
+
273
433
  ended = true;
274
434
  credential = null;
435
+ adopted = false;
275
436
  // Before the request, so a slow or dropped end never leaves a revoked key on disk.
276
437
  syncKeyFile();
277
438
 
278
- const result = await apiCall("POST", endPath(id), null, key, { exactKey: true });
439
+ if (heldElsewhere) {
440
+ return {
441
+ ended: false,
442
+ holder,
443
+ reason: "another process of this session holds the holder's credential; it was left live",
444
+ };
445
+ }
446
+
447
+ const result = await apiCall("POST", endPath(id), null, key, OWN_REQUEST);
279
448
  if (result && !result.error && result.holder) holder = result.holder;
280
449
  return result;
281
450
  }
@@ -316,5 +485,62 @@ export function createHolderSession(deps) {
316
485
  }
317
486
  }
318
487
 
319
- return { agentKey, register, heartbeat, end, start, status, sessionId, dropKeyFile };
488
+ return {
489
+ agentKey,
490
+ register,
491
+ heartbeat,
492
+ end,
493
+ start,
494
+ status,
495
+ sessionId,
496
+ dropKeyFile,
497
+ holdsCredential,
498
+ recoverCredential,
499
+ };
500
+ }
501
+
502
+ /**
503
+ * Wraps `send` (index.js's one request function, `(method, path, body, keyOverride, opts)`)
504
+ * so a request that went out on the session's holder credential and came back 401 recovers
505
+ * the credential and is retried ONCE with the new one ("Two processes of one session"). A
506
+ * 401 means loopctl applied nothing, so the retry cannot do anything twice; a second 401 is
507
+ * returned as it is.
508
+ *
509
+ * The key a request went out on is `keyOverride` itself under `exactKey` (sent verbatim), and
510
+ * `resolveKey(keyOverride)` otherwise, so a pinned request on the holder credential (the
511
+ * journal's replay, holder_replay) recovers like any other.
512
+ *
513
+ * Never retried: a request marked `noRecover` (the holder's own register, heartbeat and end,
514
+ * so a recovery never recurses into itself), and a request whose key was not the holder
515
+ * credential when it was sent (LOOPCTL_AGENT_KEY, LOOPCTL_API_KEY, LOOPCTL_USER_KEY, an
516
+ * orchestrator key): a 401 there is a real bad key.
517
+ *
518
+ * @param {{
519
+ * send: Function,
520
+ * resolveKey: (keyOverride: string|undefined) => string|undefined,
521
+ * session: { holdsCredential: (key: string) => boolean,
522
+ * recoverCredential: (key: string) => Promise<{ key: string|null }> },
523
+ * }} deps
524
+ */
525
+ export function withHolderRecovery({ send, resolveKey, session }) {
526
+ return async function apiCallWithHolderRecovery(method, apiPath, body, keyOverride, opts = {}) {
527
+ // Decided before sending: by the time a 401 lands a concurrent recovery may already have
528
+ // replaced the credential, and this request must still recover onto the new one.
529
+ if (opts && opts.noRecover) return send(method, apiPath, body, keyOverride, opts);
530
+ const sent = opts && opts.exactKey ? keyOverride : resolveKey(keyOverride);
531
+ const viaHolder = sent ? session.holdsCredential(sent) : false;
532
+
533
+ const result = await send(method, apiPath, body, keyOverride, opts);
534
+ if (!viaHolder || !result || !result.error || result.status !== 401) return result;
535
+
536
+ let fresh = null;
537
+ try {
538
+ ({ key: fresh } = await session.recoverCredential(sent));
539
+ } catch {
540
+ return result;
541
+ }
542
+ if (!fresh || fresh === sent) return result;
543
+
544
+ return send(method, apiPath, body, fresh, opts);
545
+ };
320
546
  }
package/lib/work-items.js CHANGED
@@ -27,10 +27,18 @@ export function notesPath(storyId) {
27
27
  return `/api/v1/stories/${encodeURIComponent(storyId)}/notes`;
28
28
  }
29
29
 
30
- /** `POST /api/v1/stories/:id/notes`: append one note. */
30
+ /**
31
+ * `POST /api/v1/stories/:id/notes`: append one note.
32
+ *
33
+ * With `journal` (lib/holder-journal.js, US-52.62) the note carries a client UUIDv7
34
+ * `event_id` from its first attempt, and a note that gets no answer from loopctl is journaled
35
+ * and answered `{queued: true, event_id}`. Its journal entry needs the claim epoch it was
36
+ * written under: `claim_epoch` when given, else the one this session last saw for the story,
37
+ * else read from the story before the write (once per story; its answer is remembered).
38
+ */
31
39
  export async function writeWorkItemNote(
32
- { story_id, section, body, idempotency_key } = {},
33
- { apiCall } = {},
40
+ { story_id, section, body, idempotency_key, claim_epoch } = {},
41
+ { apiCall, journal = null } = {},
34
42
  ) {
35
43
  const bad = uuid(story_id, "story_id");
36
44
  if (bad) return bad;
@@ -47,12 +55,43 @@ export async function writeWorkItemNote(
47
55
  return refuse("`idempotency_key` must be a string.");
48
56
  }
49
57
 
58
+ if (claim_epoch !== undefined && claim_epoch !== null && !Number.isInteger(claim_epoch)) {
59
+ return refuse("`claim_epoch` must be an integer: the epoch the claim returned.");
60
+ }
61
+
50
62
  const payload = { section, body };
51
63
  if (typeof idempotency_key === "string" && idempotency_key !== "") {
52
64
  payload.idempotency_key = idempotency_key;
53
65
  }
54
66
 
55
- return apiCall("POST", notesPath(story_id), payload);
67
+ if (!journal) return apiCall("POST", notesPath(story_id), payload);
68
+
69
+ const event_id = journal.newEventId();
70
+ payload.event_id = event_id;
71
+ const send = () => apiCall("POST", notesPath(story_id), payload);
72
+
73
+ if (!journal.active()) return send();
74
+
75
+ let epoch = Number.isInteger(claim_epoch) ? claim_epoch : journal.epochOf(story_id);
76
+ if (!Number.isInteger(epoch)) {
77
+ // One read per story: its answer is what the journal remembers. A read that gets no
78
+ // answer leaves the epoch unknown, and the write says so if it must be journaled.
79
+ const read = await apiCall("GET", `/api/v1/stories/${encodeURIComponent(story_id)}`, null);
80
+ const seen = read && !read.error && read.story && read.story.claim_epoch;
81
+ if (Number.isInteger(seen)) {
82
+ journal.rememberEpoch(story_id, seen);
83
+ epoch = seen;
84
+ }
85
+ }
86
+
87
+ return journal.write({
88
+ kind: "note",
89
+ story_id,
90
+ claim_epoch: Number.isInteger(epoch) ? epoch : null,
91
+ event_id,
92
+ payload: { section, body },
93
+ send,
94
+ });
56
95
  }
57
96
 
58
97
  /** `GET /api/v1/stories/:id/notes`: one page, oldest first, `current` on the first page. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopctl-mcp-server",
3
- "version": "3.37.0",
3
+ "version": "3.39.1",
4
4
  "description": "MCP server for loopctl — structural trust for AI development loops",
5
5
  "type": "module",
6
6
  "main": "index.js",