@sema-agent/core 7.56.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 (319) hide show
  1. package/CHANGELOG.md +926 -0
  2. package/LICENSE +1 -1
  3. package/dist/agents/org-delivery-gate.js +3 -4
  4. package/dist/agents/peer-held-queue.d.ts +69 -49
  5. package/dist/agents/peer-held-queue.js +255 -106
  6. package/dist/agents/peer-session-drain.js +63 -43
  7. package/dist/agents/send-message-tool.js +3 -2
  8. package/dist/agents/subagent-steps.js +2 -4
  9. package/dist/agents/subagent.js +8 -8
  10. package/dist/brain/anthropic.js +16 -8
  11. package/dist/brain/open-responses.js +10 -8
  12. package/dist/brain/openai.js +11 -9
  13. package/dist/brain/provider-dialect.d.ts +3 -2
  14. package/dist/brain/provider-dialect.js +2 -2
  15. package/dist/brain/request-params.d.ts +6 -0
  16. package/dist/brain/request-params.js +14 -1
  17. package/dist/brain/route-adjudicator.js +2 -1
  18. package/dist/brain/stream-engine.d.ts +9 -0
  19. package/dist/brain/stream-engine.js +24 -10
  20. package/dist/brain/stream-shared.d.ts +5 -4
  21. package/dist/brain/stream-shared.js +4 -4
  22. package/dist/core/a2a.d.ts +2 -1
  23. package/dist/core/a2a.js +23 -10
  24. package/dist/core/allow-entry.d.ts +5 -11
  25. package/dist/core/allow-entry.js +19 -26
  26. package/dist/core/approval-object.d.ts +21 -5
  27. package/dist/core/approval-object.js +44 -17
  28. package/dist/core/ask-origin.d.ts +23 -4
  29. package/dist/core/ask-origin.js +5 -1
  30. package/dist/core/auto-compaction.d.ts +75 -6
  31. package/dist/core/auto-compaction.js +43 -27
  32. package/dist/core/auto-mode-directive.d.ts +29 -5
  33. package/dist/core/auto-mode-directive.js +38 -8
  34. package/dist/core/background-agent-store.d.ts +6 -2
  35. package/dist/core/background-agent-store.js +1 -1
  36. package/dist/core/checkpoint-requirements.d.ts +13 -1
  37. package/dist/core/checkpoint-requirements.js +4 -0
  38. package/dist/core/checkpoint-store.d.ts +44 -40
  39. package/dist/core/checkpoint-store.js +32 -14
  40. package/dist/core/cross-boundary-taint.js +4 -2
  41. package/dist/core/engine-notice.d.ts +4 -3
  42. package/dist/core/engine-notice.js +6 -0
  43. package/dist/core/file-history-store.d.ts +14 -8
  44. package/dist/core/file-history-store.js +14 -4
  45. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  46. package/dist/core/fs-write-gate-policy.js +7 -3
  47. package/dist/core/gate-fold.js +6 -3
  48. package/dist/core/gate-lanes.js +13 -5
  49. package/dist/core/git-worktree-env.d.ts +53 -11
  50. package/dist/core/git-worktree-env.js +96 -12
  51. package/dist/core/hooks.d.ts +6 -3
  52. package/dist/core/hooks.js +12 -5
  53. package/dist/core/human-input-projection.d.ts +1 -0
  54. package/dist/core/human-input-projection.js +3 -0
  55. package/dist/core/locked-config.d.ts +15 -1
  56. package/dist/core/locked-config.js +38 -2
  57. package/dist/core/mailbox-store.d.ts +62 -1
  58. package/dist/core/mailbox-store.js +59 -0
  59. package/dist/core/mcp-call-meta.d.ts +66 -0
  60. package/dist/core/mcp-call-meta.js +103 -0
  61. package/dist/core/mcp-connection-pool.d.ts +3 -1
  62. package/dist/core/mcp-connection-pool.js +3 -1
  63. package/dist/core/mcp-failure.d.ts +7 -1
  64. package/dist/core/mcp-failure.js +10 -0
  65. package/dist/core/mcp-name-judge.d.ts +46 -0
  66. package/dist/core/mcp-name-judge.js +61 -0
  67. package/dist/core/mcp-probe.d.ts +5 -1
  68. package/dist/core/mcp-probe.js +3 -6
  69. package/dist/core/mcp-server-link.d.ts +5 -2
  70. package/dist/core/mcp-server-spec.d.ts +46 -18
  71. package/dist/core/mcp-server-spec.js +1 -18
  72. package/dist/core/mcp.d.ts +6 -14
  73. package/dist/core/mcp.js +85 -65
  74. package/dist/core/memory-engine/consolidation-driver.js +4 -3
  75. package/dist/core/memory-engine/distiller.js +26 -17
  76. package/dist/core/memory-engine/layout.js +5 -2
  77. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  78. package/dist/core/memory-engine/scope-contract.js +80 -11
  79. package/dist/core/mode-policy.d.ts +8 -5
  80. package/dist/core/mode-policy.js +5 -4
  81. package/dist/core/mods/host.js +1 -1
  82. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  83. package/dist/core/mods/kernel/dispatch.js +10 -8
  84. package/dist/core/mods/kernel/events.d.ts +5 -1
  85. package/dist/core/mods/kernel/events.js +1 -1
  86. package/dist/core/mods/kernel/registration.d.ts +5 -1
  87. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  88. package/dist/core/mods/kernel/site-rules.js +10 -0
  89. package/dist/core/mods/package.d.ts +23 -0
  90. package/dist/core/mods/package.js +118 -0
  91. package/dist/core/mods/stations.d.ts +2 -2
  92. package/dist/core/mods/stations.js +1 -1
  93. package/dist/core/mods/tool-call.d.ts +5 -1
  94. package/dist/core/mods/tool-call.js +12 -3
  95. package/dist/core/park-selfcheck.js +2 -0
  96. package/dist/core/path-guard-rows.d.ts +20 -0
  97. package/dist/core/path-guard-rows.js +11 -0
  98. package/dist/core/peer-seat.d.ts +186 -0
  99. package/dist/core/peer-seat.js +307 -0
  100. package/dist/core/permission-rule-consent.d.ts +5 -3
  101. package/dist/core/permission-rule-consent.js +20 -15
  102. package/dist/core/permission-rule-model.d.ts +43 -2
  103. package/dist/core/permission-rule-model.js +52 -8
  104. package/dist/core/permission-rule-org.js +1 -1
  105. package/dist/core/present-plan-tool.d.ts +10 -1
  106. package/dist/core/present-plan-tool.js +46 -2
  107. package/dist/core/protocol-http-auth.d.ts +56 -31
  108. package/dist/core/protocol-http-auth.js +71 -42
  109. package/dist/core/protocol-naming.d.ts +20 -0
  110. package/dist/core/protocol-naming.js +20 -3
  111. package/dist/core/read-only-shell.d.ts +20 -5
  112. package/dist/core/read-only-shell.js +29 -14
  113. package/dist/core/redaction-marks.d.ts +16 -0
  114. package/dist/core/redaction-marks.js +16 -0
  115. package/dist/core/redaction-passes.js +8 -9
  116. package/dist/core/remote-env.d.ts +37 -1
  117. package/dist/core/remote-env.js +11 -0
  118. package/dist/core/resume-startup-cause.d.ts +24 -2
  119. package/dist/core/resume-startup-cause.js +20 -1
  120. package/dist/core/retention.d.ts +41 -15
  121. package/dist/core/retention.js +59 -12
  122. package/dist/core/rewrite-rejudge.d.ts +37 -0
  123. package/dist/core/rewrite-rejudge.js +40 -0
  124. package/dist/core/roles.js +50 -7
  125. package/dist/core/run-origin.d.ts +40 -0
  126. package/dist/core/run-origin.js +37 -0
  127. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  128. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  129. package/dist/core/runner/compact-session.d.ts +10 -0
  130. package/dist/core/runner/compact-session.js +202 -0
  131. package/dist/core/runner/compaction-call-options.d.ts +2 -2
  132. package/dist/core/runner/compaction-restate.d.ts +15 -6
  133. package/dist/core/runner/compaction-restate.js +28 -2
  134. package/dist/core/runner/compaction-seams.d.ts +21 -1
  135. package/dist/core/runner/compaction-seams.js +11 -8
  136. package/dist/core/runner/contracts.d.ts +36 -21
  137. package/dist/core/runner/derived-route-fallback.d.ts +13 -0
  138. package/dist/core/runner/derived-route-fallback.js +6 -0
  139. package/dist/core/runner/env-capability-census.d.ts +3 -2
  140. package/dist/core/runner/env-capability-census.js +9 -3
  141. package/dist/core/runner/gate-exit.d.ts +18 -4
  142. package/dist/core/runner/gate-exit.js +5 -1
  143. package/dist/core/runner/permission-rule-lanes.d.ts +7 -7
  144. package/dist/core/runner/permission-rule-lanes.js +17 -11
  145. package/dist/core/runner/prepare-acquire-reconcile.d.ts +3 -0
  146. package/dist/core/runner/prepare-acquire-reconcile.js +2 -1
  147. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  148. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  149. package/dist/core/runner/prepare-config-doors.d.ts +14 -5
  150. package/dist/core/runner/prepare-config-doors.js +16 -13
  151. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  152. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  153. package/dist/core/runner/prepare-gate-stations.js +1 -1
  154. package/dist/core/runner/prepare-hands-readface.d.ts +10 -4
  155. package/dist/core/runner/prepare-hands-readface.js +6 -1
  156. package/dist/core/runner/prepare-memory.d.ts +3 -0
  157. package/dist/core/runner/prepare-memory.js +19 -23
  158. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  159. package/dist/core/runner/prepare-park-ask.js +2 -2
  160. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  161. package/dist/core/runner/prepare-policy-chain.js +4 -6
  162. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  163. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  164. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  165. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  166. package/dist/core/runner/prepare-task.d.ts +4 -1
  167. package/dist/core/runner/prepare-task.js +46 -37
  168. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +13 -0
  169. package/dist/core/runner/prepare-tool-disclosure-mount.js +13 -7
  170. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  171. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  172. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  173. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  174. package/dist/core/runner/resume-admission.js +1 -1
  175. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  176. package/dist/core/runner/rewind-files.d.ts +2 -5
  177. package/dist/core/runner/rewind-files.js +9 -51
  178. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  179. package/dist/core/runner/run-harness-handlers.js +1 -8
  180. package/dist/core/runner/run-identity-wiring.js +1 -0
  181. package/dist/core/runner/run-leg.js +15 -22
  182. package/dist/core/runner/run-notification-lane.d.ts +2 -0
  183. package/dist/core/runner/run-notification-lane.js +5 -2
  184. package/dist/core/runner/run-recovery-lanes.js +3 -4
  185. package/dist/core/runner/run-settle-and-teardown.js +5 -11
  186. package/dist/core/runner/run-terminal-adoption.js +3 -4
  187. package/dist/core/runner/run-turn-boundary.js +3 -5
  188. package/dist/core/runner/runtask.d.ts +8 -1
  189. package/dist/core/runner/runtask.js +28 -34
  190. package/dist/core/runner/send-message-continuation.js +1 -1
  191. package/dist/core/runner/session-verb-doors.d.ts +28 -0
  192. package/dist/core/runner/session-verb-doors.js +48 -0
  193. package/dist/core/runner/session-write-ledger.d.ts +30 -0
  194. package/dist/core/runner/session-write-ledger.js +101 -0
  195. package/dist/core/runner/stream-settle-backstop.js +11 -14
  196. package/dist/core/runner/sub-agent-deny-lists.d.ts +25 -3
  197. package/dist/core/runner/sub-agent-deny-lists.js +21 -10
  198. package/dist/core/runner/teardown-bounded.d.ts +1 -0
  199. package/dist/core/runner/teardown-bounded.js +1 -0
  200. package/dist/core/runner/terminal-account.js +3 -3
  201. package/dist/core/runner/tool-end-body.js +1 -0
  202. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  203. package/dist/core/runner/tool-occurrence.js +2 -1
  204. package/dist/core/runner/write-protection-station.d.ts +8 -2
  205. package/dist/core/runner/write-protection-station.js +2 -0
  206. package/dist/core/runner-deps.d.ts +4 -4
  207. package/dist/core/secret-env.d.ts +4 -0
  208. package/dist/core/secret-env.js +3 -0
  209. package/dist/core/sensitive-path-policy.js +6 -7
  210. package/dist/core/session-log-transfer.d.ts +24 -0
  211. package/dist/core/session-log-transfer.js +166 -0
  212. package/dist/core/session-policy-store.d.ts +7 -2
  213. package/dist/core/session-policy-store.js +1 -1
  214. package/dist/core/session-store.d.ts +84 -19
  215. package/dist/core/session-store.js +162 -24
  216. package/dist/core/session.d.ts +92 -1
  217. package/dist/core/shell-read-silence.js +1 -0
  218. package/dist/core/shell-wrapper-projection.d.ts +1 -1
  219. package/dist/core/steer-replay.d.ts +4 -2
  220. package/dist/core/steer-replay.js +2 -1
  221. package/dist/core/store-contracts/background-agent-store-contract.js +1 -0
  222. package/dist/core/store-contracts/checkpoint-store-contract.js +19 -1
  223. package/dist/core/store-contracts/file-history-store-contract.js +9 -0
  224. package/dist/core/store-contracts/mailbox-store-contract.js +49 -1
  225. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  226. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  227. package/dist/core/store-contracts/session-store-contract.js +236 -2
  228. package/dist/core/task-event.d.ts +68 -8
  229. package/dist/core/task-registry-agent.d.ts +8 -4
  230. package/dist/core/task-registry-agent.js +14 -8
  231. package/dist/core/task-registry-shared.d.ts +36 -6
  232. package/dist/core/task-registry-shared.js +11 -0
  233. package/dist/core/task-registry.d.ts +1 -1
  234. package/dist/core/task-registry.js +1 -1
  235. package/dist/core/task-spec.d.ts +37 -0
  236. package/dist/core/task-stream.d.ts +2 -1
  237. package/dist/core/terminal-cause.d.ts +1 -1
  238. package/dist/core/tool-catalog-entries.d.ts +6 -0
  239. package/dist/core/tool-catalog-entries.js +2 -0
  240. package/dist/core/tool-name-aliases.d.ts +32 -2
  241. package/dist/core/tool-name-aliases.js +23 -0
  242. package/dist/core/tool-name-readings.d.ts +4 -0
  243. package/dist/core/tool-name-readings.js +1 -0
  244. package/dist/core/tool-policy.d.ts +10 -6
  245. package/dist/core/tool-policy.js +4 -7
  246. package/dist/core/tool-result-store.d.ts +17 -10
  247. package/dist/core/tool-result-store.js +3 -1
  248. package/dist/core/trace.d.ts +4 -1
  249. package/dist/core/trace.js +2 -1
  250. package/dist/core/types.d.ts +1 -1
  251. package/dist/core/untrusted-egress.d.ts +18 -0
  252. package/dist/core/untrusted-egress.js +82 -12
  253. package/dist/core/wiring-manifest.d.ts +12 -3
  254. package/dist/core/wiring-manifest.js +4 -3
  255. package/dist/core/workspace-snapshot.d.ts +44 -0
  256. package/dist/core/workspace-snapshot.js +34 -0
  257. package/dist/core/write-protect.d.ts +43 -3
  258. package/dist/core/write-protect.js +43 -16
  259. package/dist/engine/execution-env/node-execution-env.js +15 -11
  260. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  261. package/dist/engine/harness/agent-harness.d.ts +12 -5
  262. package/dist/engine/harness/agent-harness.js +13 -2
  263. package/dist/engine/harness/types.d.ts +48 -7
  264. package/dist/engine/harness/types.js +5 -1
  265. package/dist/engine/llm/types.d.ts +12 -3
  266. package/dist/engine/llm/types.js +1 -1
  267. package/dist/engine/loop/agent-loop.d.ts +1 -4
  268. package/dist/engine/loop/agent-loop.js +26 -4
  269. package/dist/engine/session/import-validate.js +3 -0
  270. package/dist/engine/session/memory-repo.d.ts +17 -9
  271. package/dist/engine/session/memory-repo.js +44 -34
  272. package/dist/engine/session/repo-utils.d.ts +22 -4
  273. package/dist/engine/session/repo-utils.js +49 -1
  274. package/dist/engine/session/storage-base.d.ts +10 -1
  275. package/dist/engine/session/storage-base.js +7 -1
  276. package/dist/index.d.ts +23 -11
  277. package/dist/index.js +15 -6
  278. package/dist/internal/harness-types.d.ts +1 -1
  279. package/dist/internal/harness.d.ts +4 -3
  280. package/dist/internal/harness.js +3 -2
  281. package/dist/stores/file/checkpoint-store.d.ts +0 -4
  282. package/dist/stores/file/checkpoint-store.js +0 -1
  283. package/dist/stores/file/file-history-store.js +12 -4
  284. package/dist/stores/file/index.d.ts +4 -1
  285. package/dist/stores/file/index.js +4 -1
  286. package/dist/stores/file/mailbox-store.d.ts +2 -1
  287. package/dist/stores/file/mailbox-store.js +26 -1
  288. package/dist/stores/file/session-store.d.ts +15 -8
  289. package/dist/stores/file/session-store.js +28 -13
  290. package/dist/tools/fs/bash-readonly-classifier.d.ts +15 -19
  291. package/dist/tools/fs/bash-readonly-classifier.js +5 -10
  292. package/dist/tools/fs/fs-bash.js +10 -3
  293. package/dist/tools/fs/fs-write.d.ts +6 -3
  294. package/dist/tools/fs/fs-write.js +8 -7
  295. package/dist/tools/fs/index.d.ts +3 -0
  296. package/dist/tools/fs/index.js +1 -1
  297. package/dist/tools/fs/pattern-kill-guard.d.ts +3 -2
  298. package/dist/tools/fs/pattern-kill-guard.js +68 -36
  299. package/dist/tools/fs/safety.js +40 -8
  300. package/dist/tools/fs/search.js +6 -24
  301. package/dist/tools/fs/shell-read-check.d.ts +18 -1
  302. package/dist/tools/fs/shell-read-check.js +66 -16
  303. package/dist/tools/fs/shell-read-establish.js +2 -1
  304. package/dist/tools/fs/shell-read-identity.d.ts +12 -9
  305. package/dist/tools/fs/shell-read-identity.js +10 -5
  306. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  307. package/dist/tools/web.js +9 -7
  308. package/dist/tools/worktree.d.ts +42 -15
  309. package/dist/tools/worktree.js +60 -32
  310. package/package.json +4 -2
  311. package/test/export-surface.snapshot.json +141 -3
  312. package/wire-changes/core-stores-sql@7.57.0.json +29 -0
  313. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  314. package/wire-changes/core@7.57.0.json +1487 -0
  315. package/wire-changes/core@7.58.0.json +2188 -0
  316. package/wire-changes/mods-kernel@7.57.0.json +29 -0
  317. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  318. package/wire-changes/primitives@7.57.0.json +245 -0
  319. package/wire-changes/primitives@7.58.0.json +29 -0
