@sema-agent/core 7.57.0 → 7.58.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.
Files changed (198) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/dist/agents/subagent-steps.js +2 -4
  3. package/dist/brain/route-adjudicator.js +2 -1
  4. package/dist/core/a2a.d.ts +2 -1
  5. package/dist/core/a2a.js +23 -10
  6. package/dist/core/allow-entry.d.ts +2 -1
  7. package/dist/core/allow-entry.js +2 -1
  8. package/dist/core/ask-origin.d.ts +21 -2
  9. package/dist/core/ask-origin.js +5 -1
  10. package/dist/core/auto-compaction.d.ts +4 -0
  11. package/dist/core/auto-compaction.js +1 -1
  12. package/dist/core/auto-mode-directive.d.ts +29 -5
  13. package/dist/core/auto-mode-directive.js +38 -8
  14. package/dist/core/checkpoint-requirements.d.ts +7 -1
  15. package/dist/core/checkpoint-requirements.js +2 -0
  16. package/dist/core/checkpoint-store.d.ts +27 -11
  17. package/dist/core/checkpoint-store.js +13 -3
  18. package/dist/core/engine-notice.d.ts +1 -1
  19. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  20. package/dist/core/fs-write-gate-policy.js +7 -3
  21. package/dist/core/gate-fold.js +6 -3
  22. package/dist/core/gate-lanes.js +11 -2
  23. package/dist/core/git-worktree-env.d.ts +53 -11
  24. package/dist/core/git-worktree-env.js +96 -12
  25. package/dist/core/hooks.d.ts +4 -1
  26. package/dist/core/hooks.js +12 -5
  27. package/dist/core/human-input-projection.d.ts +1 -0
  28. package/dist/core/human-input-projection.js +3 -0
  29. package/dist/core/locked-config.d.ts +15 -1
  30. package/dist/core/locked-config.js +38 -2
  31. package/dist/core/mcp-call-meta.d.ts +66 -0
  32. package/dist/core/mcp-call-meta.js +103 -0
  33. package/dist/core/mcp-connection-pool.d.ts +3 -1
  34. package/dist/core/mcp-connection-pool.js +3 -1
  35. package/dist/core/mcp-failure.d.ts +7 -1
  36. package/dist/core/mcp-failure.js +10 -0
  37. package/dist/core/mcp-probe.d.ts +4 -0
  38. package/dist/core/mcp-probe.js +1 -1
  39. package/dist/core/mcp-server-link.d.ts +5 -2
  40. package/dist/core/mcp-server-spec.d.ts +46 -18
  41. package/dist/core/mcp-server-spec.js +1 -18
  42. package/dist/core/mcp.d.ts +6 -14
  43. package/dist/core/mcp.js +77 -37
  44. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  45. package/dist/core/memory-engine/scope-contract.js +80 -11
  46. package/dist/core/mode-policy.d.ts +8 -5
  47. package/dist/core/mode-policy.js +5 -4
  48. package/dist/core/mods/host.js +1 -1
  49. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  50. package/dist/core/mods/kernel/dispatch.js +10 -8
  51. package/dist/core/mods/kernel/events.d.ts +5 -1
  52. package/dist/core/mods/kernel/events.js +1 -1
  53. package/dist/core/mods/kernel/registration.d.ts +5 -1
  54. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  55. package/dist/core/mods/kernel/site-rules.js +10 -0
  56. package/dist/core/mods/package.d.ts +23 -0
  57. package/dist/core/mods/package.js +118 -0
  58. package/dist/core/mods/stations.d.ts +2 -2
  59. package/dist/core/mods/stations.js +1 -1
  60. package/dist/core/mods/tool-call.d.ts +5 -1
  61. package/dist/core/mods/tool-call.js +12 -3
  62. package/dist/core/path-guard-rows.d.ts +20 -0
  63. package/dist/core/path-guard-rows.js +11 -0
  64. package/dist/core/peer-seat.d.ts +186 -0
  65. package/dist/core/peer-seat.js +307 -0
  66. package/dist/core/present-plan-tool.d.ts +10 -1
  67. package/dist/core/present-plan-tool.js +46 -2
  68. package/dist/core/protocol-http-auth.d.ts +40 -29
  69. package/dist/core/protocol-http-auth.js +30 -32
  70. package/dist/core/redaction-marks.d.ts +16 -0
  71. package/dist/core/redaction-marks.js +16 -0
  72. package/dist/core/redaction-passes.js +8 -9
  73. package/dist/core/retention.d.ts +41 -15
  74. package/dist/core/retention.js +59 -12
  75. package/dist/core/rewrite-rejudge.d.ts +37 -0
  76. package/dist/core/rewrite-rejudge.js +40 -0
  77. package/dist/core/run-origin.d.ts +40 -0
  78. package/dist/core/run-origin.js +37 -0
  79. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  80. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  81. package/dist/core/runner/compaction-restate.d.ts +15 -6
  82. package/dist/core/runner/compaction-restate.js +28 -2
  83. package/dist/core/runner/contracts.d.ts +13 -5
  84. package/dist/core/runner/gate-exit.d.ts +18 -4
  85. package/dist/core/runner/gate-exit.js +5 -1
  86. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  87. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  88. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  89. package/dist/core/runner/prepare-config-doors.js +12 -10
  90. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  91. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  92. package/dist/core/runner/prepare-gate-stations.js +1 -1
  93. package/dist/core/runner/prepare-hands-readface.d.ts +7 -3
  94. package/dist/core/runner/prepare-hands-readface.js +4 -1
  95. package/dist/core/runner/prepare-memory.d.ts +3 -0
  96. package/dist/core/runner/prepare-memory.js +19 -23
  97. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  98. package/dist/core/runner/prepare-policy-chain.js +2 -2
  99. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  100. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  101. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  102. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  103. package/dist/core/runner/prepare-task.js +25 -12
  104. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  105. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  106. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  107. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  108. package/dist/core/runner/resume-admission.js +1 -1
  109. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  110. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  111. package/dist/core/runner/run-harness-handlers.js +1 -8
  112. package/dist/core/runner/run-identity-wiring.js +1 -0
  113. package/dist/core/runner/run-leg.js +5 -1
  114. package/dist/core/runner/run-notification-lane.js +3 -0
  115. package/dist/core/runner/terminal-account.js +3 -3
  116. package/dist/core/runner/tool-end-body.js +1 -0
  117. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  118. package/dist/core/runner/tool-occurrence.js +2 -1
  119. package/dist/core/runner/write-protection-station.d.ts +8 -2
  120. package/dist/core/runner/write-protection-station.js +2 -0
  121. package/dist/core/runner-deps.d.ts +2 -2
  122. package/dist/core/sensitive-path-policy.js +6 -7
  123. package/dist/core/session-log-transfer.d.ts +24 -0
  124. package/dist/core/session-log-transfer.js +166 -0
  125. package/dist/core/session-store.d.ts +84 -19
  126. package/dist/core/session-store.js +162 -24
  127. package/dist/core/session.d.ts +92 -1
  128. package/dist/core/shell-read-silence.js +1 -0
  129. package/dist/core/steer-replay.d.ts +4 -2
  130. package/dist/core/steer-replay.js +2 -1
  131. package/dist/core/store-contracts/checkpoint-store-contract.js +17 -0
  132. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  133. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  134. package/dist/core/store-contracts/session-store-contract.js +236 -2
  135. package/dist/core/task-event.d.ts +68 -8
  136. package/dist/core/task-registry-shared.d.ts +2 -1
  137. package/dist/core/task-spec.d.ts +37 -0
  138. package/dist/core/task-stream.d.ts +2 -1
  139. package/dist/core/terminal-cause.d.ts +1 -1
  140. package/dist/core/tool-catalog-entries.js +1 -0
  141. package/dist/core/tool-result-store.d.ts +17 -10
  142. package/dist/core/tool-result-store.js +3 -1
  143. package/dist/core/types.d.ts +1 -1
  144. package/dist/core/untrusted-egress.d.ts +0 -2
  145. package/dist/core/untrusted-egress.js +10 -14
  146. package/dist/core/wiring-manifest.d.ts +12 -3
  147. package/dist/core/wiring-manifest.js +4 -3
  148. package/dist/core/workspace-snapshot.d.ts +44 -0
  149. package/dist/core/workspace-snapshot.js +34 -0
  150. package/dist/core/write-protect.d.ts +43 -3
  151. package/dist/core/write-protect.js +43 -16
  152. package/dist/engine/execution-env/node-execution-env.js +15 -11
  153. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  154. package/dist/engine/harness/agent-harness.d.ts +5 -0
  155. package/dist/engine/harness/agent-harness.js +2 -0
  156. package/dist/engine/harness/types.d.ts +48 -7
  157. package/dist/engine/harness/types.js +5 -1
  158. package/dist/engine/llm/types.d.ts +12 -3
  159. package/dist/engine/llm/types.js +1 -1
  160. package/dist/engine/session/import-validate.js +3 -0
  161. package/dist/engine/session/memory-repo.d.ts +17 -9
  162. package/dist/engine/session/memory-repo.js +44 -34
  163. package/dist/engine/session/repo-utils.d.ts +22 -4
  164. package/dist/engine/session/repo-utils.js +49 -1
  165. package/dist/engine/session/storage-base.d.ts +10 -1
  166. package/dist/engine/session/storage-base.js +7 -1
  167. package/dist/index.d.ts +13 -6
  168. package/dist/index.js +10 -4
  169. package/dist/internal/harness-types.d.ts +1 -1
  170. package/dist/internal/harness.d.ts +2 -2
  171. package/dist/internal/harness.js +2 -2
  172. package/dist/stores/file/index.d.ts +4 -1
  173. package/dist/stores/file/index.js +4 -1
  174. package/dist/stores/file/session-store.d.ts +15 -8
  175. package/dist/stores/file/session-store.js +28 -13
  176. package/dist/tools/fs/fs-write.d.ts +6 -3
  177. package/dist/tools/fs/fs-write.js +8 -7
  178. package/dist/tools/fs/index.d.ts +3 -0
  179. package/dist/tools/fs/index.js +1 -1
  180. package/dist/tools/fs/safety.js +40 -8
  181. package/dist/tools/fs/search.js +6 -24
  182. package/dist/tools/fs/shell-read-check.d.ts +8 -1
  183. package/dist/tools/fs/shell-read-check.js +59 -15
  184. package/dist/tools/fs/shell-read-establish.js +2 -1
  185. package/dist/tools/fs/shell-read-identity.js +1 -1
  186. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  187. package/dist/tools/worktree.d.ts +42 -15
  188. package/dist/tools/worktree.js +60 -32
  189. package/package.json +4 -2
  190. package/test/export-surface.snapshot.json +63 -1
  191. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  192. package/wire-changes/core@7.58.0.json +2188 -0
  193. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  194. package/wire-changes/primitives@7.58.0.json +29 -0
  195. package/dist/primitives/credential-ref.d.ts +0 -89
  196. package/dist/primitives/credential-ref.js +0 -125
  197. package/dist/primitives/index.d.ts +0 -2
  198. package/dist/primitives/index.js +0 -1
