loopctl-mcp-server 3.39.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.
package/README.md CHANGED
@@ -570,9 +570,9 @@ Key distribution for the dispatch pattern (Epic 26): per-dispatch ephemeral keys
570
570
  |---|---|
571
571
  | `signup` | **US-26.7.1.** Create a NEW **agent-rooted (KB-tier)** tenant and mint its one-time root API key — entirely through this call, no human operator, no hardware authenticator, no existing API key required. The tenant gets the FULL knowledge-wiki surface but **cannot** perform work-breakdown / chain-of-custody operations (those require a separate human-anchored tenant via the WebAuthn ceremony at `https://loopctl.com/signup`). Rate-limited per client IP (<= 5/hour). The `raw_key` is shown ONCE — save it immediately (e.g. as `LOOPCTL_USER_KEY`). Required: `name`, `slug`, `email`. |
572
572
  | `dispatch` | Mint an ephemeral, scoped api_key for a sub-agent dispatch, carrying its lineage path. The `raw_key` is returned ONCE — pass it to the sub-agent's launch args, never store it in env vars; it expires after `expires_in_seconds` (default 3600, max 14400). Required: `role` (`agent`/`orchestrator`), `agent_id`, and `parent_dispatch_id` for every caller a dispatch minted — a dispatch may only be minted INSIDE the caller's own lineage. Omitting `parent_dispatch_id` requests a ROOT dispatch (a new independent lineage tree), which only the tenant's `user`-role operator key may create; anyone else gets `403 root_dispatch_forbidden` with their own dispatch id in `remediation.your_dispatch_id`. A parent outside the caller's lineage is `403 parent_outside_caller_lineage`. Optional: `story_id`. **LCP-1 §9.2 signed profile:** optionally enroll an agent key via `agent_pubkey` (hex) + `alg` + an `attestation` (from `custody_sign_attestation`) + `attestation_conditions`. |
