loopctl-mcp-server 3.20.3 → 3.21.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/index.js CHANGED
@@ -22,6 +22,10 @@ import { applyArgAliases } from "./lib/arg-aliases.js";
22
22
  import { articleId } from "./lib/article-id.js";
23
23
  import { clientContextHeader } from "./lib/client-context.js";
24
24
  import { resolveClaimSessionId } from "./lib/claim-session.js";
25
+ import { createBranchItemOpener, openWorkItem } from "./lib/branch-item.js";
26
+ import { createHolderSession } from "./lib/holder.js";
27
+ import { listWorkItemNotes, writeWorkItemNote } from "./lib/work-items.js";
28
+ import { execFile, execFileSync } from "node:child_process";
25
29
  import { degradedSearchNotice } from "./lib/search-notices.js";
26
30
  import {
27
31
  projectsPath,
@@ -196,6 +200,67 @@ function resolveKey(keyOverride) {
196
200
  );
197
201
  }
198
202
 
203
+ // US-52.13: this process's session holder. Every request that used to send
204
+ // LOOPCTL_AGENT_KEY sends `agentKey()` instead: the holder's own credential once the
205
+ // startup register succeeds, else LOOPCTL_AGENT_KEY unchanged (lib/holder.js says why a
206
+ // failed register never stops a session working).
207
+ function sessionWorktree() {
208
+ try {
209
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
210
+ cwd: process.cwd(),
211
+ encoding: "utf8",
212
+ stdio: ["ignore", "pipe", "ignore"],
213
+ timeout: 2000,
214
+ }).trim();
215
+ } catch {
216
+ return process.cwd();
217
+ }
218
+ }
219
+
220
+ // US-52.18: on each heartbeat, the worktree's branch becomes a work item this holder holds.
221
+ const branchItemOpener = createBranchItemOpener({
222
+ apiCall: (...args) => apiCall(...args),
223
+ worktree: sessionWorktree,
224
+ git: (args) =>
225
+ new Promise((resolve) => {
226
+ execFile("git", args, { encoding: "utf8", timeout: 2000 }, (err, stdout) =>
227
+ resolve(err ? null : String(stdout).trim()),
228
+ );
229
+ }),
230
+ });
231
+
232
+ const holderSession = createHolderSession({
233
+ apiCall: (...args) => apiCall(...args),
234
+ env: process.env,
235
+ hostname: () => os.hostname(),
236
+ worktree: sessionWorktree,
237
+ randomUUID: () => crypto.randomUUID(),
238
+ afterBeat: (holder, credential) => branchItemOpener.tick(holder, credential),
239
+ });
240
+
241
+ function agentKey() {
242
+ return holderSession.agentKey();
243
+ }
244
+
245
+ // For a lib module that reads `env.LOOPCTL_AGENT_KEY` from an injected env (claim-lease.js,
246
+ // escalation.js): the process env with the agent key replaced by `agentKey()`.
247
+ function agentKeyEnv() {
248
+ return { ...process.env, LOOPCTL_AGENT_KEY: agentKey() };
249
+ }
250
+
251
+ // US-52.14: the refusal a session gets on an item another session holds, even one with the
252
+ // same agent key. Shared by the story and channel claimant tools' descriptions.
253
+ const HELD_BY_OTHER_HOLDER =
254
+ "Refused 409 held_by_other_holder when another session holds the story, even one with " +
255
+ "your agent key: the error names that session's holder_id, holder_kind and holder_host. " +
256
+ "Only that session can start, renew, request review on or release it; work something " +
257
+ "else.";
258
+
259
+ const CHANNEL_HELD_BY_OTHER_SESSION =
260
+ "A ref another session holds, even one with your agent key, is refused 409 " +
261
+ "already_claimed on claim and 404 on done and release, whatever session id is sent: the " +
262
+ "claim is bound to the session's holder from its verified key (US-52.14).";
263
+
199
264
  let clientContextHeaderCache;
200
265
  function cachedClientContextHeader() {
201
266
  if (clientContextHeaderCache === undefined) {
@@ -539,7 +604,7 @@ async function resolveProjectRaw({ slug, repo_url, name } = {}) {
539
604
  "GET",
540
605
  `/api/v1/projects/resolve?${params}`,
541
606
  null,
542
- process.env.LOOPCTL_AGENT_KEY,
607
+ agentKey(),
543
608
  );
544
609
  }
545
610
 
@@ -564,7 +629,7 @@ async function createKbScopeRaw({ name, slug, repo_url, description, tech_stack
564
629
  if (tech_stack) body.tech_stack = tech_stack;
565
630
  // Uses the AGENT key (not ORCH): a KB scope is agent-createable on the KB tier — that is
566
631
  // the whole point. The server forces kind: :kb; a body-supplied kind is ignored.
567
- return await apiCall("POST", "/api/v1/kb-scopes", body, process.env.LOOPCTL_AGENT_KEY);
632
+ return await apiCall("POST", "/api/v1/kb-scopes", body, agentKey());
568
633
  }
569
634
 
570
635
  async function createKbScope(args) {
@@ -578,7 +643,7 @@ async function archiveKbScope({ project_id }) {
578
643
  "DELETE",
579
644
  `/api/v1/kb-scopes/${project_id}`,
580
645
  null,
581
- process.env.LOOPCTL_AGENT_KEY,
646
+ agentKey(),
582
647
  );
583
648
  return toContent(result);
584
649
  }
@@ -590,7 +655,7 @@ async function restoreKbScope({ project_id }) {
590
655
  "POST",
591
656
  `/api/v1/kb-scopes/${project_id}/restore`,
592
657
  {},
593
- process.env.LOOPCTL_AGENT_KEY,
658
+ agentKey(),
594
659
  );
595
660
  return toContent(result);
596
661
  }
@@ -684,7 +749,7 @@ async function channelPostRaw({
684
749
  "POST",
685
750
  "/api/v1/channel/posts",
686
751
  payload,
687
- process.env.LOOPCTL_AGENT_KEY,
752
+ agentKey(),
688
753
  );
689
754
  }
690
755
 
@@ -723,7 +788,7 @@ async function channelRecent({ project_id, since, limit }) {
723
788
  "GET",
724
789
  `/api/v1/channel/posts?${params}`,
725
790
  null,
726
- process.env.LOOPCTL_AGENT_KEY,
791
+ agentKey(),
727
792
  );
728
793
  return toContent(result);
729
794
  }
@@ -759,7 +824,7 @@ async function channelHandoffs({ project_id, host, capabilities, only_mine }) {
759
824
  "GET",
760
825
  `/api/v1/channel/handoffs?${params}`,
761
826
  null,
762
- process.env.LOOPCTL_AGENT_KEY,
827
+ agentKey(),
763
828
  );
764
829
  return toContent(result);
765
830
  }
@@ -774,7 +839,7 @@ async function channelGet({ post_id }) {
774
839
  "GET",
775
840
  `/api/v1/channel/posts/${post_id}`,
776
841
  null,
777
- process.env.LOOPCTL_AGENT_KEY,
842
+ agentKey(),
778
843
  );
779
844
  return toContent(result);
780
845
  }
@@ -799,7 +864,7 @@ async function channelClaim({ project_id, ref, lease_seconds }) {
799
864
  "POST",
800
865
  "/api/v1/channel/claims",
801
866
  payload,
802
- process.env.LOOPCTL_AGENT_KEY,
867
+ agentKey(),
803
868
  );
804
869
  return toContent(result);
805
870
  }
@@ -825,7 +890,7 @@ async function channelClaims({ project_id, ref, limit }) {
825
890
  "GET",
826
891
  `/api/v1/channel/claims?${params}`,
827
892
  null,
828
- process.env.LOOPCTL_AGENT_KEY,
893
+ agentKey(),
829
894
  );
830
895
  return toContent(result);
831
896
  }
@@ -849,7 +914,7 @@ async function channelRelease({ project_id, ref, force }) {
849
914
  "POST",
850
915
  "/api/v1/channel/claims/release",
851
916
  payload,
852
- process.env.LOOPCTL_AGENT_KEY,
917
+ agentKey(),
853
918
  );
854
919
  return toContent(result);
855
920
  }
