loopctl-mcp-server 3.20.3 → 3.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -22,6 +22,11 @@ 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 { resolveDefaultKey } from "./lib/default-key.js";
28
+ import { listWorkItemNotes, writeWorkItemNote } from "./lib/work-items.js";
29
+ import { execFile, execFileSync } from "node:child_process";
25
30
  import { degradedSearchNotice } from "./lib/search-notices.js";
26
31
  import {
27
32
  projectsPath,
@@ -181,21 +186,74 @@ function getBaseUrl() {
181
186
  }
182
187
 
183
188
  /**
184
- * Resolve which API key to use for a request.
185
- *
186
- * Priority:
187
- * 1. LOOPCTL_API_KEY (global override — if set, always used)
188
- * 2. keyOverride passed by the tool function (role-specific key)
189
- * 3. LOOPCTL_ORCH_KEY (safe default for reads)
189
+ * Resolve which API key to use for a request: the order is `resolveDefaultKey`'s
190
+ * (`lib/default-key.js`), ending with this session's agent key.
190
191
  */
191
192
  function resolveKey(keyOverride) {
192
- return (
193
- process.env.LOOPCTL_API_KEY ||
194
- keyOverride ||
195
- process.env.LOOPCTL_ORCH_KEY
196
- );
193
+ return resolveDefaultKey({ env: process.env, keyOverride, agentKey });
194
+ }
195
+
196
+ // US-52.13: this process's session holder. Every request that used to send
197
+ // LOOPCTL_AGENT_KEY sends `agentKey()` instead: the holder's own credential once the
198
+ // startup register succeeds, else LOOPCTL_AGENT_KEY unchanged (lib/holder.js says why a
199
+ // failed register never stops a session working).
200
+ function sessionWorktree() {
201
+ try {
202
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
203
+ cwd: process.cwd(),
204
+ encoding: "utf8",
205
+ stdio: ["ignore", "pipe", "ignore"],
206
+ timeout: 2000,
207
+ }).trim();
208
+ } catch {
209
+ return process.cwd();
210
+ }
197
211
  }
198
212
 
213
+ // US-52.18: on each heartbeat, the worktree's branch becomes a work item this holder holds.
214
+ const branchItemOpener = createBranchItemOpener({
215
+ apiCall: (...args) => apiCall(...args),
216
+ worktree: sessionWorktree,
217
+ git: (args) =>
218
+ new Promise((resolve) => {
219
+ execFile("git", args, { encoding: "utf8", timeout: 2000 }, (err, stdout) =>
220
+ resolve(err ? null : String(stdout).trim()),
221
+ );
222
+ }),
223
+ });
224
+
225
+ const holderSession = createHolderSession({
226
+ apiCall: (...args) => apiCall(...args),
227
+ env: process.env,
228
+ hostname: () => os.hostname(),
229
+ worktree: sessionWorktree,
230
+ randomUUID: () => crypto.randomUUID(),
231
+ afterBeat: (holder, credential) => branchItemOpener.tick(holder, credential),
232
+ });
233
+
234
+ function agentKey() {
235
+ return holderSession.agentKey();
236
+ }
237
+
238
+ // For a lib module that reads `env.LOOPCTL_AGENT_KEY` from an injected env (claim-lease.js,
239
+ // escalation.js): the process env with the agent key replaced by `agentKey()`.
240
+ function agentKeyEnv() {
241
+ return { ...process.env, LOOPCTL_AGENT_KEY: agentKey() };
242
+ }
243
+
244
+ // US-52.14: the refusal a session gets on an item another session holds, even one with the
245
+ // same agent key. Shared by the story and channel claimant tools' descriptions.
246
+ const HELD_BY_OTHER_HOLDER =
247
+ "Refused 409 held_by_other_holder when another session holds the story, even one with " +
248
+ "your agent key: the error names that session's holder_id, holder_kind and holder_host. " +
249
+ "Only that session can start, renew, request review on or release it; work something " +
250
+ "else.";
251
+
252
+ const CHANNEL_HELD_BY_OTHER_SESSION =
253
+ "A ref another session holds, even one with your agent key, is refused 409 " +
254
+ "already_claimed on claim and 404 on done and release, whatever session id is sent: the " +
255
+ "claim is bound to the session's holder from its verified key (US-52.14).";
256
+
199
257
  let clientContextHeaderCache;
200
258
  function cachedClientContextHeader() {
201
259
  if (clientContextHeaderCache === undefined) {
@@ -218,8 +276,8 @@ async function apiCall(
218
276
  ) {
219
277
  const url = `${getBaseUrl()}${path}`;
220
278
  // `exactKey` sends `keyOverride` VERBATIM instead of consulting `resolveKey`
221
- // (defined above), whose priority is LOOPCTL_API_KEY > keyOverride >
222
- // LOOPCTL_ORCH_KEY — so without it a global LOOPCTL_API_KEY displaces the key a
279
+ // (defined above, order in `lib/default-key.js`), where LOOPCTL_API_KEY comes
280
+ // before the override — so without it a global LOOPCTL_API_KEY displaces the key a
223
281
  // tool names. Two families pass it, for two different reasons:
224
282
  //
225
283
  // - USER-ROLE-PINNED tools pass LOOPCTL_USER_KEY with `exactKey: true`
@@ -539,7 +597,7 @@ async function resolveProjectRaw({ slug, repo_url, name } = {}) {
539
597
  "GET",
540
598
  `/api/v1/projects/resolve?${params}`,
541
599
  null,
542
- process.env.LOOPCTL_AGENT_KEY,
600
+ agentKey(),
543
601
  );
544
602
  }
545
603
 
@@ -564,7 +622,7 @@ async function createKbScopeRaw({ name, slug, repo_url, description, tech_stack
564
622
  if (tech_stack) body.tech_stack = tech_stack;
565
623
  // Uses the AGENT key (not ORCH): a KB scope is agent-createable on the KB tier — that is
566
624
  // 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);
625
+ return await apiCall("POST", "/api/v1/kb-scopes", body, agentKey());
568
626
  }
569
627
 
570
628
  async function createKbScope(args) {
@@ -578,7 +636,7 @@ async function archiveKbScope({ project_id }) {
578
636
  "DELETE",
579
637
  `/api/v1/kb-scopes/${project_id}`,
580
638
  null,
581
- process.env.LOOPCTL_AGENT_KEY,
639
+ agentKey(),
582
640
  );
583
641
  return toContent(result);
584
642
  }
@@ -590,7 +648,7 @@ async function restoreKbScope({ project_id }) {
590
648
  "POST",
591
649
  `/api/v1/kb-scopes/${project_id}/restore`,
592
650
  {},
593
- process.env.LOOPCTL_AGENT_KEY,
651
+ agentKey(),
594
652
  );
595
653
  return toContent(result);
596
654
  }
@@ -684,7 +742,7 @@ async function channelPostRaw({
684
742
  "POST",
685
743
  "/api/v1/channel/posts",
686
744
  payload,
687
- process.env.LOOPCTL_AGENT_KEY,
745
+ agentKey(),
688
746
  );
689
747
  }
690
748
 
@@ -723,7 +781,7 @@ async function channelRecent({ project_id, since, limit }) {
723
781
  "GET",
724
782
  `/api/v1/channel/posts?${params}`,
725
783
  null,
726
- process.env.LOOPCTL_AGENT_KEY,
784
+ agentKey(),
727
785
  );
728
786
  return toContent(result);
729
787
  }
@@ -759,7 +817,7 @@ async function channelHandoffs({ project_id, host, capabilities, only_mine }) {
759
817
  "GET",
760
818
  `/api/v1/channel/handoffs?${params}`,
761
819
  null,
762
- process.env.LOOPCTL_AGENT_KEY,
820
+ agentKey(),
763
821
  );
764
822
  return toContent(result);
765
823
  }