@@ -7,6 +7,7 @@ import { NOT_AUTO_ALLOWED, declinedProgramSentence } from "./bash-program-positi
7
7
  import { bashClassifyDefaultAllow } from "./bash-readonly-classifier.js";
8
8
  import { planShellReads } from "./shell-read-plan.js";
9
9
  import { createShellReadEstablisher, establishShellReadsLexically } from "./shell-read-establish.js";
10
+ import { readLandingsOf } from "./shell-read-identity.js";
10
11
  import { declaredReadDenyHomes, homeViewsAt } from "./read-deny-home.js";
11
12
  import { anyOptionWord, programArgs } from "./shell-read-write-targets.js";
12
13
  import { shellReadFaceWords } from "./shell-read-face.js";
@@ -103,12 +104,13 @@ function unplacedOptionsOf(judged) {
103
104
  async function writeGuardsOf(judged, boundary, env, signal) {
104
105
  const judge = boundary.writeTargetJudge;
105
106
  if (judge === undefined)
106
- return { unplaced: false, writeProtected: false };
107
+ return { unplaced: false, writeProtected: false, writeProtectedOnDisk: false };
107
108
  const { runs, concurrent } = runOrderOf(judged);
108
109
  const asKey = new Map();
109
110
  const asSpelling = new Map();
110
111
  const landingKeys = new Set();
111
112
  const writtenBy = runs.map(() => []);
113
+ const targets = [];
112
114
  const add = (into, view, child, at) => {
113
115
  if (!isAbsoluteForFamily(pathFamilyOf({ root: view }), view))
114
116
  return;
@@ -125,10 +127,16 @@ async function writeGuardsOf(judged, boundary, env, signal) {
125
127
  add(key ? asKey : asSpelling, f.read.target, child, at);
126
128
  if (key && written.seat === "landing")
127
129
  landingKeys.add(f.read.target);
128
- if (written.seat === "landing")
129
- 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) {
130
133
  add(asSpelling, spelling, child, at);
134
+ views.push([spelling, false]);
135
+ }
136
+ }
131
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)) });
132
140
  }