@@ -867,7 +932,7 @@ async function channelDone({ project_id, ref, force }) {
867
932
  "POST",
868
933
  "/api/v1/channel/claims/done",
869
934
  payload,
870
- process.env.LOOPCTL_AGENT_KEY,
935
+ agentKey(),
871
936
  );
872
937
  return toContent(result);
873
938
  }
@@ -895,7 +960,7 @@ async function channelLock({ project_id, target, ttl_seconds, note }) {
895
960
  "POST",
896
961
  "/api/v1/channel/locks",
897
962
  payload,
898
- process.env.LOOPCTL_AGENT_KEY,
963
+ agentKey(),
899
964
  );
900
965
  return toContent(result);
901
966
  }
@@ -914,7 +979,7 @@ async function channelUnlock({ project_id, target }) {
914
979
  "POST",
915
980
  "/api/v1/channel/locks/release",
916
981
  payload,
917
- process.env.LOOPCTL_AGENT_KEY,
982
+ agentKey(),
918
983
  );
919
984
  return toContent(result);
920
985
  }
@@ -931,7 +996,7 @@ async function channelLocks({ project_id, limit }) {
931
996
  "GET",
932
997
  `/api/v1/channel/locks?${params}`,
933
998
  null,
934
- process.env.LOOPCTL_AGENT_KEY,
999
+ agentKey(),
935
1000
  );
936
1001
  return toContent(result);
937
1002
  }
@@ -947,7 +1012,7 @@ async function channelDelete({ post_id }) {
947
1012
  "DELETE",
948
1013
  `/api/v1/channel/posts/${post_id}`,
949
1014
  null,
950
- process.env.LOOPCTL_AGENT_KEY,
1015
+ agentKey(),
951
1016
  );
952
1017
  return toContent(result);
953
1018
  }
@@ -967,7 +1032,7 @@ async function channelGraduate({ post_id, title, tags, category }) {
967
1032
  "POST",
968
1033
  `/api/v1/channel/posts/${post_id}/graduate`,
969
1034
  payload,
970
- process.env.LOOPCTL_AGENT_KEY,
1035
+ agentKey(),
971
1036
  );
972
1037
  return toContent(result);
973
1038
  }
@@ -1236,7 +1301,7 @@ async function contractStory({ story_id, story_title, ac_count }) {
1236
1301
  "POST",
1237
1302
  `/api/v1/stories/${story_id}/contract`,
1238
1303
  { story_title, ac_count },
1239
- process.env.LOOPCTL_AGENT_KEY
1304
+ agentKey()
1240
1305
  );
1241
1306
  return toContent(result);
1242
1307
  }
@@ -1330,7 +1395,7 @@ async function recoverStartCap(storyId) {
1330
1395
  "POST",
1331
1396
  `/api/v1/stories/${storyId}/recover-cap`,
1332
1397
  null,
1333
- process.env.LOOPCTL_AGENT_KEY
1398
+ agentKey()
1334
1399
  );
1335
1400
  return result && result.data && result.data.cap_id;
