loopctl-mcp-server 3.37.0 → 3.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,6 +72,7 @@ Or if installed locally:
72
72
  | `LOOPCTL_AGENT_KEY` | Agent role API key (contract, claim, start, request-review) | -- |
73
73
  | `LOOPCTL_USER_KEY` | User role API key (minted at signup). Required for **first-time BYO LLM key provisioning** (`set_llm_config` / `llm_config` — see [First-time setup](#first-time-setup--provision-your-byo-llm-keys)), for destructive admin tools like `knowledge_bulk_publish`, and for the `runner_*` and `intake_source_*` tools plus `place_dispatch` in [Runner and delivery-loop tools](#runner-and-delivery-loop-tools); `resolve_escalation` prefers it and falls back to the holder credential. **Not for the whole of that section:** `story_stage` takes `LOOPCTL_AGENT_KEY`, and `force_unclaim_story` is `exact_role: :orchestrator`, where a user key is 403'd like any other non-member. | -- |
74
74
  | `LOOPCTL_STH_STATE_PATH` | Absolute path for the witness-protocol STH cache file (see [Witness protocol](#witness-protocol-sth)). Optional. | per-(server + key) file under the OS temp dir |
75
+ | `LOOPCTL_JOURNAL_DIR` | Directory of the holder's offline journal (US-52.62): notes and checkpoints written while loopctl did not answer, one file per session named sha256(server URL + `:` + session id), mode 0600 in a 0700 directory, replayed through `holder_replay` when loopctl answers. Every append and settle holds the file's `<file>.lock` (0600, never through a symlink; broken when its pid is gone or it is over 30 s old), so two MCP processes of one session neither lose nor repeat each other's entries; a write that cannot take it within 2 s is answered an error naming the journal busy, never queued. Not under the OS temp dir, so a reboot does not drop what is owed. Wrong (unwritable): a note or checkpoint that gets no answer is reported as an error instead of queued, as before this journal existed. | `~/.loopctl/journal` |
75
76
 
76
77
  Key resolution priority: `LOOPCTL_API_KEY` > tool-specific key > `LOOPCTL_ORCH_KEY`.
77
78
 
@@ -572,9 +573,10 @@ Key distribution for the dispatch pattern (Epic 26): per-dispatch ephemeral keys
572
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`. |
573
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. |
574
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. |
575
- | `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`. |
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
+ | `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). |
576
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. |
577
- | `work_item_checkpoint` | **Checkpoint a work item** (`POST /api/v1/stories/:id/checkpoints`, US-52.41): computes from `worktree` the branch, the commit its work applies to (the pushed head, else the merge-base with origin's default branch) and `git diff --binary` on top of it with untracked files, without writing to the worktree, and records them with one progress note from `done` and `next` and a `checkpointed` event. Sends this session's own key (its holder credential): only the current holder at the story's `claim_epoch` (read from the story when omitted) with a live lease. `409 not_holder` (names the holder), `409 stale_claim_epoch`, `409 claim_lease_expired`, `409 checkpoint_id_conflict`, `403 holder_credential_required`, `404` for another tenant's story; `413 diff_over_bound` over 4 MiB (push a `wip/...` branch and pass `wip_branch` instead); `422 secret_in_diff` (names the files), `422 diff_and_wip_branch`, `422 invalid_wip_branch`. A repeated `checkpoint_id` with the same content returns the stored checkpoint (`replayed: true`). A checkpoint from a claim that has ended (the epoch you held, after the item moved on) is stored fenced and answered `202` (`fenced: true`, `current_holder_id`), with no note and no change to the item, for the current holder to resolve (US-52.42). Past 5 unresolved fenced checkpoints from you on one item, or 10 on the item from all late holders, a late checkpoint is `409 fenced_checkpoint_limit` (`limit_scope`, `max_unresolved_fenced`) and nothing is stored: push a `wip/...` branch instead. |
579
+ | `work_item_checkpoint` | **Checkpoint a work item** (`POST /api/v1/stories/:id/checkpoints`, US-52.41): computes from `worktree` the branch, the commit its work applies to (the pushed head, else the merge-base with origin's default branch) and `git diff --binary` on top of it with untracked files, without writing to the worktree, and records them with one progress note from `done` and `next` and a `checkpointed` event. Sends this session's own key (its holder credential): only the current holder at the story's `claim_epoch` (read from the story when omitted) with a live lease. `409 not_holder` (names the holder), `409 stale_claim_epoch`, `409 claim_lease_expired`, `409 checkpoint_id_conflict`, `403 holder_credential_required`, `404` for another tenant's story; `413 diff_over_bound` over 4 MiB (push a `wip/...` branch and pass `wip_branch` instead); `422 secret_in_diff` (names the files), `422 diff_and_wip_branch`, `422 invalid_wip_branch`. A repeated `checkpoint_id` with the same content returns the stored checkpoint (`replayed: true`). A checkpoint from a claim that has ended (the epoch you held, after the item moved on) is stored fenced and answered `202` (`fenced: true`, `current_holder_id`), with no note and no change to the item, for the current holder to resolve (US-52.42). Past 5 unresolved fenced checkpoints from you on one item, or 10 on the item from all late holders, a late checkpoint is `409 fenced_checkpoint_limit` (`limit_scope`, `max_unresolved_fenced`) and nothing is stored: push a `wip/...` branch instead. The checkpoint id is a client UUIDv7 unless given (US-52.62); one that gets no answer from loopctl is journaled under the epoch the session last saw and answered `{queued: true, event_id}`, unless it is too large for one replay body (about 1.5 MB encoded): then push a `wip/...` branch. |
578
580
  | `work_item_checkpoints` | **Read a work item's checkpoints**: the newest 20, newest first, without diffs (`GET /api/v1/stories/:id/checkpoints`), with `fenced: "unresolved"` the fenced ones nobody resolved yet, oldest first, or with `checkpoint_id` one checkpoint with its diff base64 (`GET .../checkpoints/:checkpoint_id`), which `git apply` takes on a checkout of its `head_sha`. Any key of the tenant. `404` for another tenant's story or checkpoint. |
579
581
  | `work_item_checkpoint_resolve` | **Apply or ignore a fenced checkpoint** (`POST /api/v1/stories/:id/checkpoints/:checkpoint_id/resolve`, US-52.42): `resolution` (`applied` or `ignored`) and a `reason`, on this session's own key; only the story's current holder with a live lease. The same resolution again is `200` and writes nothing. `409 not_holder` (names `holder_id`), `409 already_resolved`, `422 not_fenced`, `403 holder_credential_required`, `404` for a checkpoint not on this tenant's story. |
580
582
  | `work_item_move` | **Move a work item** to a host, a holder, the cloud or the loop (`POST /api/v1/stories/:id/move`, US-52.43), on this session's own key; the server picks the path from who calls. The holder (live lease) names its own `checkpoint_id` at the current epoch and the claim is released at once over the uncounted `:moved` edge: `200 released`. Anyone else REQUESTS it: the holder is told on the item's thread and has `MOVE_RELEASE_SECONDS` to answer with the same `move_id`, after which the deadline worker releases it: `202 requested`. An unheld item is released at once: `200`. While reserved only the target claims it (`409 reserved_for_move`); a move to a host, holder or the cloud unpulled after `MOVE_PULL_SECONDS` expires to the loop, and a move to the loop never expires: implement@1 places it with the move's checkpoint as `resume`, on a runner of contract 1.40.0 or later (US-52.46). An item an interactive session released is reserved for any interactive session until Mark moves it. A move to a host whose runner joined on contract 1.40.0 or later is placed there and resumes from the move's checkpoint (US-52.44); a runner session holding the item is asked over its runner's socket. The same `move_id` and target answers the first result. `400 move_id_required`/`reason_required`/`invalid_reason`, `404` (incl. `unknown_story_stage`), `409 holder_ended`/`item_closed`/`item_escalated`/`move_pending`/`item_changed`, `422 invalid_target`/`unknown_host`/`unknown_holder`/`holder_cannot_pull` (a runner_session holder claims nothing after its own placement: move to its host)/`target_unavailable`/`already_held_by_target`/`checkpoint_not_current`, `403 boundary_move_needs_mark` when the item's holder (or, unheld, its last mover or claimer) or the target holder is an interactive session and the caller is not Mark's own user key (fleet_dash; US-52.45), except the holder answering a move Mark requested with his `move_id`, his target and its own `checkpoint_id`; a key with no holder omits `checkpoint_id`; and `403` without the human anchor. |
@@ -594,7 +596,7 @@ Key distribution for the dispatch pattern (Epic 26): per-dispatch ephemeral keys
594
596
  | `work_item_cancel` | **Cancel a work item** (`POST /api/v1/stories/:id/cancel`, US-52.32): to `failed` over `:cancelled` from detected, triaged, queued, escalated or in flight. The linked issue is left open. `409 already_landed` (merged, deployed, verified), `409 already_finished` (done, failed). |
595
597
  | `work_item_close` | **Close a work item as not actionable** (`POST /api/v1/stories/:id/close`, US-52.32): as `work_item_cancel` over `:closed`; the only verb that closes the linked issue, as not actionable. Each of the four verbs sends this session's own key: `409 self_intervention_blocked` when its holder holds the item, `409 holder_required` for a non-human key with no holder, `409 stage_moved` when the item moved while the verb ran (nothing changed), `409 already_landed` for an escalated item whose change already landed (every verb but a reviewed `review_missing` requeue), `409 independent_verification` for a held chg landing on an independent path, `403` on an agent-rooted tenant, `400 reason_required` without a reason. A repeated `intervention_id` (generated when absent) writes nothing and returns the current stage row. |
596
598
  | `work_item_open` | **Open the work item for a branch** (`POST /api/v1/work_items`, US-52.18): `repo_url` and `branch`, optional `title` (default: the branch) and `epic_id` (default: the target epic of the project's live intake source). Creates one story already implementing and held by this session, with a stage row naming the branch; the MCP server also does it on each heartbeat for the worktree's non-default branch, once per branch per holder. Reopening your own item, or an unheld one, returns it (200). Needs this session's holder credential: `403 holder_credential_required` otherwise. `409 branch_held` (another session's open item has the branch), `409 holder_ended`, `409 holder_lease_expired`, `409 story_held`, `404 project_not_found`, `404 epic_not_found`, `422 no_target_epic` (pass `epic_id`), `422 invalid_branch`. |
597
- | `inbox` | **Read this session's inbox** (`GET /api/v1/inbox`, US-52.24): `dms`, `threads` (each held story with unread messages; a story taken over arrives from its first message) and, with `project_id`, `channel`, each above the session's stored cursor, with `last_seq` per section and `has_more`. `limit` defaults to 50, at most 200, DMs first. The cursor moves only on ack, so an unacked message is returned again: `ack` (a list of `{kind, id, seq}`, kind `dm`/`story`/`channel`, seq a `last_seq` a read returned) is posted first (`POST /api/v1/inbox/ack`), then the inbox is read, and the answer carries `acked`. A refused batch moves no cursor: `422 ack_beyond_end`, `422 not_in_inbox`, `422 invalid_ack`. Needs this session's holder credential: `403 holder_credential_required` otherwise. |
599
+ | `inbox` | **Read this session's inbox** (`GET /api/v1/inbox`, US-52.24): `dms`, `threads` (each held story with unread messages; a story taken over arrives from its first message) and, with `project_id`, `channel`, each above the session's stored cursor, with `last_seq` per section and `has_more`. `limit` defaults to 50, at most 200, DMs first. The cursor moves only on ack, so an unacked message is returned again: `ack` (a list of `{kind, id, seq}`, kind `dm`/`story`/`channel`, seq a `last_seq` a read returned) is posted first (`POST /api/v1/inbox/ack`), then the inbox is read, and the answer carries `acked`. A refused batch moves no cursor: `422 ack_beyond_end`, `422 not_in_inbox`, `422 invalid_ack`. Needs this session's holder credential: `403 holder_credential_required` otherwise. The answer carries `journal` (US-52.62, read locally, present even when loopctl does not answer): `{pending, oldest_recorded_at, last_fenced}`, what this session still owes loopctl from an outage and the entries of its last replay that came back fenced. |
598
600
  | `revoke_dispatch` | **Revoke a dispatch AND ITS WHOLE SUBTREE** (`POST /api/v1/dispatches/:id/revoke`), plus the ephemeral api_key each one minted — the revoke matches the dispatch OR any row carrying it in `lineage_path`, so name a LEAF unless you mean the subtree. Reach for it when a dead session's key is blocking new work: an un-revoked key OCCUPIES its agent's slot in the partial unique index `api_keys_one_role_per_agent_idx` (`(tenant_id, agent_id, role)` WHERE `revoked_at IS NULL`), which cannot also test `expires_at` — a partial-index predicate must be IMMUTABLE and `now()` is STABLE — so even an EXPIRED key holds it and the next mint answers `422 agent already has an active key with this role`. Waiting works too, slowly: the expired-dispatch sweep runs every minute and the expired-api-key sweep every five, so the slot clears at the TTL (four hours for a placement session dispatch). For a PARKED STORY prefer `force_unclaim_story`, which revokes that story's own session dispatch and frees the stage as well. It does NOT clear `implementer_dispatch_id`: that is custody provenance, and a revoked dispatch still resolves, so verify/report/review-complete compare the same lineage afterwards. `role: :orchestrator` WITH the hierarchy (orchestrator, user or superadmin all pass; an agent key is `403 insufficient_role`), so no env var is pinned — `LOOPCTL_USER_KEY` is merely PREFERRED, for the ceiling reason next. `403 dispatch_outside_caller_lineage` when the target is not in your lineage — a dispatch may only be revoked by a caller it descends from, because the revoke cascades; the body carries `remediation.your_dispatch_id`, and the tenant's `user`-role operator key may revoke anywhere in its tenant. `403 unlineaged_revoke_forbidden` when your key was minted by no dispatch and is below `user` role — a legacy `LOOPCTL_ORCH_KEY` is exactly that, and with no lineage there is no subtree that would bound a cascading revoke, so it could otherwise revoke the tenant's root; use the operator key, or `force_unclaim_story` for a parked story, or mint a dispatch under an active parent and revoke from inside that lineage. `403 custody_tier_required` on an agent-rooted tenant, `503 tenant_halted` under a custody halt, 404 for an unknown dispatch or another tenant's. Idempotent: an already-revoked dispatch answers 200 with `revoked_count: 0` and its ORIGINAL `revoked_at`. Required: `dispatch_id` (refused locally if it is not a UUID). |
599
601
  | `register_custody_owner_key` | **LCP-1 §9.2.** Register/rotate the tenant custody OWNER key — the root of trust the attestation chain hangs from. Private half stays with you; requires `LOOPCTL_USER_KEY` and a human-anchored tenant. Required: `owner_pubkey` (hex). ROTATION additionally requires `rotation_proof` (from `custody_sign_owner_rotation`); first registration needs none. |
600
602
  | `list_enrolled_agent_keys` | **LCP-1 §9.1.1 transparency.** List the agent public keys enrolled under your tenant, reconstructed from the tamper-evident audit chain (not a mutable listing). Compare against the keys you generated; any excess is operator-minted. Keyset-paged (`limit`, `cursor`). |
package/index.js CHANGED
@@ -24,6 +24,14 @@ 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
26
  import { createHolderSession } from "./lib/holder.js";
27
+ import { replayHolder } from "./lib/holder-replay.js";
28
+ import {
29
+ createHolderJournal,
30
+ GATEWAY_STATUSES,
31
+ journalDir,
32
+ withJournal,
33
+ withUnreachableNotice,
34
+ } from "./lib/holder-journal.js";
27
35
  import { machineName } from "./lib/machine-name.js";
28
36
  import { resolveDefaultKey } from "./lib/default-key.js";
29
37
  import { listWorkItemNotes, readWorkItemTimeline, writeWorkItemNote } from "./lib/work-items.js";
@@ -287,6 +295,25 @@ function agentKey() {
287
295
  return holderSession.agentKey();
288
296
  }
289
297
 
298
+ // The holder id a replay goes to: the session's CURRENT holder, and only while this process
299
+ // holds its credential. LOOPCTL_AGENT_KEY names no holder, and an ended holder's id is refused
300
+ // 403 holder_mismatch, so neither is ever replayed under.
301
+ function liveHolderId() {
302
+ const status = holderSession.status();
303
+ return status.using_holder_credential && status.holder ? status.holder.id : null;
304
+ }
305
+
306
+ // US-52.62: notes and checkpoints written while loopctl does not answer, kept on disk and
307
+ // replayed in order through holder_replay when it answers (lib/holder-journal.js).
308
+ const holderJournal = createHolderJournal({
309
+ dir: journalDir(process.env, () => os.homedir()),
310
+ serverUrl: getBaseUrl(),
311
+ sessionId: holderSession.sessionId,
312
+ holderId: liveHolderId,
313
+ apiCall: (method, path, body) =>
314
+ apiCall(method, path, body, agentKey(), { exactKey: true, timeoutMs: 60_000 }),
315
+ });
316
+
290
317
  // For a lib module that reads `env.LOOPCTL_AGENT_KEY` from an injected env (claim-lease.js,
291
318
  // escalation.js): the process env with the agent key replaced by `agentKey()`.
292
319
  function agentKeyEnv() {
@@ -402,6 +429,10 @@ async function apiCall(
402
429
  return { error: true, status: 0, body: `Network error: ${err.message}${cause}` };
403
430
  }
404
431
 
432
+ // US-52.62: loopctl answered, so whatever the journal still owes is replayed now, behind
433
+ // this call and without holding it up. A gateway error is not loopctl answering.
434
+ if (!GATEWAY_STATUSES.includes(response.status)) holderJournal.onAnswered();
435
+
405
436
  if (response.status === 204) {
406
437
  return { ok: true };
407
438
  }
@@ -447,6 +478,8 @@ async function apiCall(
447
478
  return { error: true, status: response.status, body: errorBody };
448
479
  }
449
480
 
481
+ // A story row in the answer carries the claim epoch a journaled write is recorded at.
482
+ holderJournal.observe(responseBody);
450
483
  return responseBody;
451
484
  }
452
485
 
@@ -1256,7 +1289,8 @@ async function claimStory({ story_id }) {
1256
1289
  );
1257
1290
  // The claim response carries the start_cap that POST /start will require.
1258
1291
  rememberCap(story_id, result && result.capability);
1259
- return withClaimLeaseNotice(result);
1292
+ // US-52.62: a claim is never journaled; its network error says so.
1293
+ return withClaimLeaseNotice(withUnreachableNotice(result));
1260
1294
  }
1261
1295
 
1262
1296
  // #803/#810: a claim carries a lease and an epoch. Put both at the top of the result, when
@@ -1268,13 +1302,17 @@ function withClaimLeaseNotice(result) {
1268
1302
  }
1269
1303
 
1270
1304
  async function renewStoryClaim(args) {
1271
- return withClaimLeaseNotice(await renewStoryClaimRequest(args, { apiCall, env: agentKeyEnv() }));
1305
+ return withClaimLeaseNotice(
1306
+ withUnreachableNotice(await renewStoryClaimRequest(args, { apiCall, env: agentKeyEnv() })),
1307
+ );
1272
1308
  }
1273
1309
 
1274
1310
  // #803: escalation leads with a STOP line. A session that escalates and keeps working is
1275
1311
  // the failure the affordance exists to prevent, and the JSON body alone does not say so.
1276
1312
  async function escalateStory(args) {
1277
- const result = await escalateStoryRequest(args, { apiCall, env: agentKeyEnv() });
1313
+ const result = withUnreachableNotice(
1314
+ await escalateStoryRequest(args, { apiCall, env: agentKeyEnv() }),
1315
+ );
1278
1316
  const notice = escalationNotice(result);
1279
1317
  if (!notice) return toContent(result);
1280
1318
  return { content: [{ type: "text", text: notice }, ...toContent(result).content] };
@@ -1296,7 +1334,7 @@ async function startStory({ story_id, capability }) {
1296
1334
  cap ? { capability: cap } : null,
1297
1335
  agentKey()
1298
1336
  );
1299
- return toContent(result);
1337
+ return toContent(withUnreachableNotice(result));
1300
1338
  }
1301
1339
 
1302
1340
  async function requestReview({ story_id }) {
@@ -1329,7 +1367,7 @@ async function reportStory({ story_id, artifact_type, artifact_path, token_usage
1329
1367
  Object.keys(body).length > 0 ? body : null,
1330
1368
  process.env.LOOPCTL_ORCH_KEY
1331
1369
  );
1332
- return toContent(result);
1370
+ return toContent(withUnreachableNotice(result));
1333
1371
  }
1334
1372
 
1335
1373
  async function reviewComplete({ story_id, review_type, findings_count, fixes_count, disproved_count, summary, commit_sha, claim }) {
@@ -1377,7 +1415,7 @@ async function verifyStory({ story_id, summary, review_type, claim }) {
1377
1415
  orch.override,
1378
1416
  orch.options,
1379
1417
  );
1380
- return toContent(result);
1418
+ return toContent(withUnreachableNotice(result));
1381
1419
  }
1382
1420
 
1383
1421
  async function rejectStory({ story_id, reason }) {
@@ -3091,6 +3129,21 @@ async function holderEndTool() {
3091
3129
  return toContent(result && result.error ? result : holderSession.status());
3092
3130
  }
3093
3131
 
3132
+ // US-52.61: the offline journal, on the holder's own credential and to its own id. Only a live
3133
+ // holder credential is sent: LOOPCTL_AGENT_KEY names no holder, so loopctl would answer 403.
3134
+ async function holderReplayTool(args) {
3135
+ const status = holderSession.status();
3136
+ const holderId = status.using_holder_credential && status.holder ? status.holder.id : null;
3137
+
3138
+ return toContent(
3139
+ await replayHolder(args, {
3140
+ holderId,
3141
+ apiCall: (method, path, body) =>
3142
+ apiCall(method, path, body, agentKey(), { exactKey: true, timeoutMs: 60_000 }),
3143
+ }),
3144
+ );
3145
+ }
3146
+
3094
3147
  // US-52.23: one message to a thread, a DM or a channel, on the session's own key, so the
3095
3148
  // server stamps the author's holder from it (lib/messages.js).
3096
3149
  async function messageSendTool(args) {
@@ -3104,10 +3157,12 @@ async function messageSendTool(args) {
3104
3157
 
3105
3158
  // US-52.17: a work item's notes, on the session's own key: the write is accepted from the
3106
3159
  // story's CURRENT holder, so it travels on the credential that holds it (lib/work-items.js).
3160
+ // US-52.62: a note that gets no answer is journaled and replayed (lib/holder-journal.js).
3107
3161
  async function workItemNoteTool(args) {
3108
3162
  return toContent(
3109
3163
  await writeWorkItemNote(args, {
3110
3164
  apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3165
+ journal: holderJournal,
3111
3166
  }),
3112
3167
  );
3113
3168
  }
@@ -3143,11 +3198,13 @@ async function workItemNotesTool(args) {
3143
3198
 
3144
3199
  // US-52.41: a checkpoint, on the session's own key: the write is accepted from the story's
3145
3200
  // CURRENT holder only, so it travels on the credential that holds it (lib/checkpoints.js).
3201
+ // US-52.62: one that gets no answer is journaled and replayed (lib/holder-journal.js).
3146
3202
  async function workItemCheckpointTool(args) {
3147
3203
  return toContent(
3148
3204
  await recordCheckpoint(args, {
3149
3205
  apiCall: (method, path, body, opts) => apiCall(method, path, body, agentKey(), opts),
3150
3206
  randomUUID: () => crypto.randomUUID(),
3207
+ journal: holderJournal,
3151
3208
  }),
3152
3209
  );
3153
3210
  }
@@ -3173,10 +3230,12 @@ async function workItemCheckpointResolveTool(args) {
3173
3230
  // session's own key.
3174
3231
  async function workItemMoveTool(args) {
3175
3232
  return toContent(
3176
- await moveWorkItem(args, {
3177
- apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3178
- randomUUID: () => crypto.randomUUID(),
3179
- }),
3233
+ withUnreachableNotice(
3234
+ await moveWorkItem(args, {
3235
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3236
+ randomUUID: () => crypto.randomUUID(),
3237
+ }),
3238
+ ),
3180
3239
  );
3181
3240
  }
3182
3241
 
@@ -3286,12 +3345,16 @@ async function snapshotUrlsTool(args) {
3286
3345
  }
3287
3346
 
3288
3347
  // US-52.24: this session's inbox, acks first, on the session's own key: both routes answer
3289
- // only a holder credential (lib/inbox.js).
3348
+ // only a holder credential (lib/inbox.js). US-52.62: the answer carries `journal`, what this
3349
+ // session still owes loopctl from an outage, even when the read itself got no answer.
3290
3350
  async function inboxTool(args) {
3291
3351
  return toContent(
3292
- await readInbox(args, {
3293
- apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3294
- }),
3352
+ withJournal(
3353
+ await readInbox(args, {
3354
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3355
+ }),
3356
+ holderJournal,
3357
+ ),
3295
3358
  );
3296
3359
  }
3297
3360
 
@@ -8623,6 +8686,59 @@ const TOOLS = [
8623
8686
  inputSchema: { type: "object", properties: {} },
8624
8687
  },
8625
8688
 
8689
+ {
8690
+ name: "holder_replay",
8691
+ description:
8692
+ "REPLAY WHAT THIS SESSION RECORDED WHILE LOOPCTL WAS UNREACHABLE (POST " +
8693
+ "/api/v1/holders/:id/replay, US-52.61), on this session's holder credential and to its " +
8694
+ "own holder id (never one you pass). Send the journal's entries in the order you wrote " +
8695
+ "them; each is {event_id (uuid, unique per entry, reused on a resend), seq (integer, " +
8696
+ "strictly ascending), kind (note or checkpoint), story_id, claim_epoch (the epoch you " +
8697
+ "held the story under), recorded_at (ISO 8601), payload}. A note's payload is " +
8698
+ "{section, body} as work_item_note takes it; a checkpoint's is {branch, head_sha, diff " +
8699
+ "(base64) or wip_branch, done, next}. Only notes and checkpoints replay: a claim, a " +
8700
+ "stage move, a report, review or verify needs a live answer and is never replayed. " +
8701
+ "loopctl answers one result per entry in seq order: `applied` (you hold the story at " +
8702
+ "that claim_epoch and it went through the verb's own checks), `replayed` (this event_id " +
8703
+ "was already applied with this payload; the first result, nothing written), `fenced` " +
8704
+ "(your session held the story at that epoch and no longer does: a note is kept as a " +
8705
+ "fenced_replay event, a checkpoint stored fenced for the current holder; the story does " +
8706
+ "not move) or `refused` with error.code (invalid_entry, not_found, event_id_conflict, " +
8707
+ "not_holder when your session never held the story, stale_claim_epoch, busy, " +
8708
+ "fenced_note_limit (the item already keeps 50 fenced notes from you or 200 from all " +
8709
+ "late holders; nothing written), or a checkpoint refusal such as " +
8710
+ "fenced_checkpoint_limit); one refused entry never stops the rest, and a refused entry is " +
8711
+ "safe to resend. A holder that lapsed during the outage is replayed by the session's " +
8712
+ "next holder: its entries come back fenced. Refused whole, nothing applied: 403 " +
8713
+ "holder_mismatch (the key's holder is not this id), 409 holder_ended, 422 " +
8714
+ "replay_not_ordered (a seq missing, repeated or out of order), 422 replay_too_large " +
8715
+ "(over 200 entries: split the journal). Refused locally when this session holds no " +
8716
+ "live holder credential (call holder_register).",
8717
+ inputSchema: {
8718
+ type: "object",
8719
+ properties: {
8720
+ entries: {
8721
+ type: "array",
8722
+ description: "The journal entries, in strictly ascending seq.",
8723
+ items: {
8724
+ type: "object",
8725
+ properties: {
8726
+ event_id: { type: "string" },
8727
+ seq: { type: "integer" },
8728
+ kind: { type: "string", enum: ["note", "checkpoint"] },
8729
+ story_id: { type: "string" },
8730
+ claim_epoch: { type: "integer" },
8731
+ recorded_at: { type: "string" },
8732
+ payload: { type: "object" },
8733
+ },
8734
+ required: ["event_id", "seq", "kind", "story_id", "claim_epoch", "recorded_at", "payload"],
8735
+ },
8736
+ },
8737
+ },
8738
+ required: ["entries"],
8739
+ },
8740
+ },
8741
+
8626
8742
  {
8627
8743
  name: "work_item_note",
8628
8744
  description:
@@ -8637,7 +8753,14 @@ const TOOLS = [
8637
8753
  "body, a body over 16384 bytes, or a body that looks like a credential (every holder " +
8638
8754
  "reads notes). Pass `idempotency_key` to make a retry after a lost response return the " +
8639
8755
  "first note and write nothing; the key is the WRITER's, so a key another writer's note " +
8640
- "on this story already carries is 409 idempotency_key_reused and writes nothing.",
8756
+ "on this story already carries is 409 idempotency_key_reused and writes nothing. " +
8757
+ "OUTAGE (US-52.62): every note carries a client event_id; when loopctl does not answer " +
8758
+ "(network error, timeout, 502/503/504) the note is journaled locally and the call " +
8759
+ "answers {queued: true, event_id} instead of an error: keep working, it is sent in the " +
8760
+ "order written when loopctl answers, and the inbox tool's `journal` block shows what is " +
8761
+ "still owed. While the journal holds entries, a new note queues behind them. Journaling " +
8762
+ "needs the claim_epoch the note is written under: pass `claim_epoch`, or the tool uses " +
8763
+ "the one this session last saw for the story.",
8641
8764
  inputSchema: {
8642
8765
  type: "object",
8643
8766
  properties: {
@@ -8652,6 +8775,12 @@ const TOOLS = [
8652
8775
  type: "string",
8653
8776
  description: "Optional: a key unique to this note, so a retry writes it once.",
8654
8777
  },
8778
+ claim_epoch: {
8779
+ type: "integer",
8780
+ description:
8781
+ "Optional: the claim_epoch your claim returned, recorded with the note if loopctl " +
8782
+ "does not answer and it is journaled.",
8783
+ },
8655
8784
  },
8656
8785
  required: ["story_id", "section", "body"],
8657
8786
  },
@@ -8805,7 +8934,12 @@ const TOOLS = [
8805
8934
  "checkpoints are bounded: past 5 from you on one item, or 10 on the item from all late " +
8806
8935
  "holders, a late checkpoint is refused 409 fenced_checkpoint_limit (limit_scope holder " +
8807
8936
  "or item, max_unresolved_fenced) and nothing is stored; push the work to a wip/... " +
8808
- "branch instead, and stop checkpointing an item you no longer hold.",
8937
+ "branch instead, and stop checkpointing an item you no longer hold. OUTAGE (US-52.62): " +
8938
+ "the checkpoint id is a client UUIDv7 unless you pass one; when loopctl does not answer " +
8939
+ "(network error, timeout, 502/503/504) the checkpoint is journaled locally under the " +
8940
+ "epoch this session last saw and answered {queued: true, event_id}: keep working, it is " +
8941
+ "sent in order when loopctl answers. A checkpoint too large for one replay body (about " +
8942
+ "1.5 MB encoded) is not journaled: push a wip/... branch and pass wip_branch.",
8809
8943
  inputSchema: {
8810
8944
  type: "object",
8811
8945
  properties: {
@@ -9300,7 +9434,12 @@ const TOOLS = [
9300
9434
  "422 ack_beyond_end (seq above that attachment's last message), 422 not_in_inbox " +
9301
9435
  "(another holder's DMs, a story you do not hold, a channel not of your tenant), 422 " +
9302
9436
  "invalid_ack. Needs this session's holder credential: 403 " +
9303
- "holder_credential_required for any other key, whatever its role.",
9437
+ "holder_credential_required for any other key, whatever its role. The answer also " +
9438
+ "carries `journal` (US-52.62, read locally, present even when loopctl does not " +
9439
+ "answer): {pending (notes and checkpoints written while loopctl was unreachable and " +
9440
+ "not yet replayed), oldest_recorded_at, last_fenced ({at, entries: [{event_id, seq, " +
9441
+ "kind, story_id}]} of the last replay that came back fenced: written under a claim that " +
9442
+ "had ended, kept on the item as history and applied to nothing; null when none)}.",
9304
9443
  inputSchema: {
9305
9444
  type: "object",
9306
9445
  properties: {
@@ -12007,6 +12146,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
12007
12146
  case "holder_end":
12008
12147
  return await holderEndTool();
12009
12148
 
12149
+ case "holder_replay":
12150
+ return await holderReplayTool(args);
12151
+
12010
12152
  case "work_item_note":
12011
12153
  return await workItemNoteTool(args);
12012
12154
 
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { uuid } from "./delivery-loop.js";
17
+ import { unreachable, withUnreachableNotice } from "./holder-journal.js";
17
18
  import { headCommit, worktreeDiff } from "./worktree-diff.js";
18
19
 
19
20
  // A checkpoint body can be several megabytes; give the upload more than the default.
@@ -34,10 +35,17 @@ async function currentEpoch(storyId, apiCall) {
34
35
  return Number.isInteger(epoch) ? { epoch } : { error: refuse("The story carries no claim_epoch.") };
35
36
  }
36
37
 
37
- /** `POST /api/v1/stories/:id/checkpoints`, with the diff computed from `worktree`. */
38
+ /**
39
+ * `POST /api/v1/stories/:id/checkpoints`, with the diff computed from `worktree`.
40
+ *
41
+ * With `journal` (lib/holder-journal.js, US-52.62) the checkpoint's id is a client UUIDv7, the
42
+ * `event_id` its journaled copy keeps, and a checkpoint that gets no answer from loopctl is
43
+ * journaled and answered `{queued: true, event_id}`. When the story's epoch cannot be read
44
+ * because loopctl does not answer, the one this session last saw for it is used.
45
+ */
38
46
  export async function recordCheckpoint(
39
47
  { story_id, worktree, done, next, wip_branch, claim_epoch, checkpoint_id } = {},
40
- { apiCall, randomUUID, diffOf = worktreeDiff, headOf = headCommit } = {},
48
+ { apiCall, randomUUID, diffOf = worktreeDiff, headOf = headCommit, journal = null } = {},
41
49
  ) {
42
50
  const bad = uuid(story_id, "story_id");
43
51
  if (bad) return bad;
@@ -69,27 +77,42 @@ export async function recordCheckpoint(
69
77
  let epoch = claim_epoch;
70
78
  if (!Number.isInteger(epoch)) {
71
79
  const read = await currentEpoch(story_id, apiCall);
72
- if (read.error) return read.error;
73
- epoch = read.epoch;
80
+ if (read.error) {
81
+ const seen = journal && journal.active() && unreachable(read.error) ? journal.epochOf(story_id) : null;
82
+ if (!Number.isInteger(seen)) return journal ? withUnreachableNotice(read.error) : read.error;
83
+ epoch = seen;
84
+ } else {
85
+ epoch = read.epoch;
86
+ if (journal) journal.rememberEpoch(story_id, epoch);
87
+ }
74
88
  }
75
89
 
76
- const payload = {
77
- id: checkpoint_id || randomUUID(),
78
- claim_epoch: epoch,
79
- branch: state.branch,
80
- head_sha: state.head_sha,
81
- done,
82
- };
90
+ const id = checkpoint_id || (journal ? journal.newEventId() : randomUUID());
83
91
 
84
- if (typeof next === "string" && next !== "") payload.next = next;
92
+ // The fields a journaled copy replays (`Loopctl.Holders.Replay`'s checkpoint payload).
93
+ const content = { branch: state.branch, head_sha: state.head_sha, done };
94
+ if (typeof next === "string" && next !== "") content.next = next;
85
95
 
86
96
  if (typeof wip_branch === "string" && wip_branch !== "") {
87
- payload.wip_branch = wip_branch;
97
+ content.wip_branch = wip_branch;
88
98
  } else {
89
- payload.diff = state.diff.toString("base64");
99
+ content.diff = state.diff.toString("base64");
90
100
  }
91
101
 
92
- return apiCall("POST", checkpointsPath(story_id), payload, { timeoutMs: UPLOAD_TIMEOUT_MS });
102
+ const payload = { id, claim_epoch: epoch, ...content };
103
+ const send = () =>
104
+ apiCall("POST", checkpointsPath(story_id), payload, { timeoutMs: UPLOAD_TIMEOUT_MS });
105
+
106
+ if (!journal) return send();
107
+
108
+ return journal.write({
109
+ kind: "checkpoint",
110
+ story_id,
111
+ claim_epoch: epoch,
112
+ event_id: id,
113
+ payload: content,
114
+ send,
115
+ });
93
116
  }
94
117
 
95
118
  /**