@@ -774,7 +832,7 @@ async function channelGet({ post_id }) {
774
832
  "GET",
775
833
  `/api/v1/channel/posts/${post_id}`,
776
834
  null,
777
- process.env.LOOPCTL_AGENT_KEY,
835
+ agentKey(),
778
836
  );
779
837
  return toContent(result);
780
838
  }
@@ -799,7 +857,7 @@ async function channelClaim({ project_id, ref, lease_seconds }) {
799
857
  "POST",
800
858
  "/api/v1/channel/claims",
801
859
  payload,
802
- process.env.LOOPCTL_AGENT_KEY,
860
+ agentKey(),
803
861
  );
804
862
  return toContent(result);
805
863
  }
@@ -825,7 +883,7 @@ async function channelClaims({ project_id, ref, limit }) {
825
883
  "GET",
826
884
  `/api/v1/channel/claims?${params}`,
827
885
  null,
828
- process.env.LOOPCTL_AGENT_KEY,
886
+ agentKey(),
829
887
  );
830
888
  return toContent(result);
831
889
  }
@@ -849,7 +907,7 @@ async function channelRelease({ project_id, ref, force }) {
849
907
  "POST",
850
908
  "/api/v1/channel/claims/release",
851
909
  payload,
852
- process.env.LOOPCTL_AGENT_KEY,
910
+ agentKey(),
853
911
  );
854
912
  return toContent(result);
855
913
  }
@@ -867,7 +925,7 @@ async function channelDone({ project_id, ref, force }) {
867
925
  "POST",
868
926
  "/api/v1/channel/claims/done",
869
927
  payload,
870
- process.env.LOOPCTL_AGENT_KEY,
928
+ agentKey(),
871
929
  );
872
930
  return toContent(result);
873
931
  }
@@ -895,7 +953,7 @@ async function channelLock({ project_id, target, ttl_seconds, note }) {
895
953
  "POST",
896
954
  "/api/v1/channel/locks",
897
955
  payload,
898
- process.env.LOOPCTL_AGENT_KEY,
956
+ agentKey(),
899
957
  );
900
958
  return toContent(result);
901
959
  }
@@ -914,7 +972,7 @@ async function channelUnlock({ project_id, target }) {
914
972
  "POST",
915
973
  "/api/v1/channel/locks/release",
916
974
  payload,
917
- process.env.LOOPCTL_AGENT_KEY,
975
+ agentKey(),
918
976
  );
919
977
  return toContent(result);
920
978
  }
@@ -931,7 +989,7 @@ async function channelLocks({ project_id, limit }) {
931
989
  "GET",
932
990
  `/api/v1/channel/locks?${params}`,
933
991
  null,
934
- process.env.LOOPCTL_AGENT_KEY,
992
+ agentKey(),
935
993
  );
936
994
  return toContent(result);
937
995
  }
@@ -947,7 +1005,7 @@ async function channelDelete({ post_id }) {
947
1005
  "DELETE",
948
1006
  `/api/v1/channel/posts/${post_id}`,
949
1007
  null,
950
- process.env.LOOPCTL_AGENT_KEY,
1008
+ agentKey(),
951
1009
  );
952
1010
  return toContent(result);
953
1011
  }
@@ -967,7 +1025,7 @@ async function channelGraduate({ post_id, title, tags, category }) {
967
1025
  "POST",
968
1026
  `/api/v1/channel/posts/${post_id}/graduate`,
969
1027
  payload,
970
- process.env.LOOPCTL_AGENT_KEY,
1028
+ agentKey(),
971
1029
  );
972
1030
  return toContent(result);
973
1031
  }
@@ -1236,7 +1294,7 @@ async function contractStory({ story_id, story_title, ac_count }) {
1236
1294
  "POST",
1237
1295
  `/api/v1/stories/${story_id}/contract`,
1238
1296
  { story_title, ac_count },
1239
- process.env.LOOPCTL_AGENT_KEY
1297
+ agentKey()
1240
1298
  );
1241
1299
  return toContent(result);
1242
1300
  }
@@ -1330,7 +1388,7 @@ async function recoverStartCap(storyId) {
1330
1388
  "POST",
1331
1389
  `/api/v1/stories/${storyId}/recover-cap`,
1332
1390
  null,
1333
- process.env.LOOPCTL_AGENT_KEY
1391
+ agentKey()
1334
1392
  );
1335
1393
  return result && result.data && result.data.cap_id;