573
- | `holder_register` | **Register this session as a holder** (`POST /api/v1/holders`, US-52.13). The server does this at startup and heartbeats on a timer; call it to re-register after `holder_end`. Sends `LOOPCTL_AGENT_KEY` exactly, with `kind: interactive`, the session id (`CLAUDE_CODE_SESSION_ID`, else `CLAUDE_SESSION_ID`, else a per-process uuid), the host and the git top level. A live holder of the same session answers with the SAME holder and a new credential, which this process keeps in memory and sends on every agent-key request; the raw key is never returned to the caller. Each register and every rotation also writes it to the holder credential file `$HOME/.claude/loopctl-holders/<session_id>.key` (mode 0600, directory 0700, written atomically by temp file and rename), named by the same session id, so a hook of the same session (claude-config's SessionStart inbox read and its tool-round hook) can read the inbox as this holder. The id must match `[A-Za-z0-9._-]`; a process with no session marker, or a runner session (`LOOP_MODE`), writes no file. `403 custody_tier_required` on an agent-rooted tenant, `403 holder_mint_forbidden` for a dispatch-minted key, `422 agent_required` for a key naming no agent; on any refusal the session keeps using `LOOPCTL_AGENT_KEY`. |
574
- | `holder_heartbeat` | **Renew this session holder's lease now** (`POST /api/v1/holders/:id/heartbeat`), by the holder's own credential. Runs on its own every `heartbeat_seconds`. Also moves every uncapped claim this holder holds to the new lease (US-52.19). A 401, 404 or 409 (credential expired, holder ended) registers again; a `409 holder_lease_expired` means the lease ran out first, so loopctl ended the holder and released its claims: the session registers as a NEW holder (logged to stderr) and must re-claim. |
575
- | `holder_end` | **End this session holder** (`POST /api/v1/holders/:id/end`): sets `ended_at`, revokes its credential and releases every uncapped claim it holds (a `released` item event, reason "holder ended"), then falls back to `LOOPCTL_AGENT_KEY`. Deletes the holder credential file before the request is sent; a heartbeat refused as gone deletes it too, until a new register writes the new key. Runs on its own when stdin closes, on SIGTERM or on SIGINT, and any other exit still deletes the file. A repeated end writes nothing. |
573
+ | `holder_register` | **Register this session as a holder** (`POST /api/v1/holders`, US-52.13). The server does this at startup and heartbeats on a timer; call it to re-register after `holder_end`. Sends `LOOPCTL_AGENT_KEY` exactly, with `kind: interactive`, the session id (`CLAUDE_CODE_SESSION_ID`, else `CLAUDE_SESSION_ID`, else a per-process uuid), the host and the git top level. A live holder of the same session answers with the SAME holder and a new credential, which this process keeps in memory and sends on every agent-key request; the raw key is never returned to the caller. Each register and every rotation also writes it to the holder credential file `$HOME/.claude/loopctl-holders/<session_id>.key` (mode 0600, directory 0700, written atomically by temp file and rename), named by the same session id, so a hook of the same session (claude-config's SessionStart inbox read and its tool-round hook) can read the inbox as this holder. A register rotates the live holder's credential and revokes every earlier key, another MCP process of the same session's included (an `/mcp` reconnect), so you do not need it after a 401: a request sent on the holder credential that gets 401 takes up the newer key another process of the session wrote to the file, or else registers, and is retried once on its own (a pinned request on the holder credential, such as `holder_replay` and the journal's replay, recovers too; the holder's own register, heartbeat and end, a request on `LOOPCTL_AGENT_KEY` or any other key, and a second 401 are returned as they are; concurrent 401s share one recovery). The id must match `[A-Za-z0-9._-]`; a process with no session marker, or a runner session (`LOOP_MODE`), writes no file. `403 custody_tier_required` on an agent-rooted tenant, `403 holder_mint_forbidden` for a dispatch-minted key, `422 agent_required` for a key naming no agent; on any refusal the session keeps using `LOOPCTL_AGENT_KEY`. |
574
+ | `holder_heartbeat` | **Renew this session holder's lease now** (`POST /api/v1/holders/:id/heartbeat`), by the holder's own credential. Runs on its own every `heartbeat_seconds`. Also moves every uncapped claim this holder holds to the new lease (US-52.19). A 401, 404 or 409 (credential revoked or expired, holder ended) first takes up a newer key another process of this session wrote to the holder credential file and beats once with it; only without one, or when that beat is refused too, does it register again (which would revoke the other process's key); a `409 holder_lease_expired` means the lease ran out first, so loopctl ended the holder and released its claims: the session registers as a NEW holder (logged to stderr) and must re-claim. |
575
+ | `holder_end` | **End this session holder** (`POST /api/v1/holders/:id/end`): sets `ended_at`, revokes its credential and releases every uncapped claim it holds (a `released` item event, reason "holder ended"), then falls back to `LOOPCTL_AGENT_KEY`. Deletes the holder credential file before the request is sent; a heartbeat refused as gone deletes it too, until a new register writes the new key. Runs on its own when stdin closes, on SIGTERM or on SIGINT, and any other exit still deletes the file. A repeated end writes nothing. When another MCP process of this session holds the credential (the file holds another key, or this process took its key from the file) it sends no end and answers `ended: false`: ending would revoke that live process's key and release its claims; it drops only its own state, and the holder lapses on its lease if that process is gone too. |
576
576
  | `holder_replay` | **Replay what this session recorded while loopctl was unreachable** (`POST /api/v1/holders/:id/replay`, US-52.61), on this session's holder credential and to its own holder id. `entries` in strictly ascending `seq`, each `{event_id, seq, kind, story_id, claim_epoch, recorded_at, payload}`; only `note` (`{section, body}`) and `checkpoint` (`{branch, head_sha, diff` base64 `or wip_branch, done, next}`) replay, never a claim, stage move, report, review or verify. One result per entry in seq order: `applied` (held at that `claim_epoch`, through the verb's own checks), `replayed` (the `event_id` already applied with this payload: the first result, nothing written), `fenced` (the session held the story at that epoch and no longer does: a note becomes a `fenced_replay` event, a checkpoint is stored fenced for the current holder; the story does not move) or `refused` with `error.code` (`invalid_entry`, `not_found`, `event_id_conflict`, `not_holder`, `stale_claim_epoch`, `busy`, `fenced_note_limit` when the item already keeps 50 fenced notes from this holder or 200 from all late holders and nothing is written, a checkpoint refusal such as `fenced_checkpoint_limit`); one refusal never stops the rest. A holder that lapsed during the outage is replayed by the session's next holder, fenced. Refused whole: `403 holder_mismatch`, `409 holder_ended`, `422 replay_not_ordered`, `422 replay_too_large` (over 200 entries). Refused locally, sending nothing, with no live holder credential or a body out of seq order. |
577
577
  | `work_item_note` | **Write a note on a work item** (`POST /api/v1/stories/:id/notes`, US-52.17): `section` (plan, progress, decision, question) and `body`, appended and never edited, plus a `note_written` event on the story log in the same transaction. Sends this session's own key (its holder credential). Only the story's current holder writes one: `409 held_by_other_holder` when another session holds it, `409 not_holder` when nobody does, `404` for another tenant's story, `422` for an unknown section, an empty body, a body over 16384 bytes or a credential-shaped body. A writer repeating its own `idempotency_key` gets its first note back; a key another writer's note already carries is `409 idempotency_key_reused`. Every note carries a client UUIDv7 `event_id` (US-52.62); when loopctl does not answer (network error, timeout, 502/503/504) the note is journaled (`LOOPCTL_JOURNAL_DIR`) and answered `{queued: true, event_id}`, then replayed in order through `holder_replay`; while the journal holds entries a new note queues behind them. The journal entry needs the `claim_epoch` (optional argument; else the one the session last saw, else read from the story once). |
578
578
  | `work_item_notes` | **Read a work item's notes** (`GET /api/v1/stories/:id/notes`), oldest first; the first page carries `current`, the newest note of each section. Optional `section`, `limit` (default 50, max 200) and `after` (a page's `next_cursor`). `404` for another tenant's story, `422` for an unknown section or a cursor it did not return. |
package/index.js CHANGED
@@ -23,7 +23,7 @@ import { articleId } from "./lib/article-id.js";
23
23
  import { clientContextHeader } from "./lib/client-context.js";
24
24
  import { resolveLockSessionId } from "./lib/lock-session.js";
25
25
  import { createBranchItemOpener, openWorkItem } from "./lib/branch-item.js";
26
- import { createHolderSession } from "./lib/holder.js";
26
+ import { createHolderSession, withHolderRecovery } from "./lib/holder.js";
27
27
  import { replayHolder } from "./lib/holder-replay.js";
28
28
  import {
29
29
  createHolderJournal,
@@ -341,7 +341,23 @@ function cachedClientContextHeader() {
341
341
  return clientContextHeaderCache;
342
342
  }
343
343
 
344
- async function apiCall(
344
+ // Every request this server sends goes through apiCall: a request sent with the holder
345
+ // credential that gets 401 recovers the credential ONCE and is retried ONCE, here and not per
346
+ // tool (lib/holder.js, "Two processes of one session"). A pinned (exactKey) request on the
347
+ // holder credential recovers too: holder_replay and the journal's own replay. The holder's own
348
+ // register, heartbeat and end (noRecover) and a request on any other key come back as
349
+ // sendRequest answered them.
350
+ const holderRecoveringApiCall = withHolderRecovery({
351
+ send: (...args) => sendRequest(...args),
352
+ resolveKey,
353
+ session: holderSession,
354
+ });
355
+
356
+ async function apiCall(method, path, body, keyOverride, opts) {
357
+ return holderRecoveringApiCall(method, path, body, keyOverride, opts);
358
+ }
359
+
360
+ async function sendRequest(
345
361
  method,
346
362
  path,
347
363
  body,
@@ -3126,7 +3142,12 @@ async function holderHeartbeatTool() {
3126
3142
 
3127
3143
  async function holderEndTool() {
3128
3144
  const result = await holderSession.end();
3129
- return toContent(result && result.error ? result : holderSession.status());
3145
+ if (result && result.error) return toContent(result);
3146
+ // Another process of this session holds the holder, so nothing was ended (lib/holder.js).
3147
+ if (result && result.ended === false) {
3148
+ return toContent({ ...holderSession.status(), ended: false, reason: result.reason });
3149
+ }
3150
+ return toContent(holderSession.status());
3130
3151
  }
3131
3152
 
3132
3153
  // US-52.61: the offline journal, on the holder's own credential and to its own id. Only a live
@@ -8658,7 +8679,11 @@ const TOOLS = [
8658
8679
  "(exactly, never another variable) with kind interactive, this session's id, the host " +
8659
8680
  "and the git top level. loopctl answers with the SAME holder while it is live and a new " +
8660
8681
  "credential, which this process keeps in memory and sends on every agent-key request " +
8661
- "from then on; the credential is never returned to you. REFUSES: 403 " +
8682
+ "from then on; the credential is never returned to you. A register ROTATES the live " +
8683
+ "holder's credential and revokes every earlier key, including another MCP process of " +
8684
+ "this session's (an /mcp reconnect). You do not need it after a 401: a request on the " +
8685
+ "holder credential that gets 401 takes up the newer key that process wrote, or " +
8686
+ "registers, and is retried once by itself. REFUSES: 403 " +
8662
8687
  "custody_tier_required on an agent-rooted tenant, 403 holder_mint_forbidden for a " +
8663
8688
  "dispatch-minted key, 422 agent_required for a key naming no agent. On any refusal the " +
8664
8689
  "session keeps using LOOPCTL_AGENT_KEY.",
@@ -8671,7 +8696,9 @@ const TOOLS = [
8671
8696
  "RENEW THIS SESSION'S HOLDER LEASE NOW (POST /api/v1/holders/:id/heartbeat), by the " +
8672
8697
  "holder's own credential. The server does this every heartbeat_seconds on its own. " +
8673
8698
  "It also moves every uncapped claim the holder holds to the new lease. A 401, 404 or " +
8674
- "409 (credential expired, holder ended) makes it register again; 409 " +
8699
+ "409 (credential revoked or expired, holder ended) first takes up a newer credential " +
8700
+ "another MCP process of this session wrote to the holder key file and beats once with " +
8701
+ "it; only without one, or when that beat is refused too, does it register again. 409 " +
8675
8702
  "holder_lease_expired means the lease ran out first, so loopctl ended the holder and " +
8676
8703
  "released its claims: the session registers as a NEW holder and must re-claim.",
8677
8704
  inputSchema: { type: "object", properties: {} },
@@ -8682,7 +8709,10 @@ const TOOLS = [
8682
8709
  description:
8683
8710
  "END THIS SESSION'S HOLDER (POST /api/v1/holders/:id/end): sets ended_at and revokes " +
8684
8711
  "its credential; this process falls back to LOOPCTL_AGENT_KEY. The server does this " +
8685
- "itself when stdin closes or on SIGTERM. A repeated end writes nothing.",
8712
+ "itself when stdin closes or on SIGTERM. A repeated end writes nothing. When another " +
8713
+ "MCP process of this session holds the credential (the holder key file holds another " +
8714
+ "key, or this process took its key from there) it sends nothing and answers ended: " +
8715
+ "false: ending the holder would revoke that live process's key and release its claims.",
8686
8716
  inputSchema: { type: "object", properties: {} },
8687
8717
  },
8688
8718
 
@@ -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
  }
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopctl-mcp-server",
3
- "version": "3.39.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",