@@ -444,7 +444,7 @@ function within(rootCanonical, p) {
444
444
  }
445
445
  export async function resolveKey(env, rootCanonical, path, signal, baseCwd, additionalRoots, exactFileReadExemption, readDeny, containmentFace) {
446
446
  const views = await readPath(env, path, baseCwd ?? rootCanonical, { root: rootCanonical, ...(baseCwd !== undefined ? { cwd: baseCwd } : {}) }, { intent: "resolve", views: readDeny !== undefined ? "chain" : "canonical" }, signal);
447
- const canon = views.canonical ?? (await canonicalizeTarget(env, path, signal, pathFamilyOf({ root: rootCanonical }), baseCwd));
447
+ const canon = views.canonical ?? { ok: false, message: `cannot resolve path "${clipSpelling(path)}": ${views.lexical?.kind === "unreadable" ? views.lexical.reason : "the environment was not asked where it lands"}; refused.` };
448
448
  if (!canon.ok)
449
449
  return { ok: false, violation: { code: "invalid", message: canon.message } };
450
450
  const key = canon.key;
@@ -545,6 +545,10 @@ async function probeRealTarget(env, path, target, family, signal) {
545
545
  if (!newPath.ok) {
546
546
  return { ok: false, message: newPath.message, unresolvedSymlink: true };
547
547
  }
548
+ if ("reprobe" in newPath) {
549
+ abs = newPath.reprobe;
550
+ continue;
551
+ }
548
552
  return { ok: true, key: newPath.key };
549
553
  }
550
554
  const canon = await env.canonicalPath(abs, signal);
@@ -559,6 +563,10 @@ async function probeRealTarget(env, path, target, family, signal) {
559
563
  if (!viaAncestors.ok) {
560
564
  return { ok: false, message: viaAncestors.message, unresolvedSymlink: true };
561
565
  }
566
+ if ("reprobe" in viaAncestors) {
567
+ abs = viaAncestors.reprobe;
568
+ continue;
569
+ }
562
570
  return { ok: true, key: viaAncestors.key };
563
571
  }
564
572
  if (!env.readLink) {
@@ -584,7 +592,7 @@ async function probeRealTarget(env, path, target, family, signal) {
584
592
  }
585
593
  abs = reabs.value;
586
594
  }
587
- return { ok: false, message: `symlink chain for "${path}" exceeded the hop cap; target unresolved`, unresolvedSymlink: true };
595
+ return { ok: false, message: `resolving "${path}" exceeded the hop cap (links followed, or a \`..\` back into an existing directory re-probed); target unresolved`, unresolvedSymlink: true };
588
596
  }