1336
1394
  } catch {
@@ -1343,7 +1401,7 @@ async function claimStory({ story_id }) {
1343
1401
  "POST",
1344
1402
  `/api/v1/stories/${story_id}/claim`,
1345
1403
  null,
1346
- process.env.LOOPCTL_AGENT_KEY
1404
+ agentKey()
1347
1405
  );
1348
1406
  // The claim response carries the start_cap that POST /start will require.
1349
1407
  rememberCap(story_id, result && result.capability);
@@ -1359,13 +1417,13 @@ function withClaimLeaseNotice(result) {
1359
1417
  }
1360
1418
 
1361
1419
  async function renewStoryClaim(args) {
1362
- return withClaimLeaseNotice(await renewStoryClaimRequest(args, { apiCall }));
1420
+ return withClaimLeaseNotice(await renewStoryClaimRequest(args, { apiCall, env: agentKeyEnv() }));
1363
1421
  }
1364
1422
 
1365
1423
  // #803: escalation leads with a STOP line. A session that escalates and keeps working is
1366
1424
  // the failure the affordance exists to prevent, and the JSON body alone does not say so.
1367
1425
  async function escalateStory(args) {
1368
- const result = await escalateStoryRequest(args, { apiCall });
1426
+ const result = await escalateStoryRequest(args, { apiCall, env: agentKeyEnv() });
1369
1427
  const notice = escalationNotice(result);
1370
1428
  if (!notice) return toContent(result);
1371
1429
  return { content: [{ type: "text", text: notice }, ...toContent(result).content] };
@@ -1378,14 +1436,14 @@ async function startStory({ story_id, capability }) {
1378
1436
  const cap =
1379
1437
  capability ||
1380
1438
  takeCap(story_id, "start_cap") ||
1381
- (await fetchCap(story_id, "start_cap", process.env.LOOPCTL_AGENT_KEY)) ||
1439
+ (await fetchCap(story_id, "start_cap", agentKey())) ||
1382
1440
  (await recoverStartCap(story_id));
1383
1441
 
1384
1442
  const result = await apiCall(
1385
1443
  "POST",
1386
1444
  `/api/v1/stories/${story_id}/start`,
1387
1445
  cap ? { capability: cap } : null,
1388
- process.env.LOOPCTL_AGENT_KEY
1446
+ agentKey()
1389
1447
  );
1390
1448
  return toContent(result);
1391
1449
  }
@@ -1395,7 +1453,7 @@ async function requestReview({ story_id }) {
1395
1453
  "POST",
1396
1454
  `/api/v1/stories/${story_id}/request-review`,
1397
1455
  null,
1398
- process.env.LOOPCTL_AGENT_KEY
1456
+ agentKey()
1399
1457
  );
1400
1458
  return toContent(result);
1401
1459
  }
@@ -1531,7 +1589,7 @@ async function reportTokenUsage({ story_id, input_tokens, output_tokens, model_n
1531
1589
  "POST",
1532
1590
  "/api/v1/token-usage",
1533
1591
  body,
1534
- process.env.LOOPCTL_AGENT_KEY
1592
+ agentKey()
1535
1593
  );
1536
1594
  return toContent(result);
1537
1595
  }
@@ -1637,7 +1695,7 @@ async function knowledgeIndex({ project_id, story_id, category, tags, match, off
1637
1695
  if (suppressed) params.set("suppressed", suppressed);
1638
1696
  const qs = params.toString();
1639
1697
  const path = qs ? `${basePath}?${qs}` : basePath;
1640
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
1698
+ const result = await apiCall("GET", path, null, agentKey());
1641
1699
  return toContent(result);
1642
1700
  }
1643
1701
 
@@ -1646,7 +1704,7 @@ async function knowledgeIndex({ project_id, story_id, category, tags, match, off
1646
1704
  // step deletes the stale-dimension rows (loopctl reserves data-removing operations for
1647
1705
  // higher roles), so it deliberately does NOT fall back to the agent key.
1648
1706
  async function embeddingStatus() {
1649
- const result = await apiCall("GET", "/api/v1/knowledge/embeddings", null, process.env.LOOPCTL_AGENT_KEY);
1707
+ const result = await apiCall("GET", "/api/v1/knowledge/embeddings", null, agentKey());
1650
1708
  return toContent(result);
1651
1709
  }
1652
1710
 
@@ -1655,7 +1713,7 @@ async function embeddingMaterializeSystemCorpus() {
1655
1713
  "POST",
1656
1714
  "/api/v1/knowledge/embeddings/system-corpus",
1657
1715
  {},
1658
- process.env.LOOPCTL_AGENT_KEY,
1716
+ agentKey(),
1659
1717
  );
1660
1718
  return toContent(result);
1661
1719
  }
@@ -1686,7 +1744,7 @@ async function knowledgeStats({ project_id }) {
1686
1744
  const path = project_id
1687
1745
  ? `/api/v1/projects/${project_id}/knowledge/stats`
1688
1746
  : "/api/v1/knowledge/stats";
1689
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
1747
+ const result = await apiCall("GET", path, null, agentKey());
1690
1748
  return toContent(result);
1691
1749
  }
1692
1750
 
@@ -1701,7 +1759,7 @@ async function knowledgeGraph({ article_id, depth, project_id }) {
1701
1759
  "GET",
1702
1760
  `/api/v1/knowledge/graph?${params}`,
1703
1761
  null,
1704
- process.env.LOOPCTL_AGENT_KEY,
1762
+ agentKey(),
1705
1763
  );
1706
1764
  return toContent(result);
1707
1765
  }
@@ -1718,7 +1776,7 @@ async function knowledgeSuggestLinks({ article_id, limit, threshold }) {
1718
1776
  "GET",
1719
1777
  qs ? `${base}?${qs}` : base,
1720
1778
  null,
1721
- process.env.LOOPCTL_AGENT_KEY,
1779
+ agentKey(),
1722
1780
  );
1723
1781
  return toContent(result);
1724
1782
  }
@@ -1732,7 +1790,7 @@ async function knowledgeDistantPairs({ min_distance, max_distance, bridge_path,
1732
1790
  if (offset != null) params.set("offset", String(offset));
1733
1791
  const qs = params.toString();
1734
1792
  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);
1793
+ const result = await apiCall("GET", path, null, agentKey());
1736
1794
  return toContent(result);
1737
1795
  }
1738
1796
 
@@ -1742,7 +1800,7 @@ async function knowledgeNovelty({ ideas, texts, prior_tag }) {
1742
1800
  if (ideas !== undefined) body.ideas = ideas;
1743
1801
  if (texts !== undefined) body.texts = texts;
1744
1802
  if (prior_tag) body.prior_tag = prior_tag;
1745
- const result = await apiCall("POST", "/api/v1/knowledge/novelty", body, process.env.LOOPCTL_AGENT_KEY);
1803
+ const result = await apiCall("POST", "/api/v1/knowledge/novelty", body, agentKey());
1746
1804
  return toContent(result);
1747
1805
  }
1748
1806
 
@@ -1754,7 +1812,7 @@ async function knowledgeRandomWalk({ start_id, length }) {
1754
1812
  "GET",
1755
1813
  `/api/v1/knowledge/walk?${params}`,
1756
1814
  null,
1757
- process.env.LOOPCTL_AGENT_KEY,
1815
+ agentKey(),
1758
1816
  );
1759
1817
  return toContent(result);
1760
1818
  }
@@ -1780,7 +1838,7 @@ async function knowledgeCount({
1780
1838
  if (idempotency_key) params.set("idempotency_key", idempotency_key);
1781
1839
  const qs = params.toString();
1782
1840
  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);
1841
+ const result = await apiCall("GET", path, null, agentKey());
1784
1842
  return toContent(result);
1785
1843
  }
1786
1844
 
@@ -1806,7 +1864,7 @@ async function knowledgeFacets({
1806
1864
  "GET",
1807
1865
  `/api/v1/knowledge/facets?${params}`,
1808
1866
  null,
1809
- process.env.LOOPCTL_AGENT_KEY,
1867
+ agentKey(),
1810
1868
  );
1811
1869
  return toContent(result);
1812
1870
  }
