loopctl-mcp-server 3.40.1 → 3.41.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.
@@ -15,6 +15,25 @@
15
15
  * server will repeat (4xx) are logged to stderr and not retried for that branch; a network
16
16
  * error, a 429 or a 5xx is retried on the next heartbeat. Nothing is created locally, and the
17
17
  * open is idempotent on the server, so a lost response costs one repeated call.
18
+ *
19
+ * ## A finished branch
20
+ *
21
+ * loopctl answers `outcome: "finished"` when the branch's most recent item ended at done (its
22
+ * pull request merged, or its holder closed it), and creates nothing. Such a branch is
23
+ * remembered for the life of the PROCESS, not the holder: a re-register must not ask again, and
24
+ * a new process asks once and is told the same. The automatic open never sends `new_item`; new
25
+ * work on a finished branch name is opened deliberately with work_item_open and `new_item: true`,
26
+ * which also makes this process open that branch again on its heartbeat.
27
+ *
28
+ * ## The base branch (US-54.9)
29
+ *
30
+ * The open carries `base_branch` only when the session was TOLD it: the environment variable
31
+ * LOOPCTL_BASE_BRANCH, when it is not blank (the e2e harness sets it on every session it
32
+ * starts). Otherwise the open names none and the server files the item under the repository's
33
+ * primary source, as before. Nothing is guessed from the checkout: a single-branch clone's
34
+ * refspec names the branch that was CLONED, which is as often the work branch as the base, and
35
+ * a guessed base no source carries is a 422 the opener never retries. A worktree sitting on the
36
+ * named base branch opens nothing, as on the default branch.
18
37
  */
19
38
 
20
39
  export const WORK_ITEMS_PATH = "/api/v1/work_items";
@@ -28,7 +47,10 @@ function present(value) {
28
47
  }
29
48
 
30
49
  /** `POST /api/v1/work_items`: open (or reopen) the item for a branch. */