589
597
  function parentDir(abs) {
590
598
  const i = lastSepIndex(abs);
@@ -623,15 +631,39 @@ async function canonicalizeNewPath(env, abs, family, signal, opts) {
623
631
  if (!canon.ok) {
624
632
  return { ok: false, message: `cannot canonicalize existing ancestor "${candidate}": ${canon.error.message}` };
625
633
  }
626
- const tailSegments = tail.reverse();
627
- const canonSep = nativeSepOf(canon.value);
628
- if (tailSegments.length === 0)
629
- return { ok: true, key: canon.value };
630
- return { ok: true, key: [canon.value.replace(family === "win" ? /[\\/]+$/ : /\/+$/, ""), ...tailSegments].join(canonSep) };
634
+ return { ok: true, ...rejoinMissingTail(canon.value, tail.reverse(), family) };
631
635
  }
632
636
  tail.push(parts.pop());
633
637
  }
634
- return { ok: true, key: abs };
638
+ const share = family === "win" && isUncSpelling(abs) ? tail.pop() : undefined;
639
+ return { ok: true, ...rejoinMissingTail(`${[...parts, ...(share !== undefined ? [share] : [])].join(sep)}${sep}`, tail.reverse(), family) };
640
+ }
641
+ function rejoinMissingTail(canonical, tail, family) {
642
+ const trimmed = (at) => at.replace(family === "win" ? /[\\/]+$/ : /\/+$/, "");
643
+ let at = canonical;
644
+ const names = [];
645
+ for (let i = 0; i < tail.length; i++) {
646
+ const seg = tail[i];
647
+ if (seg === "" || seg === ".")
648
+ continue;
649
+ if (seg !== "..")
650
+ names.push(seg);
651
+ else if (names.length > 1)
652
+ names.pop();
653
+ else {
654
+ if (names.length === 1)
655
+ names.pop();
656
+ else {
657
+ const up = normalizeAbsPathLexically(`${at}/..`);
658
+ if (up !== normalizeAbsPathLexically(at))
659
+ at = up;
660
+ }
661
+ const rest = tail.slice(i + 1);
662
+ if (rest.some((s) => s !== "" && s !== "."))
663
+ return { reprobe: [trimmed(at), ...rest].join(nativeSepOf(at)) };
664
+ }
665
+ }
666
+ return { key: names.length === 0 ? at : [trimmed(at), ...names].join(nativeSepOf(at)) };
635
667
  }
636
668
  export function violationText(toolName, v) {
637
669
  return `Error (${toolName}): ${v.message}`;
@@ -40,25 +40,6 @@ const TYPE_GLOBS = {
40
40
  css: "*.{css,scss,less}",
41
41
  };
42
42
  const basename = (p) => p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1);