@@ -1830,7 +1888,7 @@ async function knowledgeSearch({ q, project_id, story_id, category, tags, match,
1830
1888
  if (limit != null) params.set("limit", String(limit));
1831
1889
  if (offset != null) params.set("offset", String(offset));
1832
1890
 
1833
- const result = await apiCall("GET", `/api/v1/knowledge/search?${params}`, null, process.env.LOOPCTL_AGENT_KEY);
1891
+ const result = await apiCall("GET", `/api/v1/knowledge/search?${params}`, null, agentKey());
1834
1892
  // If search silently degraded to keyword-only for a missing embedding key, the
1835
1893
  // server attaches meta.remediation — surface it PROMINENTLY so the agent knows to
1836
1894
  // call set_llm_config to enable semantic ranking.
@@ -1850,7 +1908,7 @@ async function knowledgeHybridSearch({ query, project_id, category, tags, match,
1850
1908
  "POST",
1851
1909
  "/api/v1/knowledge/hybrid_search",
1852
1910
  bodyPayload,
1853
- process.env.LOOPCTL_AGENT_KEY,
1911
+ agentKey(),
1854
1912
  );
1855
1913
  // meta.provenance ("curated" | "retrieved") is the load-bearing field and rides
1856
1914
  // through toContent verbatim. Same missing-embedding-key remediation surfacing as
@@ -1872,7 +1930,7 @@ async function knowledgeProgressiveIndex({ topic, query, category, limit }) {
1872
1930
  "GET",
1873
1931
  `/api/v1/knowledge/progressive_index?${params}`,
1874
1932
  null,
1875
- process.env.LOOPCTL_AGENT_KEY,
1933
+ agentKey(),
1876
1934
  );
1877
1935
  // A topic browse is a RETRIEVAL: it runs the same ranked pool, so it can come back
1878
1936
  // short or keyword-only. Without the banner a shed index reads as "the KB has no
@@ -1890,7 +1948,7 @@ async function knowledgeHeatIndex({ category, limit, since }) {
1890
1948
  "GET",
1891
1949
  `/api/v1/knowledge/heat_index?${params}`,
1892
1950
  null,
1893
- process.env.LOOPCTL_AGENT_KEY,
1951
+ agentKey(),
1894
1952
  );
1895
1953
  // The query-free route, reached for precisely when the query-shaped ones came back
1896
1954
  // empty — so an unannounced degradation here strands the agent with no route left.
@@ -1913,7 +1971,7 @@ async function knowledgeProgressiveDrill({ article_id, body_max_bytes, body_offs
1913
1971
  "GET",
1914
1972
  qs ? `${base}?${qs}` : base,
1915
1973
  null,
1916
- process.env.LOOPCTL_AGENT_KEY,
1974
+ agentKey(),
1917
1975
  );
1918
1976
  return toContent(result);
1919
1977
  }
@@ -1956,7 +2014,7 @@ async function knowledgeList({
1956
2014
  "GET",
1957
2015
  `/api/v1/articles?${params}`,
1958
2016
  null,
1959
- process.env.LOOPCTL_AGENT_KEY,
2017
+ agentKey(),
1960
2018
  );
1961
2019
  // Enumeration, not ranking — but a short page still under-reports the set, and an
1962
2020
  // agent enumerating to decide something absent is the caller least able to tell.
@@ -1988,7 +2046,7 @@ async function knowledgeGet({
1988
2046
  params.set("body_offset", String(body_offset));
1989
2047
  const qs = params.toString();
1990
2048
  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);
2049
+ const result = await apiCall("GET", path, null, agentKey());
1992
2050
  return toContent(result);
1993
2051
  }
1994
2052
 
@@ -2012,7 +2070,7 @@ async function knowledgeContext({
2012
2070
  if (agents) params.set("agents", Array.isArray(agents) ? agents.join(",") : agents);
2013
2071
  if (conversation_id) params.set("conversation_id", conversation_id);
2014
2072
 
2015
- const result = await apiCall("GET", `/api/v1/knowledge/context?${params}`, null, process.env.LOOPCTL_AGENT_KEY);
2073
+ const result = await apiCall("GET", `/api/v1/knowledge/context?${params}`, null, agentKey());
2016
2074
  // Same as knowledge_search: surface a missing-embedding-key remediation prominently.
2017
2075
  return withRemediationNotice(result);
2018
2076
  }
@@ -2056,7 +2114,7 @@ async function knowledgeCreate({
2056
2114
  "POST",
2057
2115
  "/api/v1/articles",
2058
2116
  payload,
2059
- process.env.LOOPCTL_AGENT_KEY,
2117
+ agentKey(),
2060
2118
  );
2061
2119
  return toContent(result);
2062
2120
  }
@@ -2078,7 +2136,7 @@ async function knowledgeUpdate({ article_id, title, body, category, tags, metada
2078
2136
  "PATCH",
2079
2137
  `/api/v1/articles/${art.id}`,
2080
2138
  payload,
2081
- process.env.LOOPCTL_AGENT_KEY,
2139
+ agentKey(),
2082
2140
  );
2083
2141
  return toContent(result);
2084
2142
  }
@@ -2126,7 +2184,7 @@ async function memoryRemember({
2126
2184
  "POST",
2127
2185
  "/api/v1/memory",
2128
2186
  payload,
2129
- process.env.LOOPCTL_AGENT_KEY,
2187
+ agentKey(),
2130
2188
  );
2131
2189
  return toContent(result);
2132
2190
  }
@@ -2140,7 +2198,7 @@ async function memoryRecall({ query, limit, include_superseded }) {
2140
2198
  "POST",
2141
2199
  "/api/v1/memory/recall",
2142
2200
  payload,
2143
- process.env.LOOPCTL_AGENT_KEY,
2201
+ agentKey(),
2144
2202
  );
2145
2203
  // Surface meta (fallback/reason/total_count/underfilled) so the caller can tell
2146
2204
  // a degraded recall from a genuinely empty scope (AC-28.4.4). meta alone was not
@@ -2167,7 +2225,7 @@ async function recallContext({ query, project_id, limit, session_id }) {
2167
2225
  "POST",
2168
2226
  "/api/v1/recall",
2169
2227
  payload,
2170
- process.env.LOOPCTL_AGENT_KEY,
2228
+ agentKey(),
2171
2229
  );
2172
2230
  // Surface both per-source metas (memory fallback/underfilled + knowledge degraded)
2173
2231
  // so the caller can tell a degraded recall from a genuinely empty scope. The merged
@@ -2201,7 +2259,7 @@ async function recallReferenced({ recall_id, article_ids, project_id }) {
2201
2259
  "POST",
2202
2260
  `/api/v1/recall/${encodeURIComponent(recall_id.trim())}/referenced`,
2203
2261
  payload,
2204
- process.env.LOOPCTL_AGENT_KEY,
2262
+ agentKey(),
2205
2263
  );
2206
2264
  return toContent(result);
2207
2265
  }
@@ -2212,7 +2270,7 @@ async function memoryList({ limit, offset, include_superseded, all_subjects }) {
2212
2270
  // one deliberate cross-subject read this MCP surface can express (module
2213
2271
  // comment above), and only for a superadmin caller.
2214
2272
  const path = memoryPath({ limit, offset, include_superseded, all_subjects });
2215
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
2273
+ const result = await apiCall("GET", path, null, agentKey());
2216
2274
  // Surface meta.total_count/limit/offset (AC-28.4.4).
2217
2275
  return toContent(result);
2218
2276
  }
@@ -2230,7 +2288,7 @@ async function memoryForget({ id }) {
2230
2288
  "DELETE",
2231
2289
  `/api/v1/memory/${id}`,
2232
2290
  null,
2233
- process.env.LOOPCTL_AGENT_KEY,
2291
+ agentKey(),
2234
2292
  );
2235
2293
  return toContent(result);
2236
2294
  }
@@ -2241,7 +2299,7 @@ async function memoryPromote({ session_id }) {
2241
2299
  "POST",
2242
2300
  "/api/v1/memory/promote",
2243
2301
  payload,
2244
- process.env.LOOPCTL_AGENT_KEY,
2302
+ agentKey(),
2245
2303
  );
2246
2304
  return toContent(result);
2247
2305
  }
@@ -2259,7 +2317,7 @@ async function memoryGraduate({ memory_id, re_scope }) {
2259
2317
  "POST",
2260
2318
  "/api/v1/memory/graduate",
2261
2319
  payload,
2262
- process.env.LOOPCTL_AGENT_KEY,
2320
+ agentKey(),
2263
2321
  );
2264
2322
  return toContent(result);
2265
2323
  }
@@ -2345,7 +2403,7 @@ async function knowledgeArchive({ article_id }) {
2345
2403
  "POST",
2346
2404
  `/api/v1/articles/${art.id}/archive`,
2347
2405
  null,
2348
- process.env.LOOPCTL_AGENT_KEY
2406
+ agentKey()
2349
2407
  );
2350
2408
  return toContent(result);
2351
2409
  }