1336
1401
  } catch {
@@ -1343,7 +1408,7 @@ async function claimStory({ story_id }) {
1343
1408
  "POST",
1344
1409
  `/api/v1/stories/${story_id}/claim`,
1345
1410
  null,
1346
- process.env.LOOPCTL_AGENT_KEY
1411
+ agentKey()
1347
1412
  );
1348
1413
  // The claim response carries the start_cap that POST /start will require.
1349
1414
  rememberCap(story_id, result && result.capability);
@@ -1359,13 +1424,13 @@ function withClaimLeaseNotice(result) {
1359
1424
  }
1360
1425
 
1361
1426
  async function renewStoryClaim(args) {
1362
- return withClaimLeaseNotice(await renewStoryClaimRequest(args, { apiCall }));
1427
+ return withClaimLeaseNotice(await renewStoryClaimRequest(args, { apiCall, env: agentKeyEnv() }));
1363
1428
  }
1364
1429
 
1365
1430
  // #803: escalation leads with a STOP line. A session that escalates and keeps working is
1366
1431
  // the failure the affordance exists to prevent, and the JSON body alone does not say so.
1367
1432
  async function escalateStory(args) {
1368
- const result = await escalateStoryRequest(args, { apiCall });
1433
+ const result = await escalateStoryRequest(args, { apiCall, env: agentKeyEnv() });
1369
1434
  const notice = escalationNotice(result);
1370
1435
  if (!notice) return toContent(result);
1371
1436
  return { content: [{ type: "text", text: notice }, ...toContent(result).content] };
@@ -1378,14 +1443,14 @@ async function startStory({ story_id, capability }) {
1378
1443
  const cap =
1379
1444
  capability ||
1380
1445
  takeCap(story_id, "start_cap") ||
1381
- (await fetchCap(story_id, "start_cap", process.env.LOOPCTL_AGENT_KEY)) ||
1446
+ (await fetchCap(story_id, "start_cap", agentKey())) ||
1382
1447
  (await recoverStartCap(story_id));
1383
1448
 
1384
1449
  const result = await apiCall(
1385
1450
  "POST",
1386
1451
  `/api/v1/stories/${story_id}/start`,
1387
1452
  cap ? { capability: cap } : null,
1388
- process.env.LOOPCTL_AGENT_KEY
1453
+ agentKey()
1389
1454
  );
1390
1455
  return toContent(result);
1391
1456
  }
@@ -1395,7 +1460,7 @@ async function requestReview({ story_id }) {
1395
1460
  "POST",
1396
1461
  `/api/v1/stories/${story_id}/request-review`,
1397
1462
  null,
1398
- process.env.LOOPCTL_AGENT_KEY
1463
+ agentKey()
1399
1464
  );
1400
1465
  return toContent(result);
1401
1466
  }
@@ -1531,7 +1596,7 @@ async function reportTokenUsage({ story_id, input_tokens, output_tokens, model_n
1531
1596
  "POST",
1532
1597
  "/api/v1/token-usage",
1533
1598
  body,
1534
- process.env.LOOPCTL_AGENT_KEY
1599
+ agentKey()
1535
1600
  );
1536
1601
  return toContent(result);
1537
1602
  }
@@ -1637,7 +1702,7 @@ async function knowledgeIndex({ project_id, story_id, category, tags, match, off
1637
1702
  if (suppressed) params.set("suppressed", suppressed);
1638
1703
  const qs = params.toString();
1639
1704
  const path = qs ? `${basePath}?${qs}` : basePath;
1640
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
1705
+ const result = await apiCall("GET", path, null, agentKey());
1641
1706
  return toContent(result);
1642
1707
  }
1643
1708
 
@@ -1646,7 +1711,7 @@ async function knowledgeIndex({ project_id, story_id, category, tags, match, off
1646
1711
  // step deletes the stale-dimension rows (loopctl reserves data-removing operations for
1647
1712
  // higher roles), so it deliberately does NOT fall back to the agent key.
1648
1713
  async function embeddingStatus() {
1649
- const result = await apiCall("GET", "/api/v1/knowledge/embeddings", null, process.env.LOOPCTL_AGENT_KEY);
1714
+ const result = await apiCall("GET", "/api/v1/knowledge/embeddings", null, agentKey());
1650
1715
  return toContent(result);
1651
1716
  }
1652
1717
 
@@ -1655,7 +1720,7 @@ async function embeddingMaterializeSystemCorpus() {
1655
1720
  "POST",
1656
1721
  "/api/v1/knowledge/embeddings/system-corpus",
1657
1722
  {},
1658
- process.env.LOOPCTL_AGENT_KEY,
1723
+ agentKey(),
1659
1724
  );
1660
1725
  return toContent(result);
1661
1726
  }
@@ -1686,7 +1751,7 @@ async function knowledgeStats({ project_id }) {
1686
1751
  const path = project_id
1687
1752
  ? `/api/v1/projects/${project_id}/knowledge/stats`
1688
1753
  : "/api/v1/knowledge/stats";
1689
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
1754
+ const result = await apiCall("GET", path, null, agentKey());
1690
1755
  return toContent(result);
1691
1756
  }
1692
1757
 
@@ -1701,7 +1766,7 @@ async function knowledgeGraph({ article_id, depth, project_id }) {
1701
1766
  "GET",
1702
1767
  `/api/v1/knowledge/graph?${params}`,
1703
1768
  null,
1704
- process.env.LOOPCTL_AGENT_KEY,
1769
+ agentKey(),
1705
1770
  );
1706
1771
  return toContent(result);
1707
1772
  }
@@ -1718,7 +1783,7 @@ async function knowledgeSuggestLinks({ article_id, limit, threshold }) {
1718
1783
  "GET",
1719
1784
  qs ? `${base}?${qs}` : base,
1720
1785
  null,
1721
- process.env.LOOPCTL_AGENT_KEY,
1786
+ agentKey(),
1722
1787
  );
1723
1788
  return toContent(result);
1724
1789
  }
@@ -1732,7 +1797,7 @@ async function knowledgeDistantPairs({ min_distance, max_distance, bridge_path,
1732
1797
  if (offset != null) params.set("offset", String(offset));
1733
1798
  const qs = params.toString();
1734
1799
  const path = qs ? `/api/v1/knowledge/pairs?${qs}` : "/api/v1/knowledge/pairs";
1735
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
1800
+ const result = await apiCall("GET", path, null, agentKey());
1736
1801
  return toContent(result);
1737
1802
  }
1738
1803
 
@@ -1742,7 +1807,7 @@ async function knowledgeNovelty({ ideas, texts, prior_tag }) {
1742
1807
  if (ideas !== undefined) body.ideas = ideas;
1743
1808
  if (texts !== undefined) body.texts = texts;
1744
1809
  if (prior_tag) body.prior_tag = prior_tag;
1745
- const result = await apiCall("POST", "/api/v1/knowledge/novelty", body, process.env.LOOPCTL_AGENT_KEY);
1810
+ const result = await apiCall("POST", "/api/v1/knowledge/novelty", body, agentKey());
1746
1811
  return toContent(result);
1747
1812
  }
1748
1813
 
@@ -1754,7 +1819,7 @@ async function knowledgeRandomWalk({ start_id, length }) {
1754
1819
  "GET",
1755
1820
  `/api/v1/knowledge/walk?${params}`,
1756
1821
  null,
1757
- process.env.LOOPCTL_AGENT_KEY,
1822
+ agentKey(),
1758
1823
  );
1759
1824
  return toContent(result);
1760
1825
  }
@@ -1780,7 +1845,7 @@ async function knowledgeCount({
1780
1845
  if (idempotency_key) params.set("idempotency_key", idempotency_key);
1781
1846
  const qs = params.toString();
1782
1847
  const path = qs ? `/api/v1/knowledge/count?${qs}` : "/api/v1/knowledge/count";
1783
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
1848
+ const result = await apiCall("GET", path, null, agentKey());
1784
1849
  return toContent(result);
1785
1850
  }
1786
1851
 
@@ -1806,7 +1871,7 @@ async function knowledgeFacets({
1806
1871
  "GET",
1807
1872
  `/api/v1/knowledge/facets?${params}`,
1808
1873
  null,
1809
- process.env.LOOPCTL_AGENT_KEY,
1874
+ agentKey(),
1810
1875
  );
1811
1876
  return toContent(result);
1812
1877
  }
@@ -1830,7 +1895,7 @@ async function knowledgeSearch({ q, project_id, story_id, category, tags, match,
1830
1895
  if (limit != null) params.set("limit", String(limit));
1831
1896
  if (offset != null) params.set("offset", String(offset));
1832
1897
 
1833
- const result = await apiCall("GET", `/api/v1/knowledge/search?${params}`, null, process.env.LOOPCTL_AGENT_KEY);
1898
+ const result = await apiCall("GET", `/api/v1/knowledge/search?${params}`, null, agentKey());
1834
1899
  // If search silently degraded to keyword-only for a missing embedding key, the
1835
1900
  // server attaches meta.remediation — surface it PROMINENTLY so the agent knows to
1836
1901
  // call set_llm_config to enable semantic ranking.
@@ -1850,7 +1915,7 @@ async function knowledgeHybridSearch({ query, project_id, category, tags, match,
1850
1915
  "POST",
1851
1916
  "/api/v1/knowledge/hybrid_search",
1852
1917
  bodyPayload,
1853
- process.env.LOOPCTL_AGENT_KEY,
1918
+ agentKey(),
1854
1919
  );
1855
1920
  // meta.provenance ("curated" | "retrieved") is the load-bearing field and rides
1856
1921
  // through toContent verbatim. Same missing-embedding-key remediation surfacing as
@@ -1872,7 +1937,7 @@ async function knowledgeProgressiveIndex({ topic, query, category, limit }) {
1872
1937
  "GET",
1873
1938
  `/api/v1/knowledge/progressive_index?${params}`,
1874
1939
  null,
1875
- process.env.LOOPCTL_AGENT_KEY,
1940
+ agentKey(),
1876
1941
  );
1877
1942
  // A topic browse is a RETRIEVAL: it runs the same ranked pool, so it can come back
1878
1943
  // short or keyword-only. Without the banner a shed index reads as "the KB has no
@@ -1890,7 +1955,7 @@ async function knowledgeHeatIndex({ category, limit, since }) {
1890
1955
  "GET",
1891
1956
  `/api/v1/knowledge/heat_index?${params}`,
1892
1957
  null,
1893
- process.env.LOOPCTL_AGENT_KEY,
1958
+ agentKey(),
1894
1959
  );
1895
1960
  // The query-free route, reached for precisely when the query-shaped ones came back
1896
1961
  // empty — so an unannounced degradation here strands the agent with no route left.
@@ -1913,7 +1978,7 @@ async function knowledgeProgressiveDrill({ article_id, body_max_bytes, body_offs
1913
1978
  "GET",
1914
1979
  qs ? `${base}?${qs}` : base,
1915
1980
  null,
1916
- process.env.LOOPCTL_AGENT_KEY,
1981
+ agentKey(),
1917
1982
  );
1918
1983
  return toContent(result);
1919
1984
  }
@@ -1956,7 +2021,7 @@ async function knowledgeList({
1956
2021
  "GET",
1957
2022
  `/api/v1/articles?${params}`,
1958
2023
  null,
1959
- process.env.LOOPCTL_AGENT_KEY,
2024
+ agentKey(),
1960
2025
  );
1961
2026
  // Enumeration, not ranking — but a short page still under-reports the set, and an
1962
2027
  // agent enumerating to decide something absent is the caller least able to tell.
@@ -1988,7 +2053,7 @@ async function knowledgeGet({
1988
2053
  params.set("body_offset", String(body_offset));
1989
2054
  const qs = params.toString();
1990
2055
  const path = qs ? `/api/v1/articles/${art.id}?${qs}` : `/api/v1/articles/${art.id}`;
1991
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
2056
+ const result = await apiCall("GET", path, null, agentKey());
1992
2057
  return toContent(result);
1993
2058
  }
1994
2059
 
@@ -2012,7 +2077,7 @@ async function knowledgeContext({
2012
2077
  if (agents) params.set("agents", Array.isArray(agents) ? agents.join(",") : agents);
2013
2078
  if (conversation_id) params.set("conversation_id", conversation_id);
2014
2079
 
2015
- const result = await apiCall("GET", `/api/v1/knowledge/context?${params}`, null, process.env.LOOPCTL_AGENT_KEY);
2080
+ const result = await apiCall("GET", `/api/v1/knowledge/context?${params}`, null, agentKey());
2016
2081
  // Same as knowledge_search: surface a missing-embedding-key remediation prominently.
2017
2082
  return withRemediationNotice(result);
2018
2083
  }
@@ -2056,7 +2121,7 @@ async function knowledgeCreate({
2056
2121
  "POST",
2057
2122
  "/api/v1/articles",
2058
2123
  payload,
2059
- process.env.LOOPCTL_AGENT_KEY,
2124
+ agentKey(),
2060
2125
  );
2061
2126
  return toContent(result);
2062
2127
  }
@@ -2078,7 +2143,7 @@ async function knowledgeUpdate({ article_id, title, body, category, tags, metada
2078
2143
  "PATCH",
2079
2144
  `/api/v1/articles/${art.id}`,
2080
2145
  payload,
2081
- process.env.LOOPCTL_AGENT_KEY,
2146
+ agentKey(),
2082
2147
  );
2083
2148
  return toContent(result);
2084
2149
  }
@@ -2126,7 +2191,7 @@ async function memoryRemember({
2126
2191
  "POST",
2127
2192
  "/api/v1/memory",
2128
2193
  payload,
2129
- process.env.LOOPCTL_AGENT_KEY,
2194
+ agentKey(),
2130
2195
  );
2131
2196
  return toContent(result);
2132
2197
  }
@@ -2140,7 +2205,7 @@ async function memoryRecall({ query, limit, include_superseded }) {
2140
2205
  "POST",
2141
2206
  "/api/v1/memory/recall",
2142
2207
  payload,
2143
- process.env.LOOPCTL_AGENT_KEY,
2208
+ agentKey(),
2144
2209
  );
2145
2210
  // Surface meta (fallback/reason/total_count/underfilled) so the caller can tell
2146
2211
  // a degraded recall from a genuinely empty scope (AC-28.4.4). meta alone was not
@@ -2167,7 +2232,7 @@ async function recallContext({ query, project_id, limit, session_id }) {
2167
2232
  "POST",
2168
2233
  "/api/v1/recall",
2169
2234
  payload,
2170
- process.env.LOOPCTL_AGENT_KEY,
2235
+ agentKey(),
2171
2236
  );
2172
2237
  // Surface both per-source metas (memory fallback/underfilled + knowledge degraded)
2173
2238
  // so the caller can tell a degraded recall from a genuinely empty scope. The merged
@@ -2201,7 +2266,7 @@ async function recallReferenced({ recall_id, article_ids, project_id }) {
2201
2266
  "POST",
2202
2267
  `/api/v1/recall/${encodeURIComponent(recall_id.trim())}/referenced`,
2203
2268
  payload,
2204
- process.env.LOOPCTL_AGENT_KEY,
2269
+ agentKey(),
2205
2270
  );
2206
2271
  return toContent(result);
2207
2272
  }
@@ -2212,7 +2277,7 @@ async function memoryList({ limit, offset, include_superseded, all_subjects }) {
2212
2277
  // one deliberate cross-subject read this MCP surface can express (module
2213
2278
  // comment above), and only for a superadmin caller.
2214
2279
  const path = memoryPath({ limit, offset, include_superseded, all_subjects });
2215
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
2280
+ const result = await apiCall("GET", path, null, agentKey());
2216
2281
  // Surface meta.total_count/limit/offset (AC-28.4.4).
2217
2282
  return toContent(result);
2218
2283
  }
@@ -2230,7 +2295,7 @@ async function memoryForget({ id }) {
2230
2295
  "DELETE",
2231
2296
  `/api/v1/memory/${id}`,
2232
2297
  null,
2233
- process.env.LOOPCTL_AGENT_KEY,
2298
+ agentKey(),
2234
2299
  );
2235
2300
  return toContent(result);
2236
2301
  }
@@ -2241,7 +2306,7 @@ async function memoryPromote({ session_id }) {
2241
2306
  "POST",
2242
2307
  "/api/v1/memory/promote",
2243
2308
  payload,
2244
- process.env.LOOPCTL_AGENT_KEY,
2309
+ agentKey(),
2245
2310
  );
2246
2311
  return toContent(result);
2247
2312
  }
@@ -2259,7 +2324,7 @@ async function memoryGraduate({ memory_id, re_scope }) {
2259
2324
  "POST",
2260
2325
  "/api/v1/memory/graduate",
2261
2326
  payload,
2262
- process.env.LOOPCTL_AGENT_KEY,
2327
+ agentKey(),
2263
2328
  );
2264
2329
  return toContent(result);
2265
2330
  }
@@ -2345,7 +2410,7 @@ async function knowledgeArchive({ article_id }) {
2345
2410
  "POST",
2346
2411
  `/api/v1/articles/${art.id}/archive`,
2347
2412
  null,
2348
- process.env.LOOPCTL_AGENT_KEY
2413
+ agentKey()
2349
2414
  );
2350
2415
  return toContent(result);
2351
2416
  }
@@ -2360,7 +2425,7 @@ async function knowledgeSuppress({ article_id, reason }) {
2360
2425
  "POST",
2361
2426
  `/api/v1/articles/${art.id}/suppress`,
2362
2427
  { reason },
2363
- process.env.LOOPCTL_AGENT_KEY
2428
+ agentKey()
2364
2429
  );
2365
2430
  return toContent(result);
2366
2431
  }
@@ -2372,7 +2437,7 @@ async function knowledgeUnsuppress({ article_id }) {
2372
2437
  "POST",
2373
2438
  `/api/v1/articles/${art.id}/unsuppress`,
2374
2439
  null,
2375
- process.env.LOOPCTL_AGENT_KEY
2440
+ agentKey()
2376
2441
  );
2377
2442
  return toContent(result);
2378
2443
  }
@@ -2385,7 +2450,7 @@ async function knowledgeDelete({ article_id }) {
2385
2450
  "DELETE",
2386
2451
  `/api/v1/articles/${art.id}`,
2387
2452
  null,
2388
- process.env.LOOPCTL_AGENT_KEY
2453
+ agentKey()
2389
2454
  );
2390
2455
  return toContent(result);
2391
2456
  }