133
141
  });
134
142
  const probes = new Map();
@@ -159,20 +167,52 @@ async function writeGuardsOf(judged, boundary, env, signal) {
159
167
  };
160
168
  const answer = async (view, key) => (await judge(view, { fs: env, ...(signal !== undefined ? { signal } : {}), ...(key ? { canonical: true } : {}) })) ?? "clear";
161
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
+ };
162
192
  let unplaced = false;
163
193
  let writeProtected = false;
164
- for (const [view, v, key] of asked) {
165
- if (!(await writable(view, v)) && !changedBefore(view, v.at))
166
- continue;
167
- const found = await answer(view, key);
168
- if (found === "protected")
169
- writeProtected = true;
170
- if (found !== "clear")
171
- unplaced = true;
172
- 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)
173
213
  break;
174
214
  }
175
- return { unplaced, writeProtected };
215
+ return { unplaced, writeProtected, writeProtectedOnDisk };
176
216
  }
177
217
  export function readStationMemberOf(call, members) {
178
218
  return seatOf("fold.readStation", members, call);
@@ -351,13 +391,18 @@ async function runShellReadStation(tool, command, declared, seat, readers, estab
351
391
  };
352
392
  let judged = judgedNow();
353
393
  let judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
354
- 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);
355
395
  judged = judgedNow();