@@ -2360,7 +2418,7 @@ async function knowledgeSuppress({ article_id, reason }) {
2360
2418
  "POST",
2361
2419
  `/api/v1/articles/${art.id}/suppress`,
2362
2420
  { reason },
2363
- process.env.LOOPCTL_AGENT_KEY
2421
+ agentKey()
2364
2422
  );
2365
2423
  return toContent(result);
2366
2424
  }
@@ -2372,7 +2430,7 @@ async function knowledgeUnsuppress({ article_id }) {
2372
2430
  "POST",
2373
2431
  `/api/v1/articles/${art.id}/unsuppress`,
2374
2432
  null,
2375
- process.env.LOOPCTL_AGENT_KEY
2433
+ agentKey()
2376
2434
  );
2377
2435
  return toContent(result);
2378
2436
  }
@@ -2385,7 +2443,7 @@ async function knowledgeDelete({ article_id }) {
2385
2443
  "DELETE",
2386
2444
  `/api/v1/articles/${art.id}`,
2387
2445
  null,
2388
- process.env.LOOPCTL_AGENT_KEY
2446
+ agentKey()
2389
2447
  );
2390
2448
  return toContent(result);
2391
2449
  }
@@ -2472,7 +2530,7 @@ async function knowledgeConflicts({ limit, offset }) {
2472
2530
  const path = qs
2473
2531
  ? `/api/v1/knowledge/conflicts?${qs}`
2474
2532
  : "/api/v1/knowledge/conflicts";
2475
- const result = await apiCall("GET", path, null, process.env.LOOPCTL_AGENT_KEY);
2533
+ const result = await apiCall("GET", path, null, agentKey());
2476
2534
  return toContent(result);
2477
2535
  }
2478
2536
 
@@ -2491,7 +2549,7 @@ async function knowledgeAssertConflict({
2491
2549
  "POST",
2492
2550
  "/api/v1/knowledge/conflicts",
2493
2551
  payload,
2494
- process.env.LOOPCTL_AGENT_KEY,
2552
+ agentKey(),
2495
2553
  );
2496
2554
  return toContent(result);
2497
2555
  }
@@ -2523,7 +2581,7 @@ async function knowledgeResolveConflict({
2523
2581
  "POST",
2524
2582
  "/api/v1/knowledge/conflicts/resolve",
2525
2583
  payload,
2526
- process.env.LOOPCTL_AGENT_KEY,
2584
+ agentKey(),
2527
2585
  );
2528
2586
  return toContent(result);
2529
2587
  }
@@ -2697,7 +2755,7 @@ async function egressPosture() {
2697
2755
  "GET",
2698
2756
  "/api/v1/egress/posture",
2699
2757
  null,
2700
- process.env.LOOPCTL_AGENT_KEY,
2758
+ agentKey(),
2701
2759
  );
2702
2760
  return toContent(result);
2703
2761
  }
@@ -2714,7 +2772,7 @@ async function custodyClaim({ subject_type, subject_id } = {}) {
2714
2772
  "GET",
2715
2773
  `/api/v1/custody/claims/${encodeURIComponent(subject_type)}/${encodeURIComponent(subject_id)}`,
2716
2774
  null,
2717
- process.env.LOOPCTL_AGENT_KEY,
2775
+ agentKey(),
2718
2776
  );
2719
2777
  return toContent(result);
2720
2778
  }
@@ -2724,7 +2782,7 @@ async function custodyFailures() {
2724
2782
  "GET",
2725
2783
  "/api/v1/custody/failures",
2726
2784
  null,
2727
- process.env.LOOPCTL_AGENT_KEY,
2785
+ agentKey(),
2728
2786
  );
2729
2787
  return toContent(result);
2730
2788
  }
@@ -2788,7 +2846,7 @@ async function egressRepin({ host, project_id } = {}) {
2788
2846
  "POST",
2789
2847
  "/api/v1/egress/repin",
2790
2848
  body,
2791
- process.env.LOOPCTL_AGENT_KEY,
2849
+ agentKey(),
2792
2850
  );
2793
2851
  return toContent(result);
2794
2852
  }
@@ -3165,6 +3223,51 @@ async function revokeDispatch(args) {
3165
3223
  );
3166
3224
  }
3167
3225
 
3226
+ // US-52.13: this session's holder. The raw credential never leaves the process, so each tool
3227
+ // answers with `holderSession.status()` beside what loopctl said, never the key.
3228
+ async function holderRegisterTool() {
3229
+ const result = await holderSession.register();
3230
+ return toContent(result && result.error ? result : holderSession.status());
3231
+ }
3232
+
3233
+ async function holderHeartbeatTool() {
3234
+ const result = await holderSession.heartbeat();
3235
+ return toContent(result && result.error ? result : { ...holderSession.status(), lease: result });
3236
+ }
3237
+
3238
+ async function holderEndTool() {
3239
+ const result = await holderSession.end();
3240
+ return toContent(result && result.error ? result : holderSession.status());
3241
+ }
3242
+
3243
+ // US-52.17: a work item's notes, on the session's own key: the write is accepted from the
3244
+ // story's CURRENT holder, so it travels on the credential that holds it (lib/work-items.js).
3245
+ async function workItemNoteTool(args) {
3246
+ return toContent(
3247
+ await writeWorkItemNote(args, {
3248
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3249
+ }),
3250
+ );
3251
+ }
3252
+
3253
+ // US-52.18: open (or reopen) the work item for a branch, on the session's own key: the
3254
+ // route accepts only a holder credential (lib/branch-item.js).
3255
+ async function workItemOpenTool(args) {
3256
+ return toContent(
3257
+ await openWorkItem(args, {
3258
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3259
+ }),
3260
+ );
3261
+ }
3262
+
3263
+ async function workItemNotesTool(args) {
3264
+ return toContent(
3265
+ await listWorkItemNotes(args, {
3266
+ apiCall: (method, path, body) => apiCall(method, path, body, agentKey()),
3267
+ }),
3268
+ );
3269
+ }
3270
+
3168
3271
  // LCP-1 §9.2: register/rotate the tenant custody owner key (root of trust).
3169
3272
  // ROTATION (an owner key already exists) requires `rotation_proof`: a hex Ed25519
3170
3273
  // signature by the OUTGOING owner key over owner_rotation_preimage(tenant_id,
@@ -3490,11 +3593,11 @@ async function placeDispatch(args) {
3490
3593
  }
3491
3594
 