@@ -2472,7 +2537,7 @@ async function knowledgeConflicts({ limit, offset }) {
2472
2537
  const path = qs
2473
2538
  ? `/api/v1/knowledge/conflicts?${qs}`
2474
2539
  : "/api/v1/knowledge/conflicts";
2475
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
2540
+ const result = await apiCall("GET", path, null, agentKey());
2476
2541
  return toContent(result);
2477
2542
  }
2478
2543
 
@@ -2491,7 +2556,7 @@ async function knowledgeAssertConflict({
2491
2556
  "POST",
2492
2557
  "/api/v1/knowledge/conflicts",
2493
2558
  payload,
2494
- process.env.LOOPCTL_AGENT_KEY,
2559
+ agentKey(),
2495
2560
  );
2496
2561
  return toContent(result);
2497
2562
  }
@@ -2523,7 +2588,7 @@ async function knowledgeResolveConflict({
2523
2588
  "POST",
2524
2589
  "/api/v1/knowledge/conflicts/resolve",
2525
2590
  payload,
2526
- process.env.LOOPCTL_AGENT_KEY,
2591
+ agentKey(),
2527
2592
  );
2528
2593
  return toContent(result);
2529
2594
  }
@@ -2697,7 +2762,7 @@ async function egressPosture() {
2697
2762
  "GET",
2698
2763
  "/api/v1/egress/posture",
2699
2764
  null,
2700
- process.env.LOOPCTL_AGENT_KEY,
2765
+ agentKey(),
2701
2766
  );
2702
2767
  return toContent(result);
2703
2768
  }
@@ -2714,7 +2779,7 @@ async function custodyClaim({ subject_type, subject_id } = {}) {
2714
2779
  "GET",
2715
2780
  `/api/v1/custody/claims/${encodeURIComponent(subject_type)}/${encodeURIComponent(subject_id)}`,
2716
2781
  null,
2717
- process.env.LOOPCTL_AGENT_KEY,
2782
+ agentKey(),
2718
2783
  );
2719
2784
  return toContent(result);
2720
2785
  }
@@ -2724,7 +2789,7 @@ async function custodyFailures() {
2724
2789
  "GET",
2725
2790
  "/api/v1/custody/failures",
2726
2791
  null,
2727
- process.env.LOOPCTL_AGENT_KEY,
2792
+ agentKey(),
2728
2793
  );
2729
2794
  return toContent(result);
2730
2795
  }
@@ -2788,7 +2853,7 @@ async function egressRepin({ host, project_id } = {}) {
2788
2853
  "POST",
2789
2854
  "/api/v1/egress/repin",
2790
2855
  body,
2791
- process.env.LOOPCTL_AGENT_KEY,
2856
+ agentKey(),
2792
2857
  );
2793
2858
  return toContent(result);
2794
2859
  }
@@ -3165,6 +3230,51 @@ async function revokeDispatch(args) {
3165
3230
  );
3166
3231
  }
3167
3232
 