43
- function collapseDotSegments(p) {
44
- const win = isWinFormPath(p);
45
- const lead = (win ? /^[\\/]*/ : /^\/*/).exec(p)?.[0] ?? "";
46
- const sep = win ? "\\" : "/";
47
- const parts = p.slice(lead.length).split(win ? /[\\/]+/ : /\/+/);
48
- const floor = !win ? 0 : lead.length >= 2 ? 2 : /^[A-Za-z]:$/.test(parts[0] ?? "") ? 1 : 0;
49
- const kept = [];
50
- for (const part of parts) {
51
- if (part === "" || part === ".")
52
- continue;
53
- if (part === "..") {
54
- if (kept.length > floor)
55
- kept.pop();
56
- continue;
57
- }
58
- kept.push(part);
59
- }
60
- return kept.length === 0 ? "" : lead + kept.join(sep);
61
- }
62
43
  const NO_MATCHES = "No matches.";
63
44
  const GREP_LINE_CLIP = 500;
64
45
  function clipLine(line) {
@@ -813,18 +794,19 @@ export async function jsGrepDetailed(env, root, p, signal, guards, deny, denyOut
813
794
  const mode = p.output_mode ?? "files_with_matches";
814
795
  const rel = (abs) => (abs.startsWith(rootPrefix) ? abs.slice(rootPrefix.length) : abs);
815
796
  const startWin = isWinFormPath(start);
816
- const startNorm = collapseDotSegments(start);
817
- const targetSpell = p.path ? p.path.replace(startWin ? /[\\/]+$/ : /\/+$/, "") : "";
797
+ const trailingSeparators = startWin ? /[\\/]+$/ : /\/+$/;
798
+ const anchor = start.replace(trailingSeparators, "");
799
+ const targetSpell = p.path ? p.path.replace(trailingSeparators, "") : "";
818
800
  const isBoundary = (c) => c === "/" || (startWin && c === "\\");
819
801
  const relOut = (abs) => {
820
802
  if (!p.path) {
821
803
  const r = rel(abs);
822
804
  return r === abs ? r : `./${r}`;
823
805
  }
824
- if (abs === startNorm || abs === start)
806
+ if (abs === start || abs === anchor)
825
807
  return targetSpell;
826
- if (abs.startsWith(startNorm) && isBoundary(abs[startNorm.length]))
827
- return targetSpell + abs.slice(startNorm.length);
808
+ if (abs.startsWith(anchor) && isBoundary(abs[anchor.length]))
809
+ return targetSpell + abs.slice(anchor.length);
828
810
  return rel(abs);
829
811
  };
830
812
  if (p.glob) {
@@ -105,8 +105,15 @@ export interface ShellReadVerdictFacts {
105
105
  readonly writesPlaced?: true;
106
106
  /** A FACT beside the disposition: a write target this command names lands on the write-protection table — judged by
107
107
  * the table's own judge, as a write tool's target is — so the command's ask carries that table's class, whichever
108
- * mode reads it. Absent ⇒ no target the station established is covered (or no judge is mounted). */
108
+ * mode reads it. Absent ⇒ no target the station established is covered (or no judge is mounted). Said of a target whose
109
+ * TEXT names the row (the table's spelling view of one of its spellings); a covered target whose text names none is the
110
+ * member below — one target, one of the two. */
109
111
  readonly writeProtected?: true;
112
+ /** A FACT beside the disposition: a write target this command names meets the write-protection table only where it resolves
113
+ * on disk (its real target, a link on the way) — none of the target's spellings names a row — so the command's ask carries
114
+ * that reading's class, which the auto-mode classifier does not answer. Beside `writeProtected` when another target's text
115
+ * names a row. Absent ⇒ no such target (or no judge is mounted). */
116
+ readonly writeProtectedOnDisk?: true;
110
117
  /** A FACT beside the disposition: a target this command's program WRITES was placed and the environment could not say
111
118
  * where it leads ({@link EstablishedRead.unresolved}) — the reading's `target_unresolved` fact, the same one a write
112
119
  * tool's unresolved target states, so the command's ask carries that class (no automatic lane answers it; the shell face
@@ -104,12 +104,13 @@ function unplacedOptionsOf(judged) {
104
104
  async function writeGuardsOf(judged, boundary, env, signal) {
105
105
  const judge = boundary.writeTargetJudge;
106
106
  if (judge === undefined)
107
- return { unplaced: false, writeProtected: false };
107
+ return { unplaced: false, writeProtected: false, writeProtectedOnDisk: false };
108
108
  const { runs, concurrent } = runOrderOf(judged);
109
109
  const asKey = new Map();
110
110
  const asSpelling = new Map();
111
111
  const landingKeys = new Set();
112
112
  const writtenBy = runs.map(() => []);
113
+ const targets = [];
113
114
  const add = (into, view, child, at) => {
114
115
  if (!isAbsoluteForFamily(pathFamilyOf({ root: view }), view))
115
116
  return;
@@ -126,10 +127,16 @@ async function writeGuardsOf(judged, boundary, env, signal) {
126
127
  add(key ? asKey : asSpelling, f.read.target, child, at);
127
128
  if (key && written.seat === "landing")
128
129
  landingKeys.add(f.read.target);
129
- if (written.seat === "landing")
130
- for (const spelling of f.read.spellings)
130
+ const views = [[f.read.target, key]];
131
+ if (written.seat === "landing") {
132
+ for (const spelling of f.read.spellings) {
131
133
  add(asSpelling, spelling, child, at);
134
+ views.push([spelling, false]);
135
+ }
136
+ }
132
137
  writtenBy[at].push(f.read.target, ...f.read.spellings);
138
+ const derived = f.read.derivedSpellings ?? [];
139
+ targets.push({ views, text: f.read.established === "expansion" ? (f.read.origin !== undefined ? [f.read.origin] : []) : f.read.spellings.filter((s) => !derived.includes(s)) });
133
140
  }
134
141
  });
135
142
  const probes = new Map();
@@ -160,20 +167,52 @@ async function writeGuardsOf(judged, boundary, env, signal) {
160
167
  };
161
168
  const answer = async (view, key) => (await judge(view, { fs: env, ...(signal !== undefined ? { signal } : {}), ...(key ? { canonical: true } : {}) })) ?? "clear";
162
169
  const asked = [...[...asKey].map(([view, v]) => [view, v, true]), ...[...asSpelling].filter(([view]) => !landingKeys.has(view)).map(([view, v]) => [view, v, false])];
170
+ const slotOf = (view, key) => `${key || landingKeys.has(view) ? "key" : "spelling"}\u0000${view}`;
171
+ const askable = new Map(asked.map(([view, v, key]) => [slotOf(view, key), { view, v, key }]));
172
+ const answers = new Map();
173
+ const answerAt = async (view, key) => {
174
+ const slot = slotOf(view, key);
175
+ const known = answers.get(slot);
176
+ if (known !== undefined)
177
+ return known;
178
+ const a = askable.get(slot);
179
+ const found = a === undefined || (!(await writable(a.view, a.v)) && !changedBefore(a.view, a.v.at)) ? "clear" : await answer(a.view, a.key);
180
+ answers.set(slot, found);
181
+ return found;
182
+ };
183
+ const textNamesRow = async (text) => {
184
+ for (const spelling of text) {
185
+ if (!isAbsoluteForFamily(pathFamilyOf({ root: spelling }), spelling))
186
+ continue;
187
+ if ((await judge(spelling, { fs: env, spellingOnly: true })) === "protected")
188
+ return true;
189
+ }
190
+ return false;
191
+ };
163
192
  let unplaced = false;
164
193
  let writeProtected = false;
165
- for (const [view, v, key] of asked) {
166
- if (!(await writable(view, v)) && !changedBefore(view, v.at))
167
- continue;
168
- const found = await answer(view, key);
169
- if (found === "protected")
170
- writeProtected = true;
171
- if (found !== "clear")
172
- unplaced = true;
173
- if (writeProtected)
194
+ let writeProtectedOnDisk = false;
195
+ for (const target of targets) {
196
+ let covered = false;
197
+ for (const [view, key] of target.views) {
198
+ const found = await answerAt(view, key);
199
+ if (found !== "clear")
200
+ unplaced = true;
201
+ if (found === "protected") {
202
+ covered = true;
203
+ break;
204
+ }
205
+ }
206
+ if (covered) {
207
+ if (await textNamesRow(target.text))
208
+ writeProtected = true;
209
+ else
210
+ writeProtectedOnDisk = true;
211
+ }
212
+ if (writeProtected && writeProtectedOnDisk)
174
213
  break;
175
214
  }
176
- return { unplaced, writeProtected };
215
+ return { unplaced, writeProtected, writeProtectedOnDisk };
177
216
  }
178
217
  export function readStationMemberOf(call, members) {
179
218
  return seatOf("fold.readStation", members, call);
@@ -352,13 +391,18 @@ async function runShellReadStation(tool, command, declared, seat, readers, estab
352
391
  };
353
392
  let judged = judgedNow();
354
393
  let judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
355
- const guarded = judgedVerdict.disposition === "refuse" ? { unplaced: false, writeProtected: false } : await writeGuardsOf(judged, boundary, door.fs, signal);
394
+ const guarded = judgedVerdict.disposition === "refuse" ? { unplaced: false, writeProtected: false, writeProtectedOnDisk: false } : await writeGuardsOf(judged, boundary, door.fs, signal);
356
395
  judged = judgedNow();
357
396
  judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
358
397
  const unplaced = unplacedOptionsOf(judged);
359
398
  const placed = judgedVerdict.finding !== "unanswered" && writesPlacedOf(judged, boundary);
360
399
  const unresolved = judgedVerdict.disposition !== "refuse" && runOrderOf(judged).runs.some((s) => s.findings.some((f) => f.read.written !== undefined && f.read.unresolved === true));
361
- const facts = { ...judgedVerdict, ...(guarded.writeProtected ? { writeProtected: true } : {}), ...(unresolved ? { targetUnresolved: true } : {}) };
400
+ const facts = {
401
+ ...judgedVerdict,
402
+ ...(guarded.writeProtected ? { writeProtected: true } : {}),
403
+ ...(guarded.writeProtectedOnDisk ? { writeProtectedOnDisk: true } : {}),
404
+ ...(unresolved ? { targetUnresolved: true } : {}),
405
+ };
362
406
  const verdict = placed && !guarded.unplaced ? { ...facts, writesPlaced: true } : unplaced !== undefined ? { ...facts, unplacedOptions: unplaced } : facts;
363
407
  return { plan, established, judged, boundary, verdict };
364
408
  }
@@ -444,8 +444,9 @@ function establishLegOver(seen, readRoots) {
444
444
  continue;
445
445
  }
446
446
  const spellings = at.spelled !== undefined ? [at.folded, at.spelled] : [at.folded];
447
+ const derived = name !== operand.spelled ? { derivedSpellings: spellings } : {};
447
448
  for (const seat of j.seats ?? ["landing"])
448
- out.push(writtenAt(await canonicalReadOf(j.candidate, at.spelled ?? at.folded, spellings, "canonical", undefined, undefined, signal, seat), j, seat));
449
+ out.push(writtenAt({ ...(await canonicalReadOf(j.candidate, at.spelled ?? at.folded, spellings, "canonical", undefined, undefined, signal, seat)), ...derived }, j, seat));
449
450
  }
450
451
  }
451
452
  return out;
@@ -55,7 +55,7 @@ export async function withHomeViews(door, placed, established, signal) {
55
55
  const home = landed ? await views.of(r.target, r.node === "file" ? { leaf: "file" } : undefined) : {};
56
56
  if (home.unread !== undefined && !unread.includes(home.unread))
57
57
  unread.push(home.unread);
58
- out.push(home.view === undefined || r.spellings.includes(home.view) ? r : { ...r, spellings: [...r.spellings, home.view] });
58
+ out.push(home.view === undefined || r.spellings.includes(home.view) ? r : { ...r, spellings: [...r.spellings, home.view], derivedSpellings: [...(r.derivedSpellings ?? []), home.view] });
59
59
  }
60
60
  reads.set(segment, out);
61
61
  }
@@ -218,11 +218,15 @@ export interface ShellReadBoundary extends BashReadonlyRootBoundary {
218
218
  * `"guarded"`: a deployment row covers it — the target is not placed; `undefined`: nothing covers it. Read by the
219
219
  * station's write facts only. A judgment that throws fails the station's answer (the caller's fail-closed arm). Every lookup
220
220
  * it makes goes through `fs` — the command's door — and through no environment of its own: the station's one decision about
221
- * what a silence means reads the answers the judgment got as well as the ones it did not. */
221
+ * what a silence means reads the answers the judgment got as well as the ones it did not. `spellingOnly` ⇔ judge the path as
222
+ * written and nothing else — the table's spelling view, no lookup, no deployment row: `"protected"` when the text itself names
223
+ * a row of the table (what the station tells a written target's two readings apart by,
224
+ * {@link import("./shell-read-check.js").ShellReadVerdict.writeProtectedOnDisk}). */
222
225
  readonly writeTargetJudge?: (target: string, opts: {
223
226
  readonly fs: ObservedFilesystem;
224
227
  readonly signal?: AbortSignal;
225
228
  readonly canonical?: true;
229
+ readonly spellingOnly?: true;
226
230
  }) => Promise<"protected" | "guarded" | undefined>;
227
231
  }
228
232
  /** How far one candidate got before it was judged. `lexical` = the folded spelling is the judged target
@@ -239,6 +243,11 @@ export interface EstablishedRead {
239
243
  /** Every spelling the deny judge sees BESIDE the target: the folded spelling, the kernel spelling of a
240
244
  * `..` operand, the pattern an expansion came from, the placeholder-carrying fold of a substitution. */
241
245
  readonly spellings: readonly string[];
246
+ /** The members of {@link spellings} a reading of the FILESYSTEM produced rather than the command's text — the home's view of
247
+ * a landed target (read-deny-home.ts), added so the deny judge places a home-anchored row wherever the target really is; the
248
+ * name of a GNU sed `--follow-symlinks` backup when the operand's links supplied it. Every other spelling is the command's
249
+ * own text (folded, or as the kernel walks it). Absent ⇒ none. */
250
+ readonly derivedSpellings?: readonly string[];
242
251
  /** The pattern or traversal root an `expansion` came from, as folded. */
243
252
  readonly origin?: string;
244
253
  /** What the environment said the target IS, where a read asked — only a traversal root asks (it lists the root
@@ -1,12 +1,13 @@
1
1
  /**
2
2
  * 审计深挖 G4 — the `EnterWorktree` / `ExitWorktree` tool pair: SESSION-level git-worktree
3
- * isolation. EnterWorktree creates a managed worktree under `.sema-worktrees/`
4
- * (the same {@link WORKTREE_PARENT} the subagent `isolation:"worktree"` lane uses) and REALLY switches
5
- * the task's working directory into it; ExitWorktree returns to the original directory and cleans up.
3
+ * isolation. EnterWorktree creates a managed worktree under `.sema/worktrees/`
4
+ * (the same {@link WORKTREE_PARENT} the subagent `isolation:"worktree"` lane uses, through the one mint `addWorktree`) and
5
+ * REALLY switches the task's working directory and write access into it; ExitWorktree returns to the original directory and
6
+ * cleans up.
6
7
  *
7
8
  * Semantics:
8
9
  * ① worktrees live in a managed parent dir inside the repo (CC: `.claude/worktrees/`; sema:
9
- * `.sema-worktrees/`) — never scattered;
10
+ * `.sema/worktrees/<name>`, on the new branch `sema/<name>`) — never scattered;
10
11
  * ② baseRef is two-state: `"head"` = the current local HEAD (unpushed commits present), `"fresh"` =
11
12
  * the default branch tip (CC: `origin/<default-branch>` for a clean tree);
12
13
  * ③ a second CREATING EnterWorktree (`name`) while one is active is REFUSED ("Already in a worktree
@@ -23,18 +24,16 @@
23
24
  * hands band shares one {@link CwdRef} (`handsCwdRef` in prepare-task): Bash runs every command in
24
25
  * `cwdRef.current` (and `cd` moves it), Read/Edit/Write resolve relative paths against it, Monitor
25
26
  * spawns there. EnterWorktree therefore performs a REAL switch by assigning `cwdRef.current`; the
26
- * Runner's per-tool cwd read reports it as `workspace_changed`, same as an observed `cd`. Path
27
- * containment is untouched: the worktree lives UNDER the task root, so resolveKey's canonical-within
28
- * check still holds for every subsequent fs op.
27
+ * Runner's per-tool cwd read reports it as `workspace_changed`, same as an observed `cd`.
29
28
  *
30
- * ⚠️ Containment ruling (deliberate): entering a worktree is a **cwd switch, NOT a
31
- * sandbox**. resolveKey's containment anchor stays the ORIGINAL task root — it is deliberately NOT
32
- * re-anchored/tightened to the worktree dir, so `../../` from inside the worktree can still reach the
33
- * rest of the repository (which is WITHIN the task root and was reachable before Enter too), while
34
- * anything outside the task root stays fenced exactly as before. This matches the reference's semantics
35
- * (CC worktrees live beside the repo with no containment tightening either); tightening here would buy
36
- * no security (Bash/`cd` already roam the root) and would break legitimate repo-relative access. The
37
- * tool description + Enter reply state this honestly so the model never assumes isolation.
29
+ * WRITE ROOT = WRITE LOCATION (the reference implementation's permission-root relocation: entering a worktree "moves the
30
+ * session's working directory and write access there", and after a further switch the previously visited tree is no longer
31
+ * writable). The leg's write root is read live through {@link currentCheckoutOf} — the active worktree while one is tracked,
32
+ * the task root otherwise — by every write-root reader (the structured write tools, the shell's write targets, the
33
+ * accept-edits mode gate), so the base checkout and every other managed worktree are outside the write roots while a tree is
34
+ * active and judged by the existing out-of-root semantics. The READ roots do not move (the worktree lives under the task
35
+ * root). It is still not a sandbox: an arbitrary program run in the shell writes wherever the process can; the tool
36
+ * description and the replies say both halves.
38
37
  *
39
38
  * Security posture: both tools only ever run `git` against the task root / managed worktree (no
40
39
  * arbitrary command surface), but they create/delete on-disk state ⇒ effect:"write" (plan mode gates
@@ -47,6 +46,7 @@
47
46
  * Enter→suspend→resume→Exit behaves exactly like an unsuspended session.
48
47
  */
49
48
  import type { ActiveWorktreeSession, AgentTool, ExecutionEnv } from "../internal/harness-types.js";
49
+ import type { ManagedCheckoutView } from "../core/write-protect.js";
50
50
  import type { CwdRef } from "./fs/index.js";
51
51
  /** the ACTIVE worktree session, ALL-SERIALIZABLE (plain strings, no closures):
52
52
  * prepare-task owns the ref, stamps `current` into `CheckpointState.activeWorktree` at a durable
@@ -73,6 +73,33 @@ export interface WorktreeSessionRef {
73
73
  * for the CAS-reject-vs-serialize trade-off). */
74
74
  entering?: boolean;
75
75
  }
76
+ /**
77
+ * THE write location of a leg — its one reader: the active worktree while one is tracked, the task root otherwise. Every
78
+ * write-root reader reads this (the structured write tools, the shell's write targets, the accept-edits mode gate), so
79
+ * "where may this leg write" has one answer that moves with EnterWorktree / ExitWorktree.
80
+ *
81
+ * The answer is a CANONICAL directory (the write roots compare canonical keys). A tree this engine minted is spelled under
82
+ * the task root's own spelling (`<root>/.sema/worktrees/<slug>`), and its three managed levels are refused at mint when any
83
+ * is a symlink — so its canonical form IS the task root's canonical form plus the same tail; a tree entered by `path` is
84
+ * already spelled as git reports it (the physical path). A recorded spelling under neither stands as recorded: a write root
85
+ * that matches no key refuses, never admits.
86
+ */
87
+ export declare function currentCheckoutOf(session: WorktreeSessionRef | undefined, taskRoot: {
88
+ readonly spelled: string;
89
+ readonly canonical: string;
90
+ }): string;
91
+ /** A leg's write-location seat (the EnterWorktree session; empty until the worktree mount seeds it) and its readers, minted
92
+ * before any write-root reader: `writeLocation` ({@link currentCheckoutOf} over the seat) and `checkout` — the write location
93
+ * when it is a managed tree (a switch, or a task root that IS one): its canonical identity and the spelling the leg's paths
94
+ * carry it under, for the write-protection judge's current-tree reading (`WriteProtectionCompileOptions.checkoutOf`). */
95
+ export declare function writeLocationOf(taskRoot: {
96
+ readonly spelled: string;
97
+ readonly canonical: string;
98
+ }): {
99
+ readonly seat: WorktreeSessionRef;
100
+ readonly writeLocation: () => string;
101
+ readonly checkout: () => ReadonlyArray<ManagedCheckoutView> | undefined;
102
+ };
76
103
  export interface WorktreeToolsOptions {
77
104
  /** The task root (the repo root the managed worktrees nest under; `git` runs `-C` here). */
78
105
  repoRoot: string;
@@ -1,9 +1,32 @@
1
1
  import { resolve } from "node:path";
2
2
  import { Type } from "typebox";
3
3
  import { defineTool, errorResult } from "../core/tools.js";
4
- import { addWorktree, pruneWorktrees, WORKTREE_PARENT } from "../core/git-worktree-env.js";
4
+ import { addWorktree, managedWorktreeBaseOf, pruneWorktrees, removeManagedWorktree, worktreeNameProblem, WORKTREE_PARENT } from "../core/git-worktree-env.js";
5
5
  import { mountRuleFace, toolFace } from "../core/tool-catalog-entries.js";
6
6
  import { thrownText } from "../core/thrown-value.js";
7
+ export function currentCheckoutOf(session, taskRoot) {
8
+ const dir = session?.current?.worktreeDir;
9
+ if (dir === undefined)
10
+ return taskRoot.canonical;
11
+ const spelled = taskRoot.spelled.endsWith("/") ? taskRoot.spelled.slice(0, -1) : taskRoot.spelled;
12
+ if (spelled !== taskRoot.canonical && (dir === spelled || dir.startsWith(`${spelled}/`)))
13
+ return taskRoot.canonical + dir.slice(spelled.length);
14
+ return dir;
15
+ }
16
+ export function writeLocationOf(taskRoot) {
17
+ const seat = {};
18
+ const writeLocation = () => currentCheckoutOf(seat, taskRoot);
19
+ const checkout = () => {
20
+ const views = [];
21
+ for (const [root, kind] of [[writeLocation(), "canonical"], [seat.current?.worktreeDir ?? taskRoot.spelled, "spelled"]]) {
22
+ const base = managedWorktreeBaseOf(root);
23
+ if (base !== undefined)
24
+ views.push({ root, base, kind });
25
+ }
26
+ return views.length > 0 ? views : undefined;
27
+ };
28
+ return { seat, writeLocation, checkout };
29
+ }
7
30
  const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work in a worktree — either by the user directly, or by " +
8
31
  "project instructions. This tool creates an isolated git worktree and switches the current session into it.\n" +
9
32
  "\n" +
@@ -21,9 +44,9 @@ const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work
21
44
  "\n" +
22
45
  "## Behavior\n" +
23
46
  "\n" +
24
- `- Creates a detached worktree under \`${WORKTREE_PARENT}/\` in the repository root and switches the ` +
25
- "session's working directory to it: subsequent Bash commands run there, and relative paths in " +
26
- "Read/Edit/Write resolve against it.\n" +
47
+ `- Creates a new worktree under \`${WORKTREE_PARENT}/<name>/\` in the repository root on a new branch \`sema/<name>\` and ` +
48
+ "switches the session's working directory and write access to it: subsequent Bash commands run there, relative paths in " +
49
+ "Read/Edit/Write resolve against it, and file writes must land inside it (or in an additional working directory).\n" +
27
50
  '- `baseRef` picks the starting point: `"fresh"` (default) starts from the default branch tip ' +
28
51
  "(origin's default branch when a remote exists, else local main/master, else the current HEAD with " +
29
52
  'an honest note); `"head"` starts from the current local HEAD (unpushed commits and current branch ' +
@@ -34,10 +57,13 @@ const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work
34
57
  "- Pass `path` instead of `name` to switch the session into a worktree of this repository that already " +
35
58
  "exists (it must appear in `git worktree list` and live under the task root). Switching with `path` also " +
36
59
  "works while already in a worktree session — the previous worktree is left on disk, untouched, and only " +
37
- "the new one is tracked for exit-time cleanup. ExitWorktree will not remove a worktree entered via `path`.\n" +
38
- "- This is a working-directory switch, NOT a sandbox: file-access containment stays anchored at the " +
39
- "original task root (the worktree lives under it), so paths outside the worktree but inside the task " +
40
- "root remain reachable — do not rely on the worktree as an isolation boundary.\n" +
60
+ "the new one is tracked for exit-time cleanup. ExitWorktree will not remove a worktree entered via `path`. After a further " +
61
+ "switch, previously-visited worktrees are no longer writable — re-issue EnterWorktree with `path` to return to one.\n" +
62
+ "- While a worktree is active, the base checkout and every other worktree are outside the write roots: where writes are " +
63
+ "confined to the write roots, Edit/Write refuse them and a shell command writing there asks first. Reads still reach the " +
64
+ "whole task root. Use ExitWorktree to " +
65
+ "write the base checkout again. This is not a sandbox: a program run in the shell can still write anywhere the process " +
66
+ "can — do not rely on the worktree as an isolation boundary.\n" +
41
67
  "- Requires a git repository — there is no VCS-agnostic fallback in this deployment.";
42
68
  const EXIT_DESCRIPTION = "Exit a worktree session created by EnterWorktree and return the session to the original working directory.\n" +
43
69
  "\n" +
@@ -117,7 +143,7 @@ export function createWorktreeTools(env, opts) {
117
143
  description: ENTER_DESCRIPTION,
118
144
  parameters: Type.Object({
119
145
  name: Type.Optional(Type.String({
120
- description: "Optional name for the new worktree (letters, digits, dots, underscores, dashes; other characters are sanitized). A random suffix is always appended. Generated if not provided. Mutually exclusive with `path`.",
146
+ description: 'Optional name for a new worktree. Each "/"-separated segment may contain only letters, digits, dots, underscores, and dashes; max 64 chars total. A random name is generated if not provided. Mutually exclusive with `path`.',
121
147
  })),
122
148
  path: Type.Optional(Type.String({
123
149
  description: "Path to an existing worktree of the current repository to switch into instead of creating a new one. Must appear in `git worktree list` for the current repo (and live under the task root). Mutually exclusive with `name`.",
@@ -182,7 +208,7 @@ export function createWorktreeTools(env, opts) {
182
208
  const fence = rootCanon.ok ? rootCanon.value : repoRoot;
183
209
  if (target !== fence && !target.startsWith(fence.endsWith("/") ? fence : `${fence}/`)) {
184
210
  return errorResult(`Error (EnterWorktree): the worktree ${target} lives outside the task root ${repoRoot}; ` +
185
- "file containment stays anchored at the task root, so it cannot be entered from this session.");
211
+ "read containment stays anchored at the task root, so it cannot be entered from this session.");
186
212
  }
187
213
  const head = await env.exec("git rev-parse HEAD", { cwd: target });
188
214
  if (!head.ok || head.value.exitCode !== 0) {
@@ -193,44 +219,50 @@ export function createWorktreeTools(env, opts) {
193
219
  session.current = { worktreeDir: target, originalCwd, baseSha: head.value.stdout.trim(), entered: true };
194
220
  cwdRef.current = target;
195
221
  return {
196
- content: `Switched into the existing worktree at ${target}${previous ? ` (the previous worktree at ${previous.worktreeDir} was left on disk, untouched)` : ""}. ` +
197
- "The session's working directory is now this worktree — subsequent commands and relative paths " +
198
- "operate there. Note this is a cwd switch, not a sandbox: file containment stays anchored at the " +
199
- "task root. ExitWorktree will restore the original directory but will NOT remove a worktree " +
200
- "entered via `path`.",
222
+ content: `Switched into the existing worktree at ${target}${previous ? ` (the previous worktree at ${previous.worktreeDir} was left on disk, untouched, and is no longer writable)` : ""}. ` +
223
+ "The session's working directory and write access are now this worktree — subsequent commands and relative paths " +
224
+ "operate there, and writes outside it (the base checkout included) are outside the write roots. Reads still reach " +
225
+ "the whole task root; this is not a sandbox. ExitWorktree will restore the original directory but will NOT remove a " +
226
+ "worktree entered via `path`.",
201
227
  details: { type: "worktree", action: "enter", worktreeDir: target },
202
228
  };
203
229
  }
230
+ const nameProblem = name === undefined ? undefined : worktreeNameProblem(name);
231
+ if (nameProblem !== undefined)
232
+ return errorResult(`Error (EnterWorktree): ${nameProblem.slice(0, 300)}.`);
204
233
  const base = await resolveBaseCommit(env, repoRoot, baseRef ?? "fresh");
205
234
  if ("error" in base)
206
235
  return errorResult(`Error (EnterWorktree): ${base.error}.`);
207
- let createdDir;
236
+ let created;
208
237
  try {
209
- const { worktreeDir } = await addWorktree(env, {
238
+ created = await addWorktree(env, {
210
239
  repoRoot,
211
- sessionId: name ?? "worktree",
240
+ sessionId: "worktree",
241
+ ...(name !== undefined ? { name } : {}),
212
242
  commit: base.sha,
213
243
  rootEnvAt: (dir) => Object.create(env, {
214
244
  cwd: { value: dir, configurable: true },
215
245
  destroy: { value: undefined, writable: true, configurable: true },
216
246
  }),
217
247
  });
218
- createdDir = worktreeDir;
219
248
  }
220
249
  catch (e) {
221
250
  return errorResult(`Error (EnterWorktree): ${thrownText(e)}`);
222
251
  }
252
+ const createdDir = created.worktreeDir;
223
253
  session.current = {
224
254
  worktreeDir: createdDir,
225
255
  originalCwd: cwdRef.current,
226
256
  baseSha: base.sha,
257
+ name: created.name,
258
+ branch: created.branch,
227
259
  };
228
260
  cwdRef.current = createdDir;
229
261
  return {
230
- content: `Created worktree at ${createdDir} (base: ${base.label}${base.note ?? ""}). ` +
231
- "The session's working directory is now the worktree — subsequent commands and relative paths " +
232
- "operate there. Note this is a cwd switch, not a sandbox: file containment stays anchored at the " +
233
- "task root, so the rest of the repository remains reachable. " +
262
+ content: `Created worktree at ${createdDir} (base: ${base.label}${base.note ?? ""}) on branch ${created.branch}. ` +
263
+ "The session's working directory and write access are now the worktree — subsequent commands and relative paths " +
264
+ "operate there, and writes outside it (the base checkout included) are outside the write roots. Reads still reach " +
265
+ "the rest of the task root; this is not a sandbox. " +
234
266
  "Use ExitWorktree to leave (an unchanged worktree is removed; a changed one is kept).",
235
267
  details: { type: "worktree", action: "create", worktreeDir: createdDir, base: base.label },
236
268
  };
@@ -253,7 +285,7 @@ export function createWorktreeTools(env, opts) {
253
285
  description: "true = remove the worktree even when it has uncommitted files or new commits, permanently discarding them. Default false: a changed worktree is kept and its changes listed. Cannot be combined with `keep: true`.",
254
286
  })),
255
287
  action: Type.Optional(Type.Union([Type.Literal("keep"), Type.Literal("remove")], {
256
- description: '"keep" leaves the worktree on disk. "remove" takes the default removal path: an unchanged worktree is removed, a changed one is still KEPT unless `discard_changes: true`. The worktree is detached — no branch is created or deleted either way.',
288
+ description: '"keep" leaves the worktree and its branch on disk. "remove" takes the default removal path: an unchanged worktree is removed, a changed one is still KEPT unless `discard_changes: true`. A removed worktree\'s branch is deleted with it only when it carries no commits beyond the base; a branch with commits is kept and named in the reply.',
257
289
  })),
258
290
  discard_changes: Type.Optional(Type.Boolean({
259
291
  description: 'Set true to remove the worktree even when it has uncommitted files or unmerged commits — they are permanently discarded. Without it a changed worktree is KEPT (the exit still completes and the reply lists the changes plus this escape), never refused.',
@@ -377,13 +409,9 @@ export function createWorktreeTools(env, opts) {
377
409
  details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: true },
378
410
  };
379
411
  }
380
- const removeFailure = await env
381
- .exec(`git worktree remove --force ${shq(active.worktreeDir)}`, { cwd: repoRoot })
382
- .then((r) => r.ok && r.value.exitCode === 0
383
- ? undefined
384
- : r.ok
385
- ? (r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}`).trim()
386
- : reasonOf(r.error), (e) => reasonOf(e));
412
+ const removal = await removeManagedWorktree(env, repoRoot, active.worktreeDir, active.branch !== undefined ? { name: active.branch, baseSha: active.baseSha } : undefined);
413
+ const removeFailure = removal.ok ? undefined : removal.detail.trim();
414
+ const branchNote = !removal.ok ? "" : removal.branchKept !== undefined ? ` Its branch was kept: ${removal.branchKept}.` : removal.branchDeleted !== undefined ? ` Its branch ${removal.branchDeleted} was deleted.` : "";
387
415
  const pruned = await pruneWorktrees(env, repoRoot);
388
416
  const stillThere = await env.exists(active.worktreeDir);
389
417
  const removalNote = removeFailure !== undefined ? ` (the removal command reported: ${removeFailure})` : "";
@@ -412,7 +440,7 @@ export function createWorktreeTools(env, opts) {
412
440
  }
413
441
  return {
414
442
  content: `Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
415
- `The worktree at ${active.worktreeDir} ${stateClause} and was removed.${removalNote}${pruneNote}`,
443
+ `The worktree at ${active.worktreeDir} ${stateClause} and was removed.${removalNote}${pruneNote}${branchNote}`,
416
444
  details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: false, ...pruneDetail },
417
445
  };
418
446
  }