3492
3595
  async function storyStage(args) {
3493
- // THE AGENT KEY IS EXPLICIT, like every other agent-facing tool here: `resolveKey` reads
3494
- // LOOPCTL_API_KEY, then an override, then LOOPCTL_ORCH_KEY — never LOOPCTL_AGENT_KEY. A
3495
- // session refused `stale_stage` is running on an agent key, and this read is what tells it
3496
- // where the row actually is, so on an agent-key-only config it has to work.
3497
- const key = process.env.LOOPCTL_AGENT_KEY;
3596
+ // THE AGENT KEY IS EXPLICIT, like every other agent-facing tool here: as the override it
3597
+ // comes before LOOPCTL_ORCH_KEY in `resolveKey`'s order (`lib/default-key.js`). A session
3598
+ // refused `stale_stage` is running on an agent key, and this read is what tells it where the
3599
+ // row actually is.
3600
+ const key = agentKey();
3498
3601
 
3499
3602
  return toContent(
3500
3603
  await storyStageRequest(args, {
@@ -3504,13 +3607,11 @@ async function storyStage(args) {
3504
3607
  }
3505
3608
 
3506
3609
  // US-47.7: a READ, `role: :agent` with the hierarchy, so any role's key clears the gate and
3507
- // nothing is pinned. LOOPCTL_AGENT_KEY is passed as this tool's own key for the reason
3508
- // storyStage gives above — `resolveKey` never reads it by name, and a session on an
3509
- // agent-key-only config is exactly the one asking which change its story is bound to. It is an
3510
- // OVERRIDE, not `exactKey`, so `resolveKey`'s order holds: LOOPCTL_API_KEY when set, else
3511
- // LOOPCTL_AGENT_KEY, else LOOPCTL_ORCH_KEY.
3610
+ // nothing is pinned. The agent key is passed as this tool's own key for the reason storyStage
3611
+ // gives above. It is an OVERRIDE, not `exactKey`, so `resolveKey`'s order holds
3612
+ // (`lib/default-key.js`): LOOPCTL_API_KEY when set, else the agent key.
3512
3613
  async function changeBindingGet(args) {
3513
- const key = process.env.LOOPCTL_AGENT_KEY;
3614
+ const key = agentKey();
3514
3615
 
3515
3616
  return toContent(
3516
3617
  await changeBindingGetRequest(args, {
@@ -3522,7 +3623,7 @@ async function changeBindingGet(args) {
3522
3623
  // US-48.12: a READ of the run-outcome ledger, `role: :agent` with the hierarchy — keyed as
3523
3624
  // changeBindingGet is, LOOPCTL_AGENT_KEY as an OVERRIDE so `resolveKey`'s order holds.
3524
3625
  async function agentOutcomesRead(args) {
3525
- const key = process.env.LOOPCTL_AGENT_KEY;
3626
+ const key = agentKey();
3526
3627
 
3527
3628
  return toContent(
3528
3629
  await agentOutcomes(args, {
@@ -3534,7 +3635,7 @@ async function agentOutcomesRead(args) {
3534
3635
  // US-50.6: a READ of the chg ledger summary, `role: :agent` with the hierarchy — keyed as
3535
3636
  // agentOutcomesRead is, LOOPCTL_AGENT_KEY as an OVERRIDE so `resolveKey`'s order holds.
3536
3637
  async function chgLedgerSummaryRead(args) {
3537
- const key = process.env.LOOPCTL_AGENT_KEY;
3638
+ const key = agentKey();
3538
3639
 
3539
3640
  return toContent(
3540
3641
  await chgLedgerSummary(args, {
@@ -3546,7 +3647,7 @@ async function chgLedgerSummaryRead(args) {
3546
3647
  // US-51.6: the findings list is a READ keyed as chgLedgerSummaryRead is; clearing one is a
3547
3648
  // person's act and takes the EXACT user key through runnerDeps().
3548
3649
  async function chgFindingsRead(args) {
3549
- const key = process.env.LOOPCTL_AGENT_KEY;
3650
+ const key = agentKey();
3550
3651
 
3551
3652
  return toContent(
3552
3653
  await chgFindings(args, {
@@ -3570,7 +3671,7 @@ async function resolveEscalation(args) {
3570
3671
  // US-48.11: the escalation inbox is a READ, `role: :agent` with the hierarchy, so it takes
3571
3672
  // LOOPCTL_AGENT_KEY as an override for changeBindingGet's reason above, never `exactKey`.
3572
3673
  async function escalationListRead(args) {
3573
- const key = process.env.LOOPCTL_AGENT_KEY;
3674
+ const key = agentKey();
3574
3675
 
3575
3676
  return toContent(
3576
3677
  withRemedies(
@@ -3741,7 +3842,7 @@ async function corpusCreate(args) {
3741
3842
  "POST",
3742
3843
  corporaPath(),
3743
3844
  buildCorpusCreateBody(args),
3744
- process.env.LOOPCTL_AGENT_KEY,
3845
+ agentKey(),
3745
3846
  );
3746
3847
  return toContent(result);
3747
3848
  }
@@ -3751,7 +3852,7 @@ async function corpusList(args = {}) {
3751
3852
  "GET",
3752
3853
  corporaPath(args),
3753
3854
  null,
3754
- process.env.LOOPCTL_AGENT_KEY,
3855
+ agentKey(),
3755
3856
  );
3756
3857
  return toContent(result);
3757
3858
  }
@@ -3763,7 +3864,7 @@ async function corpusIndex({ corpus_id, chunks, source_complete }) {
3763
3864
  "POST",
3764
3865
  corpusIndexPath(corpus_id),
3765
3866
  buildCorpusIndexBody({ chunks, source_complete }),
3766
- process.env.LOOPCTL_AGENT_KEY,
3867
+ agentKey(),
3767
3868
  );
3768
3869
  return toContent(result);
3769
3870
  }
@@ -3773,7 +3874,7 @@ async function corpusSearch({ corpus_id, query, query_vector, lanes, limit }) {
3773
3874
  "POST",
3774
3875
  corpusSearchPath(corpus_id),
3775
3876
  buildCorpusSearchBody({ query, query_vector, lanes, limit }),
3776
- process.env.LOOPCTL_AGENT_KEY,
3877
+ agentKey(),
3777
3878
  );
3778
3879
  // Pointers + snippets only — the caller's next step is to open the file at
3779
3880
  // source_ref/locator. Nothing here is auto-injected into a recall pack, so a
@@ -3787,7 +3888,7 @@ async function corpusStatus({ corpus_id, limit, offset }) {
3787
3888
  "GET",
3788
3889
  corpusStatusPath(corpus_id, { limit, offset }),
3789
3890
  null,
3790
- process.env.LOOPCTL_AGENT_KEY,
3891
+ agentKey(),
3791
3892
  );
3792
3893
  return toContent(result);
3793
3894
  }
@@ -4226,7 +4327,8 @@ const TOOLS = [
4226
4327
  {
4227
4328
  name: "channel_claim",
4228
4329
  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.",
4330
+ "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. " +
4331
+ CHANNEL_HELD_BY_OTHER_SESSION,
4230
4332
  inputSchema: {
4231
4333
  type: "object",
4232
4334
  properties: {
@@ -4251,7 +4353,8 @@ const TOOLS = [
4251
4353
  {
4252
4354
  name: "channel_release",
4253
4355
  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.",
4356
+ "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. " +
4357
+ CHANNEL_HELD_BY_OTHER_SESSION,
4255
4358
  inputSchema: {
4256
4359
  type: "object",
4257
4360
  properties: {
@@ -4269,7 +4372,8 @@ const TOOLS = [
4269
4372
  {
4270
4373
  name: "channel_done",
4271
4374
  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.",
4375
+ "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. " +
4376
+ CHANNEL_HELD_BY_OTHER_SESSION,
4273
4377
  inputSchema: {
4274
4378
  type: "object",
4275
4379
  properties: {
@@ -4878,7 +4982,11 @@ const TOOLS = [
4878
4982
  },
4879
4983
  {
4880
4984
  name: "get_story",
4881
- description: "Get full details for a single story by ID.",
4985
+ description:
4986
+ "Get full details for a single story by ID. The claim is on it: assigned_holder_id, " +
4987
+ "claim_epoch and claimed_until, and assigned_holder (id, kind, host, session_id, " +
4988
+ "lease_until, ended_at, ended_reason) naming the SESSION that holds it, so a claim of " +
4989
+ "another session of your own agent reads as someone else's.",
4882
4990
  inputSchema: {
4883
4991
  type: "object",
4884
4992
  properties: {
@@ -4928,14 +5036,19 @@ const TOOLS = [
4928
5036
  "Transitions contracted -> assigned. Uses the AGENT key. On a loopctl with claim leases " +
4929
5037
  "the result leads with the claim's claim_epoch and claimed_until: keep the epoch, and " +
4930
5038
  "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 " +
5039
+ "is released back to pending under you. Claimed with this session's holder credential, " +
5040
+ "the claim instead takes the holder's lease and the heartbeat keeps it alive; refused " +
5041
+ "409 holder_lease_expired once that lease has run out. Refused 409 story_held when the story's " +
4932
5042
  "delivery stage is escalated, done or failed: it is not yours to claim even when it " +
4933
5043
  "reads pending or contracted — move on. An escalated story is claimable again only " +
4934
5044
  "after resolve_escalation sends it to queued; a done or failed one never is. Refused " +
4935
5045
  "409 dependencies_not_met when a story it depends on, or one in an epic its epic " +
4936
5046
  "depends on, is not verified: list_blocked_stories names them. Refused 409 " +
4937
5047
  "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.",
5048
+ "chg_root_dispatch_id: chg-server's keys may only review. " +
5049
+ HELD_BY_OTHER_HOLDER +
5050
+ " Claiming a story THIS session already holds returns the claim unchanged, so a " +
5051
+ "retry after a lost response is safe.",
4939
5052
  inputSchema: {
4940
5053
  type: "object",
4941
5054
  properties: {
@@ -4966,7 +5079,8 @@ const TOOLS = [
4966
5079
  "expired and was reclaimed, released, or claimed again, so stop working it); 409 " +
4967
5080
  "not_claimant (your key's agent is not the story's assigned agent); " +
4968
5081
  "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).",
5082
+ "and the claim ends there, so stop working it). " +
5083
+ HELD_BY_OTHER_HOLDER,
4970
5084
  inputSchema: {
4971
5085
  type: "object",
4972
5086
  properties: {
@@ -5039,7 +5153,8 @@ const TOOLS = [
5039
5153
  "Agent starts work on a claimed story. Transitions assigned -> implementing. Uses the AGENT key. " +
5040
5154
  "The L1 capability (start_cap) is handled for you: it is taken from the claim_story response, " +
5041
5155
  "and re-minted via recover-cap if this process lost it (e.g. after a session crash). " +
5042
- "Pass `capability` only to override that.",
5156
+ "Pass `capability` only to override that. " +
5157
+ HELD_BY_OTHER_HOLDER,
5043
5158
  inputSchema: {
5044
5159
  type: "object",
5045
5160
  properties: {
@@ -5062,7 +5177,8 @@ const TOOLS = [
5062
5177
  name: "request_review",
5063
5178
  description:
5064
5179
  "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.",
5180
+ "Does NOT change the story status — fires a webhook event for the reviewer. Uses the AGENT key. " +
5181
+ HELD_BY_OTHER_HOLDER,
5066
5182
  inputSchema: {
5067
5183
  type: "object",
5068
5184
  properties: {
@@ -8573,6 +8689,132 @@ const TOOLS = [
8573
8689
  },
8574
8690
  },
8575
8691
 
8692
+ {
8693
+ name: "holder_register",
8694
+ description:
8695
+ "REGISTER THIS SESSION AS A HOLDER (POST /api/v1/holders, US-52.13). The MCP server " +
8696
+ "already does this at startup and heartbeats on a timer; call it only to re-register " +
8697
+ "after holder_end or when holder_heartbeat reports no holder. Sends LOOPCTL_AGENT_KEY " +
8698
+ "(exactly, never another variable) with kind interactive, this session's id, the host " +
8699
+ "and the git top level. loopctl answers with the SAME holder while it is live and a new " +
8700
+ "credential, which this process keeps in memory and sends on every agent-key request " +
8701
+ "from then on; the credential is never returned to you. REFUSES: 403 " +
8702
+ "custody_tier_required on an agent-rooted tenant, 403 holder_mint_forbidden for a " +
8703
+ "dispatch-minted key, 422 agent_required for a key naming no agent. On any refusal the " +
8704
+ "session keeps using LOOPCTL_AGENT_KEY.",
8705
+ inputSchema: { type: "object", properties: {} },
8706
+ },
8707
+
8708
+ {
8709
+ name: "holder_heartbeat",
8710
+ description:
8711
+ "RENEW THIS SESSION'S HOLDER LEASE NOW (POST /api/v1/holders/:id/heartbeat), by the " +
8712
+ "holder's own credential. The server does this every heartbeat_seconds on its own. " +
8713
+ "It also moves every uncapped claim the holder holds to the new lease. A 401, 404 or " +
8714
+ "409 (credential expired, holder ended) makes it register again; 409 " +
8715
+ "holder_lease_expired means the lease ran out first, so loopctl ended the holder and " +
8716
+ "released its claims: the session registers as a NEW holder and must re-claim.",
8717
+ inputSchema: { type: "object", properties: {} },
8718
+ },
8719
+
8720
+ {
8721
+ name: "holder_end",
8722
+ description:
8723
+ "END THIS SESSION'S HOLDER (POST /api/v1/holders/:id/end): sets ended_at and revokes " +
8724
+ "its credential; this process falls back to LOOPCTL_AGENT_KEY. The server does this " +
8725
+ "itself when stdin closes or on SIGTERM. A repeated end writes nothing.",
8726
+ inputSchema: { type: "object", properties: {} },
8727
+ },
8728
+
8729
+ {
8730
+ name: "work_item_note",
8731
+ description:
8732
+ "WRITE A NOTE ON A WORK ITEM (POST /api/v1/stories/:id/notes): your plan, progress, a " +
8733
+ "decision or an open question, appended under `section` and never edited, so the next " +
8734
+ "session resumes from the item instead of from your transcript. Records a note_written " +
8735
+ "event on the story's log in the same transaction. Uses this session's own key (its " +
8736
+ "holder credential). Only the story's CURRENT holder writes one: " +
8737
+ "409 held_by_other_holder when another session holds it (the error names that " +
8738
+ "session's holder_id, holder_kind and holder_host), 409 not_holder when nobody holds " +
8739
+ "it, 404 for a story that is not this tenant's. 422 for an unknown section, an empty " +
8740
+ "body, a body over 16384 bytes, or a body that looks like a credential (every holder " +
8741
+ "reads notes). Pass `idempotency_key` to make a retry after a lost response return the " +
8742
+ "first note and write nothing; the key is the WRITER's, so a key another writer's note " +
8743
+ "on this story already carries is 409 idempotency_key_reused and writes nothing.",
8744
+ inputSchema: {
8745
+ type: "object",
8746
+ properties: {
8747
+ story_id: { type: "string", description: "The UUID of the story." },
8748
+ section: {
8749
+ type: "string",
8750
+ enum: ["plan", "progress", "decision", "question"],
8751
+ description: "Which section the note is filed under.",
8752
+ },
8753
+ body: { type: "string", description: "The note's text, 1 to 16384 bytes." },
8754
+ idempotency_key: {
8755
+ type: "string",
8756
+ description: "Optional: a key unique to this note, so a retry writes it once.",
8757
+ },
8758
+ },
8759
+ required: ["story_id", "section", "body"],
8760
+ },
8761
+ },
8762
+
8763
+ {
8764
+ name: "work_item_open",
8765
+ description:
8766
+ "OPEN THE WORK ITEM FOR A BRANCH (POST /api/v1/work_items): your interactive work on " +
8767
+ "`branch` becomes one story in the project `repo_url` resolves to, already " +
8768
+ "implementing and held by this session, with a stage row naming the branch. The MCP " +
8769
+ "server already does this on each heartbeat for the worktree's non-default branch; " +
8770
+ "call it to name a title or an epic. The epic is `epic_id`, else the target epic of " +
8771
+ "the project's live intake source. Reopening your own item returns it (200, outcome " +
8772
+ "existing), an unheld item on the branch is claimed back for you (200, claimed), and " +
8773
+ "your one held item with no branch takes this one (200, branch_recorded). Needs this " +
8774
+ "session's holder credential: 403 holder_credential_required for any other key. 409 " +
8775
+ "branch_held (another session's open item has the branch; names story_id and " +
8776
+ "holder_id), 409 holder_ended, 409 story_held (the item is escalated). 404 " +
8777
+ "project_not_found (no project of your tenant has the repo), 404 epic_not_found. 422 " +
8778
+ "no_target_epic (pass epic_id), 422 invalid_branch (empty, whitespace, HEAD, over 255 " +
8779
+ "bytes). The item reaches verified only through report, review and verify like any " +
8780
+ "story; you cannot report it yourself.",
8781
+ inputSchema: {
8782
+ type: "object",
8783
+ properties: {
8784
+ repo_url: { type: "string", description: "The repo's remote URL (git remote get-url origin)." },
8785
+ branch: { type: "string", description: "The branch the work is on." },
8786
+ title: { type: "string", description: "Optional: the item's title (default: the branch)." },
8787
+ epic_id: { type: "string", description: "Optional: the UUID of the epic to file it under." },
8788
+ },
8789
+ required: ["repo_url", "branch"],
8790
+ },
8791
+ },
8792
+
8793
+ {
8794
+ name: "work_item_notes",
8795
+ description:
8796
+ "READ A WORK ITEM'S NOTES (GET /api/v1/stories/:id/notes), oldest first. The FIRST page " +
8797
+ "carries `current`: the newest note of each section, which is where the item stands. " +
8798
+ "Optional `section` filters to one section; `limit` defaults to 50, at most 200; pass a " +
8799
+ "page's `next_cursor` back as `after` for the next one. Any key of the tenant reads " +
8800
+ "them. 404 for a story that is not this tenant's; 422 for an unknown section or a " +
8801
+ "cursor this endpoint did not return.",
8802
+ inputSchema: {
8803
+ type: "object",
8804
+ properties: {
8805
+ story_id: { type: "string", description: "The UUID of the story." },
8806
+ section: {
8807
+ type: "string",
8808
+ enum: ["plan", "progress", "decision", "question"],
8809
+ description: "Optional: only this section's notes.",
8810
+ },
8811
+ limit: { type: "integer", description: "Optional page size (default 50, max 200)." },
8812
+ after: { type: "string", description: "Optional: the previous page's next_cursor." },
8813
+ },
8814
+ required: ["story_id"],
8815
+ },
8816
+ },
8817
+
8576
8818
  {
8577
8819
  name: "revoke_dispatch",
8578
8820
  description:
@@ -9423,11 +9665,17 @@ const TOOLS = [
9423
9665
  "server-side condition a re-run meets again until an operator acts; " +
9424
9666
  "`force_unclaim_failed` (the " +
9425
9667
  "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.",
9668
+ "write itself was rejected. Optional `reason`: recorded on the story's event log as " +
9669
+ "`force-unclaimed: <reason>` (at most 2000 characters, longer is cut); without it the " +
9670
+ "log says `force-unclaimed: operator`.",
9427
9671
  inputSchema: {
9428
9672
  type: "object",
9429
9673
  properties: {
9430
9674
  story_id: { type: "string", description: "The story UUID to free." },
9675
+ reason: {
9676
+ type: "string",
9677
+ description: "Why you are taking it back, for the story's event log.",
9678
+ },
9431
9679
  },
9432
9680
  required: ["story_id"],
9433
9681
  },
@@ -10432,7 +10680,7 @@ const TOOLS = [
10432
10680
  // that isn't `cr_`-prefixed or that collides with a built-in tool name.
10433
10681
  const generatedToolsRuntime = createGeneratedToolsRuntime({
10434
10682
  apiCall,
10435
- agentKey: () => process.env.LOOPCTL_AGENT_KEY,
10683
+ agentKey: () => agentKey(),
10436
10684
  staticToolNames: new Set(TOOLS.map((t) => t.name)),
10437
10685
  toContent,
10438
10686
  });
@@ -10920,6 +11168,24 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
10920
11168
  case "revoke_dispatch":
10921
11169
  return await revokeDispatch(args);
10922
11170
 
11171
+ case "holder_register":
11172
+ return await holderRegisterTool();
11173
+
11174
+ case "holder_heartbeat":
11175
+ return await holderHeartbeatTool();
11176
+
11177
+ case "holder_end":
11178
+ return await holderEndTool();
11179
+
11180
+ case "work_item_note":
11181
+ return await workItemNoteTool(args);
11182
+
11183
+ case "work_item_open":
11184
+ return await workItemOpenTool(args);
11185
+
11186
+ case "work_item_notes":
11187
+ return await workItemNotesTool(args);
11188
+
10923
11189
  case "runner_enroll":
10924
11190
  return await runnerEnroll(args);
10925
11191
 
@@ -11067,6 +11333,22 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
11067
11333
  // Start
11068
11334
  // ---------------------------------------------------------------------------
11069
11335
 
11336
+ // US-52.13: register this session as a holder before serving, waiting at most 5s so a slow
11337
+ // loopctl never delays startup; end it when Claude Code closes stdin or stops the process.
11338
+ await holderSession.start({ timeoutMs: 5000 });
11339
+
11340
+ let shuttingDown = false;
11341
+ async function endHolderAndExit() {
11342
+ if (shuttingDown) return;
11343
+ shuttingDown = true;
11344
+ const cap = new Promise((resolve) => setTimeout(resolve, 3000).unref());
11345
+ await Promise.race([holderSession.end().catch(() => {}), cap]);
11346
+ process.exit(0);
11347
+ }
11348
+
11349
+ process.stdin.on("close", endHolderAndExit);
11350
+ process.on("SIGTERM", endHolderAndExit);
11351
+
11070
11352
  const transport = new StdioServerTransport();
11071
11353
  await server.connect(transport).catch((err) => {
11072
11354
  process.stderr.write(`loopctl MCP server failed to start: ${err.message}\n`);