3233
+ // US-52.13: this session's holder. The raw credential never leaves the process, so each tool
3234
+ // answers with `holderSession.status()` beside what loopctl said, never the key.
3235
+ async function holderRegisterTool() {
3236
+ const result = await holderSession.register();
3237
+ return toContent(result && result.error ? result : holderSession.status());
3238
+ }
3239
+
3240
+ async function holderHeartbeatTool() {
3241
+ const result = await holderSession.heartbeat();
3242
+ return toContent(result && result.error ? result : { ...holderSession.status(), lease: result });
3243
+ }
3244
+
3245
+ async function holderEndTool() {
3246
+ const result = await holderSession.end();
3247
+ return toContent(result && result.error ? result : holderSession.status());
3248
+ }
3249
+
3250
+ // US-52.17: a work item's notes, on the session's own key: the write is accepted from the
3251
+ // story's CURRENT holder, so it travels on the credential that holds it (lib/work-items.js).
3252
+ async function workItemNoteTool(args) {
3253
+ return toContent(
3254
+ await writeWorkItemNote(args, {
3255
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3256
+ }),
3257
+ );
3258
+ }
3259
+
3260
+ // US-52.18: open (or reopen) the work item for a branch, on the session's own key: the
3261
+ // route accepts only a holder credential (lib/branch-item.js).
3262
+ async function workItemOpenTool(args) {
3263
+ return toContent(
3264
+ await openWorkItem(args, {
3265
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3266
+ }),
3267
+ );
3268
+ }
3269
+
3270
+ async function workItemNotesTool(args) {
3271
+ return toContent(
3272
+ await listWorkItemNotes(args, {
3273
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3274
+ }),
3275
+ );
3276
+ }
3277
+
3168
3278
  // LCP-1 §9.2: register/rotate the tenant custody owner key (root of trust).
3169
3279
  // ROTATION (an owner key already exists) requires `rotation_proof`: a hex Ed25519
3170
3280
  // signature by the OUTGOING owner key over owner_rotation_preimage(tenant_id,