356
396
  judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
357
397
  const unplaced = unplacedOptionsOf(judged);
358
398
  const placed = judgedVerdict.finding !== "unanswered" && writesPlacedOf(judged, boundary);
359
399
  const unresolved = judgedVerdict.disposition !== "refuse" && runOrderOf(judged).runs.some((s) => s.findings.some((f) => f.read.written !== undefined && f.read.unresolved === true));
360
- 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
+ };
361
406
  const verdict = placed && !guarded.unplaced ? { ...facts, writesPlaced: true } : unplaced !== undefined ? { ...facts, unplacedOptions: unplaced } : facts;
362
407
  return { plan, established, judged, boundary, verdict };
363
408
  }
@@ -395,6 +440,7 @@ export function createShellReadStation(opts) {
395
440
  };
396
441
  const admissions = new Map();
397
442
  const remember = (toolCallId, a) => {
443
+ admissions.delete(toolCallId);
398
444
  if (admissions.size >= ADMISSION_MAX) {
399
445
  const oldest = admissions.keys().next().value;
400
446
  if (oldest !== undefined)
@@ -478,5 +524,9 @@ export function createShellReadStation(opts) {
478
524
  const r = refusalOf(toolName, identity, a.boundary, []);
479
525
  return refused(errorResult(r.sentence, containmentDetails(changed.map((c) => c.target).filter((t) => t !== undefined))));
480
526
  };
481
- return { check, admit };
527
+ const landings = (toolCallId) => {
528
+ const a = admissions.get(toolCallId);
529
+ return a !== undefined ? readLandingsOf(a.established) : undefined;
530
+ };
531
+ return { check, admit, landings };
482
532
  }
@@ -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;
@@ -1,18 +1,21 @@
1
- /**
2
- * The pre-spawn identity comparison: which established reads of one plan resolve somewhere else now.
3
- *
4
- * Compared PER CANDIDATE, never as one pooled set of targets: a candidate is keyed by where it stands in the plan
5
- * (segment, nested plan) and by what it is (deny-only or a read, provenance, spelling, expansion, raw word), and its
6
- * set of established targets is compared with the same candidate's set from the re-establishment. A pooled set let
7
- * one candidate's targets hide another's move — `head linkx` retargeted onto a path some other word's pattern already
8
- * matched, or onto a home shadow's target, left the pool unchanged and the call was admitted unjudged.
9
- */
10
1
  import type { EstablishedPlan } from "./shell-read-establish.js";
11
2
  import type { ObservedEnvironment } from "./shell-read-environment.js";
12
3
  import type { EstablishedRead } from "./shell-read-judge.js";
13
4
  import { type HomeViewsCarrier } from "./read-deny-home.js";
14
5
  /** Every read of either establishment whose candidate's settled target set differs between the two. */
15
6
  export declare function movedReads(previous: EstablishedPlan, again: EstablishedPlan): EstablishedRead[];
7
+ /** One read candidate's landing: its key and where it settled, each as a sha256 hex digest (the key's raw tuple joins on
8
+ * NUL and follows the command's length; a pattern lands on up to thousands of entries), with the raw word and the
9
+ * settled targets kept for the sentence that names a moved one. */
10
+ export interface ReadLanding {
11
+ readonly key: string;
12
+ readonly landing: string;
13
+ readonly raw: string;
14
+ readonly targets: readonly string[];
15
+ }
16
+ /** Every read candidate of the establishment (nested plans included) with where it landed, in plan order. A candidate
17
+ * that settled nowhere (a lexical or unestablishable read) lands on the empty set — placed later, that is a move. */
18
+ export declare function readLandingsOf(e: EstablishedPlan): ReadLanding[];
16
19
  /**
17
20
  * The establishment with every read that landed carrying its HOME VIEW (read-deny-home.ts) among its spellings, nested
18
21
  * plans included: the deny judge then places a home-anchored row wherever the target IS below the home, whatever it is
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { homeViewsOf } from "./read-deny-home.js";
2
3
  export function movedReads(previous, again) {
3
4
  const before = targetsByCandidate(previous);
@@ -6,12 +7,19 @@ export function movedReads(previous, again) {
6
7
  for (const key of new Set([...before.keys(), ...after.keys()])) {
7
8
  const b = before.get(key);
8
9
  const a = after.get(key);
9
- if (b !== undefined && a !== undefined && sameTargets(b.targets, a.targets))
10
+ if (b !== undefined && a !== undefined && landingOf(b.targets) === landingOf(a.targets))
10
11
  continue;
11
12
  changed.push(...(b?.reads ?? []), ...(a?.reads ?? []));
12
13
  }
13
14
  return changed.filter((r) => r.target !== undefined);
14
15
  }
16
+ export function readLandingsOf(e) {
17
+ return [...targetsByCandidate(e)].map(([key, l]) => ({ key: digest(key), landing: landingOf(l.targets), raw: l.reads[0]?.candidate.raw ?? "", targets: [...l.targets].sort() }));
18
+ }
19
+ function landingOf(targets) {
20
+ return digest(JSON.stringify([...targets].sort()));
21
+ }
22
+ const digest = (s) => createHash("sha256").update(s, "utf8").digest("hex");
15
23
  function targetsByCandidate(e) {
16
24
  const out = new Map();
17
25
  const walk = (p, at) => {
@@ -35,9 +43,6 @@ function targetsByCandidate(e) {
35
43
  walk(e, "");
36
44
  return out;
37
45
  }
38
- function sameTargets(a, b) {
39
- return a.size === b.size && [...a].every((t) => b.has(t));
40
- }
41
46
  export async function withHomeViews(door, placed, established, signal) {
42
47
  const views = homeViewsOf(door.fs, placed, signal);
43
48
  const unread = [];
@@ -50,7 +55,7 @@ export async function withHomeViews(door, placed, established, signal) {
50
55
  const home = landed ? await views.of(r.target, r.node === "file" ? { leaf: "file" } : undefined) : {};
51
56
  if (home.unread !== undefined && !unread.includes(home.unread))
52
57
  unread.push(home.unread);
53
- 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] });
54
59
  }
55
60
  reads.set(segment, out);
56
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
package/dist/tools/web.js CHANGED
@@ -3,6 +3,7 @@ import { defineTool, errorResult } from "../core/tools.js";
3
3
  import { delimitUntrusted, inlineUntrusted } from "../core/untrusted-text.js";
4
4
  import { discloseReminderShaped, observeReminderMarkEcho } from "../core/reminder-disclosure.js";
5
5
  import { egressThrownText } from "../core/untrusted-egress.js";
6
+ import { remoteWords } from "../core/protocol-http-auth.js";
6
7
  import { fetchFollowing, hopRefusal, HOST_FLOOR_REFUSED_CODE } from "../core/host-floor.js";
7
8
  import { hostOfUrl } from "../core/host-target.js";
8
9
  import { assertNoRetiredKeys } from "../core/retired-keys.js";
@@ -210,12 +211,13 @@ function isPermittedRedirectHop(from, to) {
210
211
  const there = hostOfUrl(to.toString());
211
212
  return "host" in here && "host" in there && here.host === there.host;
212
213
  }
214
+ const reasonPhrase = (res) => remoteWords(res.statusText, []);
213
215
  async function fetchUnderFloor(doFetch, start, floor, userAgent, signal, onResponse) {
214
216
  const out = await fetchFollowing(doFetch, start, { method: "GET", headers: { Accept: WEBFETCH_ACCEPT, "User-Agent": userAgent }, ...(signal !== undefined ? { signal } : {}) }, {
215
217
  refusal: (url) => hopRefusal(url, floor, true),
216
218
  follows: isPermittedRedirectHop,
217
219
  maxRedirects: MAX_REDIRECTS,
218
- onResponse: (res) => onResponse?.(res.status, res.statusText),
220
+ onResponse: (res) => onResponse?.(res.status, reasonPhrase(res)),
219
221
  });
220
222
  switch (out.kind) {
221
223
  case "answered":
@@ -328,7 +330,7 @@ export function webFetchToolSpec(config = {}) {
328
330
  return failure(`Error (WebFetch): ${fr.error}`, connectedMeta ? { code: connectedMeta.status, codeText: connectedMeta.statusText } : {});
329
331
  }
330
332
  res = fr.res;
331
- connectedMeta = { status: res.status, statusText: res.statusText };
333
+ connectedMeta = { status: res.status, statusText: reasonPhrase(res) };
332
334
  finalResponse = true;
333
335
  const stream = res.body;
334
336
  if (stream && typeof stream.getReader === "function") {
@@ -449,7 +451,7 @@ export function webFetchToolSpec(config = {}) {
449
451
  : {}),
450
452
  };
451
453
  if (!res.ok) {
452
- const headline = `Error (WebFetch): HTTP ${res.status} ${res.statusText} for ${parsed.toString()}`;
454
+ const headline = `Error (WebFetch): HTTP ${res.status} ${reasonPhrase(res)} for ${parsed.toString()}`;
453
455
  const looksBinary = bodyBytes !== undefined && sniffBinarySignature(bodyBytes) !== undefined;
454
456
  const errText = looksBinary
455
457
  ? ""
@@ -476,7 +478,7 @@ export function webFetchToolSpec(config = {}) {
476
478
  type: "web-fetch",
477
479
  url: parsed.toString(),
478
480
  code: res.status,
479
- codeText: res.statusText,
481
+ codeText: reasonPhrase(res),
480
482
  bytes: bodyBytes ? bodyBytes.length : raw.length,
481
483
  durationMs: Date.now() - startedAt,
482
484
  ...transferStateDetails,
@@ -508,7 +510,7 @@ export function webFetchToolSpec(config = {}) {
508
510
  type: "web-fetch",
509
511
  url: parsed.toString(),
510
512
  code: res.status,
511
- codeText: res.statusText,
513
+ codeText: reasonPhrase(res),
512
514
  bytes: bodyBytes.length,
513
515
  durationMs: Date.now() - startedAt,
514
516
  ...transferStateDetails,
@@ -634,7 +636,7 @@ export function webFetchToolSpec(config = {}) {
634
636
  type: "web-fetch",
635
637
  url: parsed.toString(),
636
638
  code: res.status,
637
- codeText: res.statusText,
639
+ codeText: reasonPhrase(res),
638
640
  bytes: bodyBytes ? bodyBytes.length : raw.length,
639
641
  result: out.length > RESULT_PREVIEW_CHARS ? `${out.slice(0, RESULT_PREVIEW_CHARS)}\n…[${out.length - RESULT_PREVIEW_CHARS} chars truncated — full text in the tool output]` : out,
640
642
  durationMs: Date.now() - startedAt,
@@ -990,7 +992,7 @@ export function createSearxngSearchBackend(baseUrl, options = {}) {
990
992
  throw new Error(`SearXNG was redirected more than ${SEARXNG_MAX_REDIRECTS} times`);
991
993
  const res = followed.res;
992
994
  if (!res.ok)
993
- throw new Error(`SearXNG ${res.status} ${res.statusText} from ${url.origin}${url.pathname}`);
995
+ throw new Error(`SearXNG ${res.status} ${reasonPhrase(res)} from ${url.origin}${url.pathname}`);
994
996
  const body = (await res.json());
995
997
  if (!Array.isArray(body.results))
996
998
  throw new Error(`SearXNG returned no results array from ${url.origin}${url.pathname} — is format=json enabled on this instance?`);
@@ -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
  }