31
- export async function openWorkItem({ repo_url, branch, title, epic_id } = {}, { apiCall } = {}) {
50
+ export async function openWorkItem(
51
+ { repo_url, branch, title, epic_id, base_branch, new_item } = {},
52
+ { apiCall } = {},
53
+ ) {
32
54
  if (!present(repo_url)) return refuse("`repo_url` is required: the repo's remote URL.");
33
55
  if (!present(branch)) return refuse("`branch` is required: the branch the work is on.");
34
56
  if (title !== undefined && title !== null && typeof title !== "string") {
@@ -37,10 +59,22 @@ export async function openWorkItem({ repo_url, branch, title, epic_id } = {}, {
37
59
  if (epic_id !== undefined && epic_id !== null && typeof epic_id !== "string") {
38
60
  return refuse("`epic_id` must be a UUID string.");
39
61
  }
62
+ // US-54.2: the branch the work merges into; omitted, the item is the project's primary
63
+ // (unlabelled) source's.
64
+ if (base_branch !== undefined && base_branch !== null && typeof base_branch !== "string") {
65
+ return refuse("`base_branch` must be a branch name string.");
66
+ }
67
+
68
+ if (new_item !== undefined && new_item !== null && typeof new_item !== "boolean") {
69
+ return refuse("`new_item` must be a boolean.");
70
+ }
40
71
 
41
72
  const payload = { repo_url, branch };
73
+ // Only a deliberate new item is asked for; the server's default is to answer a finished one.
74
+ if (new_item === true) payload.new_item = true;
42
75
  if (present(title)) payload.title = title;
43
76
  if (present(epic_id)) payload.epic_id = epic_id;
77
+ if (present(base_branch)) payload.base_branch = base_branch;
44
78
  return apiCall("POST", WORK_ITEMS_PATH, payload);
45
79
  }
46
80
 
@@ -56,19 +90,34 @@ function final(result) {
56
90
  * apiCall: Function, // (method, path, body, key, opts) => result
57
91
  * git: (args: string[]) => Promise<string|null>, // stdout trimmed, null on failure
58
92
  * worktree: () => string,
93
+ * env?: Record<string, string|undefined>, // default process.env
59
94
  * log?: (line: string) => void,
60
95
  * }} deps
61
96
  */
62
97
  export function createBranchItemOpener(deps) {
63
- const { apiCall, git, worktree, log = (line) => process.stderr.write(line + "\n") } = deps;
98
+ const {
99
+ apiCall,
100
+ git,
101
+ worktree,
102
+ env = process.env,
103
+ log = (line) => process.stderr.write(line + "\n"),
104
+ } = deps;
64
105
  let holderId = null;
65
106
  let done = new Set();
107
+ // Branches whose work loopctl answered as finished: per process, never reset by a new holder.
108
+ const finished = new Set();
66
109
 
67
110
  async function defaultBranch(wt) {
68
111
  const ref = await git(["-C", wt, "symbolic-ref", "refs/remotes/origin/HEAD"]);
69
112
  return present(ref) ? ref.trim().replace(/^refs\/remotes\/origin\//, "") : null;
70
113
  }
71
114
 
115
+ // The branch the work merges into, or null when the session was not told it (module doc).
116
+ function baseBranch() {
117
+ const fromEnv = env && env.LOOPCTL_BASE_BRANCH;
118
+ return present(fromEnv) ? fromEnv.trim() : null;
119
+ }
120
+
72
121
  /**
73
122
  * One heartbeat's look at the worktree. `holder` is the live holder, `credential` its raw
74
123
  * key. Returns what it did: "skipped", "opened", "refused" or "retry".
@@ -82,17 +131,25 @@ export function createBranchItemOpener(deps) {
82
131
 
83
132
  const wt = worktree();
84
133
  const branch = ((await git(["-C", wt, "rev-parse", "--abbrev-ref", "HEAD"])) || "").trim();
85
- if (branch === "" || branch === "HEAD" || done.has(branch)) return "skipped";
134
+ if (branch === "" || branch === "HEAD" || done.has(branch) || finished.has(branch)) {
135
+ return "skipped";
136
+ }
86
137
 
87
138
  const fallbackDefaults = ["main", "master"];
88
139
  const known = await defaultBranch(wt);
89
140
  if (known ? branch === known : fallbackDefaults.includes(branch)) return "skipped";
90
141
 
142
+ const base = baseBranch();
143
+ if (base !== null && branch === base) return "skipped";
144
+
91
145
  const repoUrl = ((await git(["-C", wt, "remote", "get-url", "origin"])) || "").trim();
92
146
  if (repoUrl === "") return "skipped";
93
147
 
148
+ const params = { repo_url: repoUrl, branch };
149
+ if (base !== null) params.base_branch = base;
150
+
94
151
  const result = await openWorkItem(
95
- { repo_url: repoUrl, branch },
152
+ params,
96
153
  { apiCall: (method, path, body) => apiCall(method, path, body, credential, { exactKey: true }) },
97
154
  );
98
155
 
@@ -103,8 +160,24 @@ export function createBranchItemOpener(deps) {
103
160
  log(`loopctl: work item for branch ${branch} not opened (${code}); not retrying it`);
104
161
  return "refused";
105
162
  }
163
+ if (result && result.outcome === "finished") {
164
+ finished.add(branch);
165
+ log(`loopctl: branch ${branch}'s work item has ended at done; not opening it again`);
166
+ return "finished";
167
+ }
106
168
  return "opened";
107
169
  }
108
170
 
109
- return { tick };
171
+ /**
172
+ * A deliberate work_item_open answered for `branch`: a new item (`new_item: true`, or any
173
+ * open that did not answer finished) means the branch has open work again, so the heartbeat
174
+ * may open it after a re-register. A finished answer is remembered like the heartbeat's own.
175
+ */
176
+ function noteOpen(branch, result) {
177
+ if (!present(branch) || !result || result.error) return;
178
+ if (result.outcome === "finished") finished.add(branch);
179
+ else finished.delete(branch);
180
+ }
181
+
182
+ return { tick, noteOpen };
110
183
  }
package/lib/factory.js CHANGED
@@ -72,8 +72,9 @@ export async function readDecisions({ since, limit } = {}, { apiCall } = {}) {
72
72
 
73
73
  /**
74
74
  * `intake_pause` / `intake_resume` (loopctl US-52.33): `POST /api/v1/projects/:id/intake/pause`
75
- * and `/resume` on the project's one live intake source. A pause stops PROMOTION and TRIAGE
76
- * only: the webhook keeps recording, and work past detected carries on. Each call carries an
75
+ * and `/resume` on ONE intake source of the project: the one `source_id` names (US-54.4), else
76
+ * the project's primary (unlabelled) source. A pause stops PROMOTION and TRIAGE only: the
77
+ * webhook keeps recording, and work past detected carries on. Each call carries an
77
78
  * `intervention_id`, generated when absent; pass the first one again to retry after a lost
78
79
  * response.
79
80
  */
@@ -93,8 +94,16 @@ function interventionId(intervention_id, randomUUID) {
93
94
  return bad ? { bad } : { id: intervention_id };
94
95
  }
95
96
 
97
+ // US-54.4: `source_id` is optional and sent only when given, so an absent one keeps the
98
+ // server's default (the project's primary source) rather than a null the server must answer.
99
+ function withSource(body, source_id) {
100
+ if (source_id === undefined || source_id === null) return { body };
101
+ const bad = uuid(source_id, "source_id");
102
+ return bad ? { bad } : { body: { ...body, source_id } };
103
+ }
104
+
96
105
  export async function pauseIntake(
97
- { project_id, reason, intervention_id } = {},
106
+ { project_id, reason, intervention_id, source_id } = {},
98
107
  { apiCall, randomUUID } = {},
99
108
  ) {
100
109
  const bad = uuid(project_id, "project_id");
@@ -107,14 +116,18 @@ export async function pauseIntake(
107
116
  const id = interventionId(intervention_id, randomUUID);
108
117
  if (id.bad) return id.bad;
109
118
 
110
- return apiCall("POST", `/api/v1/projects/${encodeURIComponent(project_id)}/intake/pause`, {
111
- reason,
112
- intervention_id: id.id,
113
- });
119
+ const request = withSource({ reason, intervention_id: id.id }, source_id);
120
+ if (request.bad) return request.bad;
121
+
122
+ return apiCall(
123
+ "POST",
124
+ `/api/v1/projects/${encodeURIComponent(project_id)}/intake/pause`,
125
+ request.body,
126
+ );
114
127
  }
115
128
 
116
129
  export async function resumeIntake(
117
- { project_id, intervention_id } = {},
130
+ { project_id, intervention_id, source_id } = {},
118
131
  { apiCall, randomUUID } = {},
119
132
  ) {
120
133
  const bad = uuid(project_id, "project_id");
@@ -123,7 +136,12 @@ export async function resumeIntake(
123
136
  const id = interventionId(intervention_id, randomUUID);
124
137
  if (id.bad) return id.bad;
125
138
 
126
- return apiCall("POST", `/api/v1/projects/${encodeURIComponent(project_id)}/intake/resume`, {
127
- intervention_id: id.id,
128
- });
139
+ const request = withSource({ intervention_id: id.id }, source_id);
140
+ if (request.bad) return request.bad;
141
+
142
+ return apiCall(
143
+ "POST",
144
+ `/api/v1/projects/${encodeURIComponent(project_id)}/intake/resume`,
145
+ request.body,
146
+ );
129
147
  }
package/lib/holder.js CHANGED
@@ -41,7 +41,8 @@
41
41
  * one place: the holder credential file (US-52.28, lib/holder-key-file.js),
42
42
  * $HOME/.claude/loopctl-holders/<session_id>.key, mode 0600, which a hook of the same session
43
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;
44
+ * - a register (startup, every rotation) writes it, over whatever it held when the register was
45
+ * sent; a key another process wrote while it was in flight (a concurrent register) is left;
45
46
  * - a successful heartbeat writes it only when it is missing, never over another key;
46
47
  * - a key adopted from the file is never written while the file is there. When the file is
47
48
  * gone (the process that wrote it crashed and its exit handler deleted it), the next
@@ -83,6 +84,22 @@
83
84
  * process's own state and sends nothing. Ending it would revoke the live process's
84
85
  * credential and release its claims.
85
86
  *
87
+ * - **A recovery registers at most once per `reregisterIntervalMs` per process** (one heartbeat
88
+ * interval by default), counted from the last RECOVERY register this process sent (the one a
89
+ * refusal triggered), so a lone process's first recovery is never delayed.
90
+ * Inside that window a recovery that finds no newer key in the file does not register: the
91
+ * process YIELDS. It drops the refused credential (and the file, when the file still holds that
92
+ * dead key), falls back to LOOPCTL_AGENT_KEY, keeps the holder id, and logs it; the refused
93
+ * request is re-sent once on LOOPCTL_AGENT_KEY unless it was pinned (`withHolderRecovery`).
94
+ * Each heartbeat tick after that takes up the file's key when it is one loopctl has not
95
+ * refused this process,
96
+ * and registers only once the window has passed. Two processes that both read the file before
97
+ * either wrote it register once each; the loser's next refusal yields instead of revoking the
98
+ * winner, and the yield clears the loser's dead key from the file so the winner's next heartbeat
99
+ * writes its live one there. Without the bound, that race repeated is the ping-pong
100
+ * (2026-11-24, x1: a new key every 16-44 s, none used). The startup register and an explicit
101
+ * holder_register are never held back.
102
+ *
86
103
  * Ownership follows the file (the list under "The session id"). An adopted key's file is the
87
104
  * writer's: this process never deletes it, and writes it only when it is missing, which makes
88
105
  * this process the owner, so its end() ends the holder rather than leaving the claims held
@@ -179,6 +196,11 @@ export function createHolderSession(deps) {
179
196
  keyFileDir = holderKeyDir(env),
180
197
  // The key file itself, for a test; built from keyFileDir and the session marker otherwise.
181
198
  keyFile: injectedKeyFile = null,
199
+ // The clock the re-register bound reads, in milliseconds.
200
+ now = () => Date.now(),
201
+ // The shortest gap between a register this process sent and a RECOVERY register
202
+ // ("Two processes of one session"): one server heartbeat interval by default.
203
+ reregisterIntervalMs = DEFAULT_HEARTBEAT_SECONDS * 1000,
182
204
  } = deps;
183
205
 
184
206
  async function beat(result) {
@@ -211,6 +233,15 @@ export function createHolderSession(deps) {
211
233
  let adopted = false;
212
234
  // The one recovery in flight, shared by every 401 that arrives while it runs.
213
235
  let recovering = null;
236
+ // When this process last SENT a RECOVERY register (after a refusal), for the bound. The startup
237
+ // register and an explicit holder_register are not counted: they are never held back.
238
+ let lastRegisterAt = null;
239
+ // The last holder credential loopctl refused this process: never taken up from the file again.
240
+ let refusedKey = null;
241
+
242
+ function reregisterAllowed() {
243
+ return lastRegisterAt === null || now() - lastRegisterAt >= reregisterIntervalMs;
244
+ }
214
245
 
215
246
  /**
216
247
  * Makes the file match the credential held: written when one is, gone when none is. It reads
@@ -218,15 +249,20 @@ export function createHolderSession(deps) {
218
249
  * this one's file in a race (lib/holder-key-file.js remove), and the next sync rewrites it.
219
250
  *
220
251
  * `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.
252
+ * what the file held when that register was SENT (`fileAtSend`). A key that appeared while it
253
+ * was in flight is a sibling's concurrent register: which of the two loopctl answered last is
254
+ * unknowable here, so the file is left, and whichever process loopctl refuses next takes up
255
+ * the other's key from it. Overwriting it could leave a revoked key in the file, which the
256
+ * live process never replaces (below) and the hooks would keep sending. Otherwise a file
257
+ * holding ANOTHER key is left alone: that key is a sibling process's newer rotation, and
258
+ * overwriting it with this process's soon-dead key is what made two processes ping-pong.
224
259
  */
225
- function syncKeyFile({ minted = false } = {}) {
260
+ function syncKeyFile({ minted = false, fileAtSend = null } = {}) {
226
261
  if (credential) {
227
- if (keyFile.holds(credential)) {
262
+ const current = keyFile.holds(credential) ? credential : keyFile.read();
263
+ if (current === credential) {
228
264
  if (!adopted) writtenKey = credential;
229
- } else if (minted || keyFile.read() === null) {
265
+ } else if (current === null || (minted && current === fileAtSend)) {
230
266
  if (keyFile.write(credential)) {
231
267
  writtenKey = credential;
232
268
  // This process wrote the file, so it owns the holder now: the process it adopted the
@@ -286,8 +322,12 @@ export function createHolderSession(deps) {
286
322
  return beat(await registerOnly());
287
323
  }
288
324
 
289
- /** register() without the after-beat hook: the recovery holds every waiting 401 until it ends. */
290
- async function registerOnly() {
325
+ /**
326
+ * register() without the after-beat hook: the recovery holds every waiting 401 until it ends.
327
+ * `recovery` marks a register sent because loopctl refused this process's credential, the
328
+ * kind the re-register bound counts.
329
+ */
330
+ async function registerOnly({ recovery = false } = {}) {
291
331
  // A runner session (loopctl-runner sets LOOP_MODE) is already a holder, placed with its
292
332
  // dispatch (US-52.15). Registering it as interactive made its branch a new work item on
293
333
  // every heartbeat's open, which the factory then placed again (2026-11-21).
@@ -299,6 +339,10 @@ export function createHolderSession(deps) {
299
339
  if (!key) return { error: true, status: 0, body: "LOOPCTL_AGENT_KEY is not set" };
300
340
 
301
341
  const gen = generation;
342
+ // Stamped when SENT: loopctl revokes the other keys as it answers, so a register that is
343
+ // slow or never answered counts toward the bound like one that came back.
344
+ if (recovery) lastRegisterAt = now();
345
+ const fileAtSend = keyFile.read();
302
346
  const result = await apiCall(
303
347
  "POST",
304
348
  HOLDERS_PATH,
@@ -317,7 +361,7 @@ export function createHolderSession(deps) {
317
361
  credential = result.credential.raw_key;
318
362
  adopted = false;
319
363
  }
320
- syncKeyFile({ minted });
364
+ syncKeyFile({ minted, fileAtSend });
321
365
  ended = false;
322
366
  arm(result.heartbeat_seconds);
323
367
  } else if (transient(result)) {
@@ -333,16 +377,21 @@ export function createHolderSession(deps) {
333
377
 
334
378
  /**
335
379
  * 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.
380
+ * requests saw it ("Two processes of one session"). Resolves to
381
+ * `{ key, adoptedKey, fallbackKey, result }`: `key` is the holder credential to retry with
382
+ * (null when there is none), `adoptedKey` is true when it came from the key file,
383
+ * `fallbackKey` is LOOPCTL_AGENT_KEY when the recovery left this process WITHOUT a holder
384
+ * credential (it yielded inside the re-register bound, or its register failed), and `result`
385
+ * is the register's answer when one was sent.
339
386
  *
340
387
  * @param {string} staleKey
341
388
  */
342
389
  function recoverCredential(staleKey) {
343
390
  if (!staleKey) return Promise.resolve({ key: null });
344
391
  // Already replaced (a recovery finished, or a heartbeat adopted) or already dropped.
345
- if (credential !== staleKey) return Promise.resolve({ key: credential || null });
392
+ if (credential !== staleKey) {
393
+ return Promise.resolve(credential ? { key: credential } : { key: null, ...fallback() });
394
+ }
346
395
  if (!recovering) {
347
396
  recovering = renew(staleKey).finally(() => {
348
397
  recovering = null;
@@ -352,36 +401,94 @@ export function createHolderSession(deps) {
352
401
  }
353
402
 
354
403
  async function renew(staleKey) {
404
+ refusedKey = staleKey;
355
405
  const sibling = siblingKey();
356
406
  if (sibling) {
357
407
  adopt(sibling);
358
408
  return { key: sibling, adoptedKey: true };
359
409
  }
360
410
 
411
+ // Registered too recently: another process of this session is most likely registering too,
412
+ // and a register now would revoke its live key and start the ping-pong.
413
+ if (!reregisterAllowed()) {
414
+ yieldCredential();
415
+ return { key: null, throttled: true, ...fallback() };
416
+ }
417
+
361
418
  const gen = generation;
362
- const result = await registerOnly();
419
+ const result = await registerOnly({ recovery: true });
363
420
  if (gen !== generation) return { key: null, result };
364
421
 
365
422
  if (credential !== staleKey) return { key: credential || null, result };
366
423
 
367
424
  if (!result || result.error) {
368
425
  // 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).
426
+ // LOOPCTL_AGENT_KEY. A transient failure keeps the holder id, so the next tick can take
427
+ // up a key a sibling wrote meanwhile before it registers over it (`resume`); a refusal is
428
+ // final and forgets the holder.
370
429
  credential = null;
371
- holder = null;
430
+ if (!transient(result)) holder = null;
372
431
  adopted = false;
373
432
  syncKeyFile();
433
+ return { key: null, result, ...fallback() };
374
434
  }
375
435
  return { key: null, result };
376
436
  }
377
437
 
438
+ // The key this process fell back to when it holds no holder credential: its own
439
+ // LOOPCTL_AGENT_KEY, which every unpinned request now goes out on (`agentKey()`).
440
+ function fallback() {
441
+ const key = plainKey();
442
+ return key ? { fallbackKey: key } : {};
443
+ }
444
+
445
+ /**
446
+ * Gives up the refused credential without registering: the session falls back to
447
+ * LOOPCTL_AGENT_KEY and keeps the holder id for `resume`. The file is deleted only when it
448
+ * still holds this process's dead key (syncKeyFile removes `writtenKey` only while the file
449
+ * holds it), so the live sibling's next heartbeat writes its own key there.
450
+ */
451
+ function yieldCredential() {
452
+ credential = null;
453
+ adopted = false;
454
+ syncKeyFile();
455
+ const seconds = Math.ceil(reregisterIntervalMs / 1000);
456
+ log(
457
+ "loopctl: the holder credential was refused again within " +
458
+ `${seconds}s of this process's last register; another MCP process of this session is ` +
459
+ "likely registering too. Using LOOPCTL_AGENT_KEY and taking up that process's key from " +
460
+ "the holder key file when it appears, instead of registering over it.",
461
+ );
462
+ }
463
+
464
+ /**
465
+ * A heartbeat tick with no credential. A holder this process knows and a key in the file that
466
+ * loopctl has not refused this process: take it up and beat with it. Otherwise register,
467
+ * unless a yield is still inside the re-register bound.
468
+ */
469
+ async function resume() {
470
+ // An ended process registers afresh, as before: end() was this process letting go.
471
+ if (ended) return register();
472
+ const fileKey = keyFile.read();
473
+ if (holder && fileKey && fileKey !== refusedKey) {
474
+ adopt(fileKey);
475
+ return heartbeat({ retried: true });
476
+ }
477
+ // Without a holder there is nothing to recover: the first register, or one after a refusal.
478
+ if (!holder) return register();
479
+ if (!reregisterAllowed()) {
480
+ return { error: true, status: 0, body: "holder re-register held back; using LOOPCTL_AGENT_KEY" };
481
+ }
482
+ return beat(await registerOnly({ recovery: true }));
483
+ }
484
+
378
485
  /** True when `key` is the holder credential this process sends right now. */
379
486
  function holdsCredential(key) {
380
487
  return Boolean(key) && key === credential;
381
488
  }
382
489
 
383
490
  async function heartbeat({ retried = false } = {}) {
384
- if (!holder || !credential) return register();
491
+ if (!holder || !credential) return resume();
385
492
 
386
493
  const gen = generation;
387
494
  const key = credential;
@@ -506,6 +613,20 @@ export function createHolderSession(deps) {
506
613
  * 401 means loopctl applied nothing, so the retry cannot do anything twice; a second 401 is
507
614
  * returned as it is.
508
615
  *
616
+ * When the recovery leaves the process with no holder credential (it yielded inside the
617
+ * re-register bound, or its register failed), an UNPINNED request is retried once on
618
+ * LOOPCTL_AGENT_KEY instead (`fallbackKey`). That is not a change of principal the earlier
619
+ * design guarded against: an unpinned request goes out on `agentKey()`, the process's own
620
+ * default key, and the holder credential and LOOPCTL_AGENT_KEY are both THIS process's keys for
621
+ * the SAME agent (the holder file is the session's own credential, the env var the process's
622
+ * own). Had the yield come a moment earlier, the request would have been sent on
623
+ * LOOPCTL_AGENT_KEY in the first place; returning its 401 only turned a recovered refusal into
624
+ * a failed tool call. A PINNED request (`exactKey`: the journal's replay, holder_replay, the
625
+ * branch open) is never re-sent on the fallback: its caller chose the holder identity because
626
+ * what it does depends on it (a checkpoint the current holder alone may write, an open only a
627
+ * holder credential may make), so on another key it would be refused, or recorded as
628
+ * someone else.
629
+ *
509
630
  * The key a request went out on is `keyOverride` itself under `exactKey` (sent verbatim), and
510
631
  * `resolveKey(keyOverride)` otherwise, so a pinned request on the holder credential (the
511
632
  * journal's replay, holder_replay) recovers like any other.
@@ -533,12 +654,14 @@ export function withHolderRecovery({ send, resolveKey, session }) {
533
654
  const result = await send(method, apiPath, body, keyOverride, opts);
534
655
  if (!viaHolder || !result || !result.error || result.status !== 401) return result;
535
656
 
536
- let fresh = null;
657
+ let recovered;
537
658
  try {
538
- ({ key: fresh } = await session.recoverCredential(sent));
659
+ recovered = (await session.recoverCredential(sent)) || {};
539
660
  } catch {
540
661
  return result;
541
662
  }
663
+ const pinned = Boolean(opts && opts.exactKey);
664
+ const fresh = recovered.key || (pinned ? null : recovered.fallbackKey || null);
542
665
  if (!fresh || fresh === sent) return result;
543
666
 
544
667
  return send(method, apiPath, body, fresh, opts);