@@ -3494,7 +3604,7 @@ async function storyStage(args) {
3494
3604
  // LOOPCTL_API_KEY, then an override, then LOOPCTL_ORCH_KEY — never LOOPCTL_AGENT_KEY. A
3495
3605
  // session refused `stale_stage` is running on an agent key, and this read is what tells it
3496
3606
  // where the row actually is, so on an agent-key-only config it has to work.
3497
- const key = process.env.LOOPCTL_AGENT_KEY;
3607
+ const key = agentKey();
3498
3608
 
3499
3609
  return toContent(
3500
3610
  await storyStageRequest(args, {
@@ -3510,7 +3620,7 @@ async function storyStage(args) {
3510
3620
  // OVERRIDE, not `exactKey`, so `resolveKey`'s order holds: LOOPCTL_API_KEY when set, else
3511
3621
  // LOOPCTL_AGENT_KEY, else LOOPCTL_ORCH_KEY.
3512
3622
  async function changeBindingGet(args) {
3513
- const key = process.env.LOOPCTL_AGENT_KEY;
3623
+ const key = agentKey();
3514
3624
 
3515
3625
  return toContent(
3516
3626
  await changeBindingGetRequest(args, {
@@ -3522,7 +3632,7 @@ async function changeBindingGet(args) {
3522
3632
  // US-48.12: a READ of the run-outcome ledger, `role: :agent` with the hierarchy — keyed as
3523
3633
  // changeBindingGet is, LOOPCTL_AGENT_KEY as an OVERRIDE so `resolveKey`'s order holds.
3524
3634
  async function agentOutcomesRead(args) {
3525
- const key = process.env.LOOPCTL_AGENT_KEY;
3635
+ const key = agentKey();
3526
3636
 
3527
3637
  return toContent(
3528
3638
  await agentOutcomes(args, {
@@ -3534,7 +3644,7 @@ async function agentOutcomesRead(args) {
3534
3644
  // US-50.6: a READ of the chg ledger summary, `role: :agent` with the hierarchy — keyed as
3535
3645
  // agentOutcomesRead is, LOOPCTL_AGENT_KEY as an OVERRIDE so `resolveKey`'s order holds.
3536
3646
  async function chgLedgerSummaryRead(args) {
3537
- const key = process.env.LOOPCTL_AGENT_KEY;
3647
+ const key = agentKey();
3538
3648
 
3539
3649
  return toContent(
3540
3650
  await chgLedgerSummary(args, {
@@ -3546,7 +3656,7 @@ async function chgLedgerSummaryRead(args) {
3546
3656
  // US-51.6: the findings list is a READ keyed as chgLedgerSummaryRead is; clearing one is a
3547
3657
  // person's act and takes the EXACT user key through runnerDeps().
3548
3658
  async function chgFindingsRead(args) {
3549
- const key = process.env.LOOPCTL_AGENT_KEY;
3659
+ const key = agentKey();
3550
3660
 
3551
3661
  return toContent(
3552
3662
  await chgFindings(args, {
@@ -3570,7 +3680,7 @@ async function resolveEscalation(args) {
3570
3680
  // US-48.11: the escalation inbox is a READ, `role: :agent` with the hierarchy, so it takes
3571
3681
  // LOOPCTL_AGENT_KEY as an override for changeBindingGet's reason above, never `exactKey`.
3572
3682
  async function escalationListRead(args) {
3573
- const key = process.env.LOOPCTL_AGENT_KEY;
3683
+ const key = agentKey();
3574
3684
 
3575
3685
  return toContent(
3576
3686
  withRemedies(
@@ -3741,7 +3851,7 @@ async function corpusCreate(args) {
3741
3851
  "POST",
3742
3852
  corporaPath(),
3743
3853
  buildCorpusCreateBody(args),
3744
- process.env.LOOPCTL_AGENT_KEY,
3854
+ agentKey(),
3745
3855
  );
3746
3856
  return toContent(result);
3747
3857
  }
@@ -3751,7 +3861,7 @@ async function corpusList(args = {}) {
3751
3861
  "GET",
3752
3862
  corporaPath(args),
3753
3863
  null,
3754
- process.env.LOOPCTL_AGENT_KEY,
3864
+ agentKey(),
3755
3865
  );
3756
3866
  return toContent(result);
3757
3867
  }
@@ -3763,7 +3873,7 @@ async function corpusIndex({ corpus_id, chunks, source_complete }) {
3763
3873
  "POST",
3764
3874
  corpusIndexPath(corpus_id),
3765
3875
  buildCorpusIndexBody({ chunks, source_complete }),
3766
- process.env.LOOPCTL_AGENT_KEY,
3876
+ agentKey(),
3767
3877
  );
3768
3878
  return toContent(result);
3769
3879
  }
@@ -3773,7 +3883,7 @@ async function corpusSearch({ corpus_id, query, query_vector, lanes, limit }) {
3773
3883
  "POST",
3774
3884
  corpusSearchPath(corpus_id),
3775
3885
  buildCorpusSearchBody({ query, query_vector, lanes, limit }),
3776
- process.env.LOOPCTL_AGENT_KEY,
3886
+ agentKey(),
3777
3887
  );
3778
3888
  // Pointers + snippets only — the caller's next step is to open the file at
3779
3889
  // source_ref/locator. Nothing here is auto-injected into a recall pack, so a
@@ -3787,7 +3897,7 @@ async function corpusStatus({ corpus_id, limit, offset }) {
3787
3897
  "GET",
3788
3898
  corpusStatusPath(corpus_id, { limit, offset }),
3789
3899
  null,
3790
- process.env.LOOPCTL_AGENT_KEY,
3900
+ agentKey(),
3791
3901
  );
3792
3902
  return toContent(result);
3793
3903
  }
@@ -4226,7 +4336,8 @@ const TOOLS = [
4226
4336
  {
4227
4337
  name: "channel_claim",
4228
4338
  description:
4229
- "Claim a handoff ref for EXACTLY ONE agent on a repo coordination channel (Epic 40 Repo Coordination Bus, US-40.B1), on the agent key. Use this to coordinate an out-of-band unit of work (e.g. 'handoff:repo#812') among several agents racing on the same repo, so only ONE picks it up. INSERT-to-claim: the first agent to claim (tenant, project, ref) wins and gets the claim. Re-claiming YOUR OWN still-active ref is idempotent — it returns your existing claim, so a lost response / timeout is safe to retry with the same ref. A 409 tells you WHICH of four situations you hit, in its error.code — do not treat every 409 the same. 409 already_claimed means a peer holds a live claim, or you already completed this one: the ref is taken, so move on to other work. 409 claim_lease_expired means the lease died without completion and the row is only awaiting the sweeper — nobody is working it, so retry THIS ref shortly rather than moving on. 409 ref_superseded means the ref's instructions were retired by a successor post: nobody holds it, claim the successor instead. 409 claim_budget_exhausted is a limit on YOU, not a statement about the ref — finish or release one of your open claims and retry. channel_claims shows the same distinction on each row via its expired and done flags. A channel IS a project_id; the claim is tenant-isolated and project-scoped by membership (you must be a writable member of the project). tenant/agent are server-stamped from your verified key. Mark the work finished with channel_done, or give it up for another agent with channel_release. READ THE already_held FLAG BEFORE YOU START WORKING (issue #779). A fresh claim answers 201 with created: true. An idempotent re-claim answers 200 with created: false, already_held: true, the row's ORIGINAL claimed_at, and the claimed_by_session/claimed_by_host of whoever actually took it — and because a fleet's sessions typically all authenticate as ONE agent_id, that idempotent branch is ALSO what a PEER SESSION's live claim comes back as. already_held is the DECISIVE flag: the row already existed, so you did not take this ref and must not start the work on the strength of this call alone. same_session only refines it, and is the server's comparison against this session's id. false means a DIFFERENT session stamped it — usually a peer, but ALSO your own session after a restart, because a relaunched session carries a new id: compare claimed_by_host and claimed_at (an older timestamp on this same host is very likely your own crashed run) before standing down, and finish or release that ref with force: true rather than abandoning it for the rest of the lease. null means undiscriminable (the row predates the field, or the client that wrote it sends none) and is NOT the same as false. true means the same Claude Code session — which a dispatched subagent shares with its parent and its siblings, so it is not proof that YOU took it. Two machines each read a bare success as 'one claim, mine' and shipped duplicate PRs before this flag existed. STILL DO NOT USE THIS AS A PROBE: the marker tells you afterwards that you did not create the claim, but the write is still a write — call channel_claims, which answers the same question and writes nothing.",
4339
+ "Claim a handoff ref for EXACTLY ONE agent on a repo coordination channel (Epic 40 Repo Coordination Bus, US-40.B1), on the agent key. Use this to coordinate an out-of-band unit of work (e.g. 'handoff:repo#812') among several agents racing on the same repo, so only ONE picks it up. INSERT-to-claim: the first agent to claim (tenant, project, ref) wins and gets the claim. Re-claiming YOUR OWN still-active ref is idempotent — it returns your existing claim, so a lost response / timeout is safe to retry with the same ref. A 409 tells you WHICH of four situations you hit, in its error.code — do not treat every 409 the same. 409 already_claimed means a peer holds a live claim, or you already completed this one: the ref is taken, so move on to other work. 409 claim_lease_expired means the lease died without completion and the row is only awaiting the sweeper — nobody is working it, so retry THIS ref shortly rather than moving on. 409 ref_superseded means the ref's instructions were retired by a successor post: nobody holds it, claim the successor instead. 409 claim_budget_exhausted is a limit on YOU, not a statement about the ref — finish or release one of your open claims and retry. channel_claims shows the same distinction on each row via its expired and done flags. A channel IS a project_id; the claim is tenant-isolated and project-scoped by membership (you must be a writable member of the project). tenant/agent are server-stamped from your verified key. Mark the work finished with channel_done, or give it up for another agent with channel_release. READ THE already_held FLAG BEFORE YOU START WORKING (issue #779). A fresh claim answers 201 with created: true. An idempotent re-claim answers 200 with created: false, already_held: true, the row's ORIGINAL claimed_at, and the claimed_by_session/claimed_by_host of whoever actually took it — and because a fleet's sessions typically all authenticate as ONE agent_id, that idempotent branch is ALSO what a PEER SESSION's live claim comes back as. already_held is the DECISIVE flag: the row already existed, so you did not take this ref and must not start the work on the strength of this call alone. same_session only refines it, and is the server's comparison against this session's id. false means a DIFFERENT session stamped it — usually a peer, but ALSO your own session after a restart, because a relaunched session carries a new id: compare claimed_by_host and claimed_at (an older timestamp on this same host is very likely your own crashed run) before standing down, and finish or release that ref with force: true rather than abandoning it for the rest of the lease. null means undiscriminable (the row predates the field, or the client that wrote it sends none) and is NOT the same as false. true means the same Claude Code session — which a dispatched subagent shares with its parent and its siblings, so it is not proof that YOU took it. Two machines each read a bare success as 'one claim, mine' and shipped duplicate PRs before this flag existed. STILL DO NOT USE THIS AS A PROBE: the marker tells you afterwards that you did not create the claim, but the write is still a write — call channel_claims, which answers the same question and writes nothing. " +
4340
+ CHANNEL_HELD_BY_OTHER_SESSION,
4230
4341
  inputSchema: {
4231
4342
  type: "object",
4232
4343
  properties: {
@@ -4251,7 +4362,8 @@ const TOOLS = [
4251
4362
  {
4252
4363
  name: "channel_release",
4253
4364
  description:
4254
- "Release (give up) YOUR OWN claim on a handoff ref on a repo coordination channel (Epic 40 Repo Coordination Bus, US-40.B1), on the agent key — deletes the claim so the ref reopens and another agent can claim it. Owner-scoped: you can only release a claim you made; a claim you do not own, or one in another tenant, or a nonexistent one, returns a byte-identical 404 (no existence oracle). SCOPE: ownership is (tenant, project, AGENT, ref), and on top of it the server refuses a claim stamped by a DIFFERENT SESSION with 409 claim_session_mismatch (issue #779) — this call used to DELETE a peer session's live claim, silently, because two sessions on one agent key were indistinguishable. That refusal is ADVISORY, not authorization: session_id is proxy-supplied and spoofable, and force: true clears it. Use force ONLY when the claim is your own work from a session that has since restarted (a relaunched session carries a new session id) — never to take a ref off a peer that is still working it. Read channel_claims first: claimed_by_session, claimed_by_host and same_session say whose claim it is. A claim whose session died for good is also protected by the abandoned-lease sweep.",
4365
+ "Release (give up) YOUR OWN claim on a handoff ref on a repo coordination channel (Epic 40 Repo Coordination Bus, US-40.B1), on the agent key — deletes the claim so the ref reopens and another agent can claim it. Owner-scoped: you can only release a claim you made; a claim you do not own, or one in another tenant, or a nonexistent one, returns a byte-identical 404 (no existence oracle). SCOPE: ownership is (tenant, project, AGENT, ref), and on top of it the server refuses a claim stamped by a DIFFERENT SESSION with 409 claim_session_mismatch (issue #779) — this call used to DELETE a peer session's live claim, silently, because two sessions on one agent key were indistinguishable. That refusal is ADVISORY, not authorization: session_id is proxy-supplied and spoofable, and force: true clears it. Use force ONLY when the claim is your own work from a session that has since restarted (a relaunched session carries a new session id) — never to take a ref off a peer that is still working it. Read channel_claims first: claimed_by_session, claimed_by_host and same_session say whose claim it is. A claim whose session died for good is also protected by the abandoned-lease sweep. " +
4366
+ CHANNEL_HELD_BY_OTHER_SESSION,
4255
4367
  inputSchema: {
4256
4368
  type: "object",
4257
4369
  properties: {
@@ -4269,7 +4381,8 @@ const TOOLS = [
4269
4381
  {
4270
4382
  name: "channel_done",
4271
4383
  description:
4272
- "Mark YOUR OWN handoff claim done on a repo coordination channel (Epic 40 Repo Coordination Bus, US-40.B1), on the agent key — sets done_at, recording that you completed the claimed work. The done claim is retained briefly (7 days) as an audit/idempotency breadcrumb, then swept. Owner-scoped: you can only mark done a claim you made; a claim you do not own, or one in another tenant, or a nonexistent one, returns a byte-identical 404 (no existence oracle). A claim stamped by a DIFFERENT SESSION on your agent key is 409 claim_session_mismatch (issue #779) — do not mark done work a peer session is doing. That refusal is ADVISORY (session_id is proxy-supplied and spoofable, so it stops an accident, not an attack) and force: true clears it, which is what a session that crashed and relaunched under a new session id should use to finish its own work rather than waiting out the lease.",
4384
+ "Mark YOUR OWN handoff claim done on a repo coordination channel (Epic 40 Repo Coordination Bus, US-40.B1), on the agent key — sets done_at, recording that you completed the claimed work. The done claim is retained briefly (7 days) as an audit/idempotency breadcrumb, then swept. Owner-scoped: you can only mark done a claim you made; a claim you do not own, or one in another tenant, or a nonexistent one, returns a byte-identical 404 (no existence oracle). A claim stamped by a DIFFERENT SESSION on your agent key is 409 claim_session_mismatch (issue #779) — do not mark done work a peer session is doing. That refusal is ADVISORY (session_id is proxy-supplied and spoofable, so it stops an accident, not an attack) and force: true clears it, which is what a session that crashed and relaunched under a new session id should use to finish its own work rather than waiting out the lease. " +
4385
+ CHANNEL_HELD_BY_OTHER_SESSION,
4273
4386
  inputSchema: {
4274
4387
  type: "object",
4275
4388
  properties: {
@@ -4878,7 +4991,11 @@ const TOOLS = [
4878
4991
  },
4879
4992
  {
4880
4993
  name: "get_story",
4881
- description: "Get full details for a single story by ID.",
4994
+ description:
4995
+ "Get full details for a single story by ID. The claim is on it: assigned_holder_id, " +
4996
+ "claim_epoch and claimed_until, and assigned_holder (id, kind, host, session_id, " +
4997
+ "lease_until, ended_at, ended_reason) naming the SESSION that holds it, so a claim of " +
4998
+ "another session of your own agent reads as someone else's.",
4882
4999
  inputSchema: {
4883
5000
  type: "object",
4884
5001
  properties: {
@@ -4928,14 +5045,19 @@ const TOOLS = [
4928
5045
  "Transitions contracted -> assigned. Uses the AGENT key. On a loopctl with claim leases " +
4929
5046
  "the result leads with the claim's claim_epoch and claimed_until: keep the epoch, and " +
4930
5047
  "renew with renew_story_claim before claimed_until (default lease 24 hours) or the story " +
4931
- "is released back to pending under you. Refused 409 story_held when the story's " +
5048
+ "is released back to pending under you. Claimed with this session's holder credential, " +
5049
+ "the claim instead takes the holder's lease and the heartbeat keeps it alive; refused " +
5050
+ "409 holder_lease_expired once that lease has run out. Refused 409 story_held when the story's " +
4932
5051
  "delivery stage is escalated, done or failed: it is not yours to claim even when it " +
4933
5052
  "reads pending or contracted — move on. An escalated story is claimable again only " +
4934
5053
  "after resolve_escalation sends it to queued; a done or failed one never is. Refused " +
4935
5054
  "409 dependencies_not_met when a story it depends on, or one in an epic its epic " +
4936
5055
  "depends on, is not verified: list_blocked_stories names them. Refused 409 " +
4937
5056
  "chg_root_review_only when the key descends from an intake source's " +
4938
- "chg_root_dispatch_id: chg-server's keys may only review.",
5057
+ "chg_root_dispatch_id: chg-server's keys may only review. " +
5058
+ HELD_BY_OTHER_HOLDER +
5059
+ " Claiming a story THIS session already holds returns the claim unchanged, so a " +
5060
+ "retry after a lost response is safe.",
4939
5061
  inputSchema: {
4940
5062
  type: "object",
4941
5063
  properties: {
@@ -4966,7 +5088,8 @@ const TOOLS = [
4966
5088
  "expired and was reclaimed, released, or claimed again, so stop working it); 409 " +
4967
5089
  "not_claimant (your key's agent is not the story's assigned agent); " +
4968
5090
  "409 lease_cap_reached (a driver-placed claim already at its cap: nothing is renewed " +
4969
- "and the claim ends there, so stop working it).",
5091
+ "and the claim ends there, so stop working it). " +
5092
+ HELD_BY_OTHER_HOLDER,
4970
5093
  inputSchema: {
4971
5094
  type: "object",
4972
5095
  properties: {
@@ -5039,7 +5162,8 @@ const TOOLS = [
5039
5162
  "Agent starts work on a claimed story. Transitions assigned -> implementing. Uses the AGENT key. " +
5040
5163
  "The L1 capability (start_cap) is handled for you: it is taken from the claim_story response, " +
5041
5164
  "and re-minted via recover-cap if this process lost it (e.g. after a session crash). " +
5042
- "Pass `capability` only to override that.",
5165
+ "Pass `capability` only to override that. " +
5166
+ HELD_BY_OTHER_HOLDER,
5043
5167
  inputSchema: {
5044
5168
  type: "object",
5045
5169
  properties: {
@@ -5062,7 +5186,8 @@ const TOOLS = [
5062
5186
  name: "request_review",
5063
5187
  description:
5064
5188
  "Agent signals that implementation is complete and ready for review. " +
5065
- "Does NOT change the story status — fires a webhook event for the reviewer. Uses the AGENT key.",
5189
+ "Does NOT change the story status — fires a webhook event for the reviewer. Uses the AGENT key. " +
5190
+ HELD_BY_OTHER_HOLDER,
5066
5191
  inputSchema: {
5067
5192
  type: "object",
5068
5193
  properties: {
@@ -8573,6 +8698,132 @@ const TOOLS = [
8573
8698
  },
8574
8699
  },
8575
8700
 
8701
+ {
8702
+ name: "holder_register",
8703
+ description:
8704
+ "REGISTER THIS SESSION AS A HOLDER (POST /api/v1/holders, US-52.13). The MCP server " +
8705
+ "already does this at startup and heartbeats on a timer; call it only to re-register " +
8706
+ "after holder_end or when holder_heartbeat reports no holder. Sends LOOPCTL_AGENT_KEY " +
8707
+ "(exactly, never another variable) with kind interactive, this session's id, the host " +
8708
+ "and the git top level. loopctl answers with the SAME holder while it is live and a new " +
8709
+ "credential, which this process keeps in memory and sends on every agent-key request " +
8710
+ "from then on; the credential is never returned to you. REFUSES: 403 " +
8711
+ "custody_tier_required on an agent-rooted tenant, 403 holder_mint_forbidden for a " +
8712
+ "dispatch-minted key, 422 agent_required for a key naming no agent. On any refusal the " +
8713
+ "session keeps using LOOPCTL_AGENT_KEY.",
8714
+ inputSchema: { type: "object", properties: {} },
8715
+ },
8716
+
8717
+ {
8718
+ name: "holder_heartbeat",
8719
+ description:
8720
+ "RENEW THIS SESSION'S HOLDER LEASE NOW (POST /api/v1/holders/:id/heartbeat), by the " +
8721
+ "holder's own credential. The server does this every heartbeat_seconds on its own. " +
8722
+ "It also moves every uncapped claim the holder holds to the new lease. A 401, 404 or " +
8723
+ "409 (credential expired, holder ended) makes it register again; 409 " +
8724
+ "holder_lease_expired means the lease ran out first, so loopctl ended the holder and " +
8725
+ "released its claims: the session registers as a NEW holder and must re-claim.",
8726
+ inputSchema: { type: "object", properties: {} },
8727
+ },
8728
+
8729
+ {
8730
+ name: "holder_end",
8731
+ description:
8732
+ "END THIS SESSION'S HOLDER (POST /api/v1/holders/:id/end): sets ended_at and revokes " +
8733
+ "its credential; this process falls back to LOOPCTL_AGENT_KEY. The server does this " +
8734
+ "itself when stdin closes or on SIGTERM. A repeated end writes nothing.",
8735
+ inputSchema: { type: "object", properties: {} },
8736
+ },
8737
+
8738
+ {
8739
+ name: "work_item_note",
8740
+ description:
8741
+ "WRITE A NOTE ON A WORK ITEM (POST /api/v1/stories/:id/notes): your plan, progress, a " +
8742
+ "decision or an open question, appended under `section` and never edited, so the next " +
8743
+ "session resumes from the item instead of from your transcript. Records a note_written " +
8744
+ "event on the story's log in the same transaction. Uses this session's own key (its " +
8745
+ "holder credential). Only the story's CURRENT holder writes one: " +
8746
+ "409 held_by_other_holder when another session holds it (the error names that " +
8747
+ "session's holder_id, holder_kind and holder_host), 409 not_holder when nobody holds " +
8748
+ "it, 404 for a story that is not this tenant's. 422 for an unknown section, an empty " +
8749
+ "body, a body over 16384 bytes, or a body that looks like a credential (every holder " +
8750
+ "reads notes). Pass `idempotency_key` to make a retry after a lost response return the " +
8751
+ "first note and write nothing; the key is the WRITER's, so a key another writer's note " +
8752
+ "on this story already carries is 409 idempotency_key_reused and writes nothing.",
8753
+ inputSchema: {
8754
+ type: "object",
8755
+ properties: {
8756
+ story_id: { type: "string", description: "The UUID of the story." },
8757
+ section: {
8758
+ type: "string",
8759
+ enum: ["plan", "progress", "decision", "question"],
8760
+ description: "Which section the note is filed under.",
8761
+ },
8762
+ body: { type: "string", description: "The note's text, 1 to 16384 bytes." },
8763
+ idempotency_key: {
8764
+ type: "string",
8765
+ description: "Optional: a key unique to this note, so a retry writes it once.",
8766
+ },
8767
+ },
8768
+ required: ["story_id", "section", "body"],
8769
+ },
8770
+ },
8771
+
8772
+ {
8773
+ name: "work_item_open",
8774
+ description:
8775
+ "OPEN THE WORK ITEM FOR A BRANCH (POST /api/v1/work_items): your interactive work on " +
8776
+ "`branch` becomes one story in the project `repo_url` resolves to, already " +
8777
+ "implementing and held by this session, with a stage row naming the branch. The MCP " +
8778
+ "server already does this on each heartbeat for the worktree's non-default branch; " +
8779
+ "call it to name a title or an epic. The epic is `epic_id`, else the target epic of " +
8780
+ "the project's live intake source. Reopening your own item returns it (200, outcome " +
8781
+ "existing), an unheld item on the branch is claimed back for you (200, claimed), and " +
8782
+ "your one held item with no branch takes this one (200, branch_recorded). Needs this " +
8783
+ "session's holder credential: 403 holder_credential_required for any other key. 409 " +
8784
+ "branch_held (another session's open item has the branch; names story_id and " +
8785
+ "holder_id), 409 holder_ended, 409 story_held (the item is escalated). 404 " +
8786
+ "project_not_found (no project of your tenant has the repo), 404 epic_not_found. 422 " +
8787
+ "no_target_epic (pass epic_id), 422 invalid_branch (empty, whitespace, HEAD, over 255 " +
8788
+ "bytes). The item reaches verified only through report, review and verify like any " +
8789
+ "story; you cannot report it yourself.",
8790
+ inputSchema: {
8791
+ type: "object",
8792
+ properties: {
8793
+ repo_url: { type: "string", description: "The repo's remote URL (git remote get-url origin)." },
8794
+ branch: { type: "string", description: "The branch the work is on." },
8795
+ title: { type: "string", description: "Optional: the item's title (default: the branch)." },
8796
+ epic_id: { type: "string", description: "Optional: the UUID of the epic to file it under." },
8797
+ },
8798
+ required: ["repo_url", "branch"],
8799
+ },
8800
+ },
8801
+
8802
+ {
8803
+ name: "work_item_notes",
8804
+ description:
8805
+ "READ A WORK ITEM'S NOTES (GET /api/v1/stories/:id/notes), oldest first. The FIRST page " +
8806
+ "carries `current`: the newest note of each section, which is where the item stands. " +
8807
+ "Optional `section` filters to one section; `limit` defaults to 50, at most 200; pass a " +
8808
+ "page's `next_cursor` back as `after` for the next one. Any key of the tenant reads " +
8809
+ "them. 404 for a story that is not this tenant's; 422 for an unknown section or a " +
8810
+ "cursor this endpoint did not return.",
8811
+ inputSchema: {
8812
+ type: "object",
8813
+ properties: {
8814
+ story_id: { type: "string", description: "The UUID of the story." },
8815
+ section: {
8816
+ type: "string",
8817
+ enum: ["plan", "progress", "decision", "question"],
8818
+ description: "Optional: only this section's notes.",
8819
+ },
8820
+ limit: { type: "integer", description: "Optional page size (default 50, max 200)." },
8821
+ after: { type: "string", description: "Optional: the previous page's next_cursor." },
8822
+ },
8823
+ required: ["story_id"],
8824
+ },
8825
+ },
8826
+
8576
8827
  {
8577
8828
  name: "revoke_dispatch",
8578
8829
  description:
@@ -9423,11 +9674,17 @@ const TOOLS = [
9423
9674
  "server-side condition a re-run meets again until an operator acts; " +
9424
9675
  "`force_unclaim_failed` (the " +
9425
9676
  "server log names the step) is remedied by calling it again. A 422 means the release " +
9426
- "write itself was rejected. It takes no request body.",
9677
+ "write itself was rejected. Optional `reason`: recorded on the story's event log as " +
9678
+ "`force-unclaimed: <reason>` (at most 2000 characters, longer is cut); without it the " +
9679
+ "log says `force-unclaimed: operator`.",
9427
9680
  inputSchema: {
9428
9681
  type: "object",
9429
9682
  properties: {
9430
9683
  story_id: { type: "string", description: "The story UUID to free." },
9684
+ reason: {
9685
+ type: "string",
9686
+ description: "Why you are taking it back, for the story's event log.",
9687
+ },
9431
9688
  },
9432
9689
  required: ["story_id"],
9433
9690
  },
@@ -10432,7 +10689,7 @@ const TOOLS = [
10432
10689
  // that isn't `cr_`-prefixed or that collides with a built-in tool name.
10433
10690
  const generatedToolsRuntime = createGeneratedToolsRuntime({
10434
10691
  apiCall,
10435
- agentKey: () => process.env.LOOPCTL_AGENT_KEY,
10692
+ agentKey: () => agentKey(),
10436
10693
  staticToolNames: new Set(TOOLS.map((t) => t.name)),
10437
10694
  toContent,
10438
10695
  });
@@ -10920,6 +11177,24 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
10920
11177
  case "revoke_dispatch":
10921
11178
  return await revokeDispatch(args);
10922
11179
 
11180
+ case "holder_register":
11181
+ return await holderRegisterTool();
11182
+
11183
+ case "holder_heartbeat":
11184
+ return await holderHeartbeatTool();
11185
+
11186
+ case "holder_end":
11187
+ return await holderEndTool();
11188
+
11189
+ case "work_item_note":
11190
+ return await workItemNoteTool(args);
11191
+
11192
+ case "work_item_open":
11193
+ return await workItemOpenTool(args);
11194
+
11195
+ case "work_item_notes":
11196
+ return await workItemNotesTool(args);
11197
+
10923
11198
  case "runner_enroll":
10924
11199
  return await runnerEnroll(args);
10925
11200
 
@@ -11067,6 +11342,22 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
11067
11342
  // Start
11068
11343
  // ---------------------------------------------------------------------------
11069
11344
 
11345
+ // US-52.13: register this session as a holder before serving, waiting at most 5s so a slow
11346
+ // loopctl never delays startup; end it when Claude Code closes stdin or stops the process.
11347
+ await holderSession.start({ timeoutMs: 5000 });
11348
+
11349
+ let shuttingDown = false;
11350
+ async function endHolderAndExit() {
11351
+ if (shuttingDown) return;
11352
+ shuttingDown = true;
11353
+ const cap = new Promise((resolve) => setTimeout(resolve, 3000).unref());
11354
+ await Promise.race([holderSession.end().catch(() => {}), cap]);
11355
+ process.exit(0);
11356
+ }
11357
+
11358
+ process.stdin.on("close", endHolderAndExit);
11359
+ process.on("SIGTERM", endHolderAndExit);
11360
+
11070
11361
  const transport = new StdioServerTransport();
11071
11362
  await server.connect(transport).catch((err) => {
11072
11363
  process.stderr.write(`loopctl MCP server failed to start: ${err.message}\n`);