@sema-agent/core 7.67.3 → 7.68.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (501) hide show
  1. package/CHANGELOG.md +1537 -0
  2. package/README.md +18 -9
  3. package/README.zh-CN.md +16 -8
  4. package/dist/agents/agent-definition.d.ts +1 -1
  5. package/dist/agents/agent-definition.js +4 -1
  6. package/dist/agents/cascade.d.ts +2 -2
  7. package/dist/agents/cascade.js +3 -1
  8. package/dist/agents/cumulative-stats.d.ts +2 -1
  9. package/dist/agents/cumulative-stats.js +4 -1
  10. package/dist/agents/list-agents-tool.d.ts +30 -0
  11. package/dist/agents/list-agents-tool.js +45 -3
  12. package/dist/agents/peer-admission.d.ts +2 -2
  13. package/dist/agents/peer-session-drain.d.ts +2 -0
  14. package/dist/agents/peer-session-drain.js +1 -0
  15. package/dist/agents/repair-loop.js +3 -1
  16. package/dist/agents/retain-ledger.d.ts +61 -8
  17. package/dist/agents/retain-ledger.js +25 -3
  18. package/dist/agents/roster-store.d.ts +4 -2
  19. package/dist/agents/send-message-tool.d.ts +1 -1
  20. package/dist/agents/send-message-tool.js +20 -15
  21. package/dist/agents/subagent-steps.js +2 -10
  22. package/dist/agents/subagent.d.ts +3 -0
  23. package/dist/agents/subagent.js +106 -76
  24. package/dist/agents/tool-filter.d.ts +20 -11
  25. package/dist/agents/tool-filter.js +8 -4
  26. package/dist/agents/verify.d.ts +3 -1
  27. package/dist/agents/verify.js +2 -0
  28. package/dist/brain/anthropic.js +4 -4
  29. package/dist/brain/open-responses.js +3 -1
  30. package/dist/brain/openai.js +3 -1
  31. package/dist/brain/reasoning-request.d.ts +73 -19
  32. package/dist/brain/reasoning-request.js +164 -72
  33. package/dist/brain/reasoning-stamp.d.ts +26 -0
  34. package/dist/brain/reasoning-stamp.js +10 -0
  35. package/dist/brain/reasoning.d.ts +95 -162
  36. package/dist/brain/reasoning.js +31 -86
  37. package/dist/brain/route-adjudicator.d.ts +9 -7
  38. package/dist/brain/route-adjudicator.js +12 -10
  39. package/dist/brain/status-sink.d.ts +19 -64
  40. package/dist/brain/status-sink.js +5 -21
  41. package/dist/brain/stream-engine.d.ts +11 -2
  42. package/dist/brain/stream-engine.js +10 -0
  43. package/dist/core/a2a.d.ts +17 -5
  44. package/dist/core/a2a.js +11 -3
  45. package/dist/core/allow-entry.d.ts +35 -15
  46. package/dist/core/allow-entry.js +47 -60
  47. package/dist/core/ask-headline.d.ts +68 -0
  48. package/dist/core/ask-headline.js +23 -0
  49. package/dist/core/ask-origin.d.ts +36 -8
  50. package/dist/core/ask-origin.js +17 -10
  51. package/dist/core/ask-question.d.ts +34 -7
  52. package/dist/core/ask-question.js +10 -1
  53. package/dist/core/ask-unresolvable-notice.d.ts +7 -0
  54. package/dist/core/ask-unresolvable-notice.js +9 -3
  55. package/dist/core/auto-strip.d.ts +53 -0
  56. package/dist/core/auto-strip.js +76 -0
  57. package/dist/core/background-agent-store.d.ts +45 -5
  58. package/dist/core/background-agent-store.js +69 -15
  59. package/dist/core/background-shell.d.ts +2 -2
  60. package/dist/core/caller-text.js +2 -2
  61. package/dist/core/canonical-json.d.ts +13 -0
  62. package/dist/core/canonical-json.js +7 -0
  63. package/dist/core/checkpoint-features.d.ts +66 -20
  64. package/dist/core/checkpoint-features.js +12 -1
  65. package/dist/core/checkpoint-generation.d.ts +1 -1
  66. package/dist/core/checkpoint-queries.d.ts +1 -1
  67. package/dist/core/checkpoint-queries.js +4 -1
  68. package/dist/core/checkpoint-requirements.d.ts +45 -2
  69. package/dist/core/checkpoint-requirements.js +16 -6
  70. package/dist/core/checkpoint-row-verdict.d.ts +1 -0
  71. package/dist/core/checkpoint-row-verdict.js +4 -0
  72. package/dist/core/checkpoint-store.d.ts +66 -38
  73. package/dist/core/checkpoint-store.js +15 -6
  74. package/dist/core/child-clamp-seats.d.ts +6 -0
  75. package/dist/core/child-clamp-seats.js +1 -0
  76. package/dist/core/config-refusal-codes.d.ts +1 -1
  77. package/dist/core/config-refusal-codes.js +1 -0
  78. package/dist/core/delegation-frames.d.ts +9 -12
  79. package/dist/core/delegation-frames.js +9 -8
  80. package/dist/core/engine-capabilities.d.ts +21 -8
  81. package/dist/core/engine-capabilities.js +1 -1
  82. package/dist/core/engine-notice.d.ts +147 -34
  83. package/dist/core/engine-notice.js +27 -16
  84. package/dist/core/engine-storage-backend.d.ts +2 -1
  85. package/dist/core/env-budget.js +3 -3
  86. package/dist/core/env-knob-announce.d.ts +10 -10
  87. package/dist/core/env-knob-announce.js +3 -6
  88. package/dist/core/file-history-store.d.ts +29 -4
  89. package/dist/core/file-history-store.js +13 -0
  90. package/dist/core/frame-settlement.d.ts +2 -1
  91. package/dist/core/gate-fold.js +1 -1
  92. package/dist/core/gate-lanes.js +56 -49
  93. package/dist/core/governance-codes.d.ts +39 -3
  94. package/dist/core/governance-codes.js +61 -3
  95. package/dist/core/hooks.d.ts +29 -11
  96. package/dist/core/hooks.js +5 -2
  97. package/dist/core/human-input-projection.js +3 -3
  98. package/dist/core/input-author.d.ts +17 -3
  99. package/dist/core/input-author.js +15 -3
  100. package/dist/core/leg-identity.d.ts +10 -28
  101. package/dist/core/leg-identity.js +1 -21
  102. package/dist/core/lsp.d.ts +18 -13
  103. package/dist/core/lsp.js +30 -22
  104. package/dist/core/mailbox-store.d.ts +1 -1
  105. package/dist/core/mailbox-store.js +4 -4
  106. package/dist/core/mcp-connection-pool.d.ts +93 -4
  107. package/dist/core/mcp-connection-pool.js +104 -1
  108. package/dist/core/mcp-failure.d.ts +38 -12
  109. package/dist/core/mcp-failure.js +9 -13
  110. package/dist/core/mcp-probe.d.ts +4 -3
  111. package/dist/core/mcp-server-link.d.ts +4 -2
  112. package/dist/core/mcp-server-link.js +4 -5
  113. package/dist/core/mcp-server-spec.d.ts +3 -3
  114. package/dist/core/mcp-server-unavailable-notice.d.ts +22 -8
  115. package/dist/core/mcp-server-unavailable-notice.js +18 -4
  116. package/dist/core/mcp.d.ts +40 -6
  117. package/dist/core/mcp.js +39 -13
  118. package/dist/core/memory-engine/content-origin.js +2 -2
  119. package/dist/core/memory-engine/control-objects.d.ts +2 -4
  120. package/dist/core/memory-engine/control-objects.js +2 -10
  121. package/dist/core/memory-engine/delegation-settlement.js +6 -1
  122. package/dist/core/memory-engine/dual-root.js +3 -0
  123. package/dist/core/memory-engine/engine.d.ts +6 -4
  124. package/dist/core/memory-engine/engine.js +32 -29
  125. package/dist/core/memory-engine/file-backend.d.ts +20 -5
  126. package/dist/core/memory-engine/file-backend.js +21 -31
  127. package/dist/core/memory-engine/frontmatter.d.ts +2 -0
  128. package/dist/core/memory-engine/frontmatter.js +4 -0
  129. package/dist/core/memory-engine/layout.d.ts +114 -20
  130. package/dist/core/memory-engine/layout.js +340 -22
  131. package/dist/core/memory-engine/memory-deployment.d.ts +7 -5
  132. package/dist/core/memory-engine/mount-failed-notice.d.ts +19 -7
  133. package/dist/core/memory-engine/mount-failed-notice.js +43 -10
  134. package/dist/core/memory-engine/sync-client.js +4 -5
  135. package/dist/core/model-fallbacks.d.ts +5 -1
  136. package/dist/core/model-fallbacks.js +3 -3
  137. package/dist/core/model-receipt.d.ts +2 -1
  138. package/dist/core/model-receipt.js +12 -1
  139. package/dist/core/mods/kernel/dispatch.d.ts +2 -2
  140. package/dist/core/mods/kernel/dispatch.js +14 -6
  141. package/dist/core/mods/kernel/events.d.ts +8 -5
  142. package/dist/core/mods/kernel/events.js +2 -2
  143. package/dist/core/mods/kernel/index.d.ts +1 -1
  144. package/dist/core/mods/kernel/registration.d.ts +9 -0
  145. package/dist/core/mods/package.js +1 -1
  146. package/dist/core/mods/session-append.d.ts +4 -2
  147. package/dist/core/mods/session-append.js +3 -0
  148. package/dist/core/mods/stations.d.ts +7 -11
  149. package/dist/core/mods/stations.js +4 -7
  150. package/dist/core/mods/tool-call.d.ts +10 -8
  151. package/dist/core/mods/tool-call.js +15 -18
  152. package/dist/core/mounted-mcp.d.ts +0 -4
  153. package/dist/core/mounted-mcp.js +1 -1
  154. package/dist/core/park-noun.d.ts +24 -0
  155. package/dist/core/park-noun.js +21 -0
  156. package/dist/core/park-resumability.d.ts +60 -0
  157. package/dist/core/park-resumability.js +30 -0
  158. package/dist/core/permission-rule-provider.d.ts +24 -2
  159. package/dist/core/permission-rule-provider.js +11 -8
  160. package/dist/core/permission-rule-store.d.ts +8 -1
  161. package/dist/core/permission-rule-store.js +2 -3
  162. package/dist/core/permission-rules.d.ts +2 -1
  163. package/dist/core/permission-rules.js +8 -4
  164. package/dist/core/persisted-rule-arms.d.ts +3 -0
  165. package/dist/core/persisted-rule-arms.js +2 -1
  166. package/dist/core/present-plan-tool.d.ts +47 -3
  167. package/dist/core/present-plan-tool.js +62 -4
  168. package/dist/core/principal-name.d.ts +1 -1
  169. package/dist/core/principal-name.js +5 -5
  170. package/dist/core/process-identity.js +10 -5
  171. package/dist/core/protocol-http-auth.d.ts +20 -14
  172. package/dist/core/protocol-http-auth.js +70 -50
  173. package/dist/core/read-only-shell.js +9 -5
  174. package/dist/core/redaction-marks.d.ts +4 -26
  175. package/dist/core/redaction-marks.js +9 -21
  176. package/dist/core/remote-env.d.ts +43 -16
  177. package/dist/core/remote-env.js +1 -1
  178. package/dist/core/request-copy-projection.d.ts +1 -1
  179. package/dist/core/request-copy-projection.js +40 -50
  180. package/dist/core/resume-config-judge.js +1 -1
  181. package/dist/core/resume-startup-cause.d.ts +35 -18
  182. package/dist/core/resume-startup-cause.js +13 -10
  183. package/dist/core/retention.d.ts +167 -25
  184. package/dist/core/retention.js +100 -20
  185. package/dist/core/roles.d.ts +6 -0
  186. package/dist/core/roles.js +11 -5
  187. package/dist/core/rule-lane-reads.d.ts +3 -0
  188. package/dist/core/rule-lane-reads.js +5 -1
  189. package/dist/core/rule-store-fault.d.ts +70 -0
  190. package/dist/core/rule-store-fault.js +102 -0
  191. package/dist/core/runner/advertised-writable-dirs.js +16 -31
  192. package/dist/core/runner/announce-once-ledger.d.ts +19 -2
  193. package/dist/core/runner/announce-once-ledger.js +24 -2
  194. package/dist/core/runner/assemble-result.d.ts +6 -0
  195. package/dist/core/runner/assemble-result.js +1 -1
  196. package/dist/core/runner/auto-strip-notice.d.ts +36 -0
  197. package/dist/core/runner/auto-strip-notice.js +59 -0
  198. package/dist/core/runner/branch-window.d.ts +3 -0
  199. package/dist/core/runner/branch-window.js +37 -0
  200. package/dist/core/runner/caller-roster.d.ts +8 -3
  201. package/dist/core/runner/capability-withheld-seat.js +3 -9
  202. package/dist/core/runner/clock-and-limits.d.ts +22 -1
  203. package/dist/core/runner/clock-and-limits.js +30 -0
  204. package/dist/core/runner/contracts.d.ts +58 -35
  205. package/dist/core/runner/credential-refusal-seat.d.ts +2 -0
  206. package/dist/core/runner/credential-refusal-seat.js +47 -0
  207. package/dist/core/runner/cross-boundary-lane.js +6 -4
  208. package/dist/core/runner/decide-continuation.js +1 -1
  209. package/dist/core/runner/file-history-restore.d.ts +53 -2
  210. package/dist/core/runner/file-history-restore.js +29 -10
  211. package/dist/core/runner/forward-sink.d.ts +14 -1
  212. package/dist/core/runner/forward-sink.js +14 -12
  213. package/dist/core/runner/gate-exit.d.ts +8 -7
  214. package/dist/core/runner/gate-exit.js +13 -13
  215. package/dist/core/runner/git-status-frame.js +2 -4
  216. package/dist/core/runner/initial-run-state.js +1 -1
  217. package/dist/core/runner/main-call-account.d.ts +3 -1
  218. package/dist/core/runner/main-call-account.js +5 -3
  219. package/dist/core/runner/mcp-redial.d.ts +2 -5
  220. package/dist/core/runner/mcp-redial.js +2 -2
  221. package/dist/core/runner/nested-memory-content.d.ts +7 -1
  222. package/dist/core/runner/nested-memory-content.js +73 -13
  223. package/dist/core/runner/nested-memory-lane.d.ts +44 -19
  224. package/dist/core/runner/nested-memory-lane.js +152 -76
  225. package/dist/core/runner/park-commit.js +3 -1
  226. package/dist/core/runner/permission-rule-lanes.d.ts +8 -2
  227. package/dist/core/runner/permission-rule-lanes.js +29 -3
  228. package/dist/core/runner/person-path-rows.d.ts +3 -11
  229. package/dist/core/runner/person-path-rows.js +21 -24
  230. package/dist/core/runner/prepare-acquire-reconcile.js +3 -1
  231. package/dist/core/runner/prepare-artifact.d.ts +1 -1
  232. package/dist/core/runner/prepare-artifact.js +20 -14
  233. package/dist/core/runner/prepare-ask-lane.d.ts +9 -6
  234. package/dist/core/runner/prepare-ask-lane.js +6 -5
  235. package/dist/core/runner/prepare-boundary-parks.d.ts +7 -1
  236. package/dist/core/runner/prepare-boundary-parks.js +27 -24
  237. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -2
  238. package/dist/core/runner/prepare-caps-and-workflow.js +4 -3
  239. package/dist/core/runner/prepare-config-doors.d.ts +9 -24
  240. package/dist/core/runner/prepare-config-doors.js +58 -41
  241. package/dist/core/runner/prepare-context-lane.d.ts +2 -2
  242. package/dist/core/runner/prepare-context-lane.js +3 -5
  243. package/dist/core/runner/prepare-defer-classify.d.ts +1 -1
  244. package/dist/core/runner/prepare-defer-classify.js +1 -1
  245. package/dist/core/runner/prepare-delegation-surface.d.ts +2 -2
  246. package/dist/core/runner/prepare-delegation-surface.js +3 -2
  247. package/dist/core/runner/prepare-file-history.d.ts +62 -26
  248. package/dist/core/runner/prepare-file-history.js +117 -46
  249. package/dist/core/runner/prepare-gate-stations.d.ts +4 -0
  250. package/dist/core/runner/prepare-gate-stations.js +6 -5
  251. package/dist/core/runner/prepare-hands-readface.d.ts +9 -4
  252. package/dist/core/runner/prepare-hands-readface.js +8 -4
  253. package/dist/core/runner/prepare-inherited-gate.d.ts +11 -4
  254. package/dist/core/runner/prepare-inherited-gate.js +6 -6
  255. package/dist/core/runner/prepare-listings.d.ts +1 -1
  256. package/dist/core/runner/prepare-listings.js +1 -1
  257. package/dist/core/runner/prepare-memory.js +2 -2
  258. package/dist/core/runner/prepare-offload-wrappers.d.ts +1 -1
  259. package/dist/core/runner/prepare-offload-wrappers.js +1 -1
  260. package/dist/core/runner/prepare-park-ask.d.ts +10 -3
  261. package/dist/core/runner/prepare-park-ask.js +7 -9
  262. package/dist/core/runner/prepare-policy-chain.d.ts +18 -9
  263. package/dist/core/runner/prepare-policy-chain.js +18 -13
  264. package/dist/core/runner/prepare-project-context.d.ts +1 -1
  265. package/dist/core/runner/prepare-project-context.js +5 -3
  266. package/dist/core/runner/prepare-prompt-assembly.js +2 -1
  267. package/dist/core/runner/prepare-prompt-inputs.d.ts +2 -2
  268. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  269. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -5
  270. package/dist/core/runner/prepare-protocol-tools.js +7 -7
  271. package/dist/core/runner/prepare-question-face.d.ts +4 -2
  272. package/dist/core/runner/prepare-run-refs.d.ts +7 -2
  273. package/dist/core/runner/prepare-run-refs.js +8 -7
  274. package/dist/core/runner/prepare-safety-scan.d.ts +4 -3
  275. package/dist/core/runner/prepare-suspend-saga.d.ts +3 -7
  276. package/dist/core/runner/prepare-suspend-saga.js +4 -3
  277. package/dist/core/runner/prepare-task.js +66 -53
  278. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +3 -2
  279. package/dist/core/runner/prepare-tool-disclosure-mount.js +2 -1
  280. package/dist/core/runner/prepare-turn-wiring.d.ts +3 -1
  281. package/dist/core/runner/prepare-turn-wiring.js +1 -1
  282. package/dist/core/runner/prepare-wiring-manifest.d.ts +9 -4
  283. package/dist/core/runner/prepare-wiring-manifest.js +14 -6
  284. package/dist/core/runner/prepare-workspace-restore.d.ts +4 -4
  285. package/dist/core/runner/prepare-workspace-restore.js +15 -6
  286. package/dist/core/runner/remote-env-retry.d.ts +3 -3
  287. package/dist/core/runner/restore-seat.d.ts +41 -0
  288. package/dist/core/runner/restore-seat.js +38 -0
  289. package/dist/core/runner/resume-admission.js +1 -1
  290. package/dist/core/runner/resume-apply.js +4 -3
  291. package/dist/core/runner/resume-checkpoint-screen.js +2 -1
  292. package/dist/core/runner/resume-internals-and-config.js +2 -1
  293. package/dist/core/runner/resume-preflight.js +2 -1
  294. package/dist/core/runner/rewind-files.js +22 -6
  295. package/dist/core/runner/rule-store-unreadable-notice.d.ts +8 -0
  296. package/dist/core/runner/rule-store-unreadable-notice.js +11 -0
  297. package/dist/core/runner/run-brain-sinks.d.ts +3 -6
  298. package/dist/core/runner/run-brain-sinks.js +6 -6
  299. package/dist/core/runner/run-compaction-machinery.d.ts +2 -2
  300. package/dist/core/runner/run-git-lane.d.ts +2 -0
  301. package/dist/core/runner/run-git-lane.js +2 -1
  302. package/dist/core/runner/run-harness-handlers.js +5 -4
  303. package/dist/core/runner/run-identity-wiring.js +20 -12
  304. package/dist/core/runner/run-leg.js +31 -72
  305. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  306. package/dist/core/runner/run-notification-lane.js +2 -4
  307. package/dist/core/runner/run-reasoning-seat.d.ts +5 -6
  308. package/dist/core/runner/run-reasoning-seat.js +13 -18
  309. package/dist/core/runner/run-settle-and-teardown.js +13 -9
  310. package/dist/core/runner/run-terminal-adoption.js +4 -8
  311. package/dist/core/runner/run-turn-boundary.js +6 -3
  312. package/dist/core/runner/runtask.d.ts +9 -4
  313. package/dist/core/runner/runtask.js +29 -22
  314. package/dist/core/runner/session-rule-policy.d.ts +11 -1
  315. package/dist/core/runner/shell-env-withheld.js +2 -7
  316. package/dist/core/runner/side-call-account.d.ts +5 -6
  317. package/dist/core/runner/side-call-account.js +2 -2
  318. package/dist/core/runner/stream-lifecycle-verbs.d.ts +3 -0
  319. package/dist/core/runner/stream-lifecycle-verbs.js +5 -3
  320. package/dist/core/runner/stream-settle-backstop.js +4 -6
  321. package/dist/core/runner/stream-steer-verb.d.ts +1 -1
  322. package/dist/core/runner/stream-steer-verb.js +4 -4
  323. package/dist/core/runner/sub-agent-deny-lists.d.ts +8 -3
  324. package/dist/core/runner/sub-agent-deny-lists.js +7 -4
  325. package/dist/core/runner/teardown-bounded.d.ts +7 -0
  326. package/dist/core/runner/teardown-bounded.js +7 -0
  327. package/dist/core/runner/terminal-account.js +41 -13
  328. package/dist/core/runner/terminal-projection.d.ts +1 -5
  329. package/dist/core/runner/tool-end-body.d.ts +9 -3
  330. package/dist/core/runner/tool-end-body.js +6 -3
  331. package/dist/core/runner/tool-output-projection.d.ts +13 -4
  332. package/dist/core/runner/tool-output-projection.js +10 -14
  333. package/dist/core/runner/turn-attachments.d.ts +3 -2
  334. package/dist/core/runner/turn-attachments.js +12 -5
  335. package/dist/core/runner-deps.d.ts +6 -6
  336. package/dist/core/runtime-caps.d.ts +2 -1
  337. package/dist/core/secret-env.d.ts +20 -3
  338. package/dist/core/secret-env.js +13 -15
  339. package/dist/core/session-checkout.d.ts +115 -15
  340. package/dist/core/session-checkout.js +435 -136
  341. package/dist/core/session-policy-store.js +21 -3
  342. package/dist/core/session-reconcile.js +1 -0
  343. package/dist/core/session-store.js +2 -0
  344. package/dist/core/session.d.ts +11 -1
  345. package/dist/core/shell-run-candidates.d.ts +1 -0
  346. package/dist/core/shell-run-candidates.js +1 -1
  347. package/dist/core/shutdown-debug.d.ts +6 -5
  348. package/dist/core/shutdown-debug.js +5 -1
  349. package/dist/core/skill-grant.js +4 -1
  350. package/dist/core/skills-directory.js +5 -3
  351. package/dist/core/spec-contract.d.ts +1 -1
  352. package/dist/core/store-contracts/checkpoint-store-contract.js +2 -7
  353. package/dist/core/store-contracts/file-history-store-contract.js +26 -2
  354. package/dist/core/store-contracts/session-deletion-cascade-contract.js +130 -14
  355. package/dist/core/store-contracts/task-list-store-contract.d.ts +2 -1
  356. package/dist/core/store-contracts/task-list-store-contract.js +28 -1
  357. package/dist/core/task-event.d.ts +48 -27
  358. package/dist/core/task-notification.d.ts +15 -9
  359. package/dist/core/task-notification.js +12 -0
  360. package/dist/core/task-registry-agent.d.ts +24 -22
  361. package/dist/core/task-registry-agent.js +65 -46
  362. package/dist/core/task-registry-shared.d.ts +17 -5
  363. package/dist/core/task-registry.d.ts +17 -6
  364. package/dist/core/task-registry.js +6 -1
  365. package/dist/core/task-result.d.ts +71 -25
  366. package/dist/core/task-spec-members.d.ts +0 -1
  367. package/dist/core/task-spec-members.js +1 -1
  368. package/dist/core/task-spec.d.ts +60 -52
  369. package/dist/core/task-stream.d.ts +45 -12
  370. package/dist/core/terminal-cause.d.ts +45 -8
  371. package/dist/core/terminal-cause.js +5 -0
  372. package/dist/core/tool-card-bound.d.ts +32 -0
  373. package/dist/core/tool-card-bound.js +33 -0
  374. package/dist/core/tool-catalog-entries.d.ts +9 -0
  375. package/dist/core/tool-catalog-entries.js +48 -0
  376. package/dist/core/tool-errors.d.ts +4 -3
  377. package/dist/core/tool-face.d.ts +3 -3
  378. package/dist/core/tool-mount-facts.d.ts +3 -2
  379. package/dist/core/tool-mount-facts.js +1 -1
  380. package/dist/core/tool-mount-static.js +7 -5
  381. package/dist/core/tool-policy.d.ts +21 -19
  382. package/dist/core/tool-policy.js +5 -6
  383. package/dist/core/tool-registry.d.ts +3 -1
  384. package/dist/core/tool-registry.js +15 -1
  385. package/dist/core/tool-result-store.d.ts +9 -3
  386. package/dist/core/tool-result-store.js +14 -1
  387. package/dist/core/tool-roster.d.ts +18 -0
  388. package/dist/core/tool-roster.js +30 -1
  389. package/dist/core/tool-spec.d.ts +17 -8
  390. package/dist/core/trace.d.ts +35 -31
  391. package/dist/core/types.d.ts +2 -2
  392. package/dist/core/untrusted-egress.d.ts +10 -9
  393. package/dist/core/untrusted-egress.js +9 -9
  394. package/dist/core/untrusted-text.d.ts +0 -18
  395. package/dist/core/untrusted-text.js +7 -3
  396. package/dist/core/user-attachment.d.ts +9 -6
  397. package/dist/core/user-attachment.js +12 -10
  398. package/dist/core/user-row-origin.d.ts +44 -25
  399. package/dist/core/user-row-origin.js +30 -20
  400. package/dist/core/wiring-manifest.d.ts +26 -7
  401. package/dist/core/wiring-manifest.js +14 -11
  402. package/dist/core/workspace-snapshot.d.ts +3 -1
  403. package/dist/core/workspace-snapshot.js +1 -0
  404. package/dist/engine/execution-env/node-execution-env.d.ts +23 -16
  405. package/dist/engine/execution-env/node-execution-env.js +127 -67
  406. package/dist/engine/harness/agent-harness.d.ts +4 -5
  407. package/dist/engine/harness/agent-harness.js +2 -7
  408. package/dist/engine/harness/types.d.ts +51 -19
  409. package/dist/engine/harness/types.js +28 -1
  410. package/dist/engine/llm/types.d.ts +26 -14
  411. package/dist/engine/llm/types.js +2 -2
  412. package/dist/engine/loop/agent-loop.d.ts +2 -2
  413. package/dist/engine/loop/agent-loop.js +51 -275
  414. package/dist/engine/loop/types.d.ts +0 -18
  415. package/dist/engine/session/import-validate.d.ts +3 -0
  416. package/dist/engine/session/import-validate.js +34 -2
  417. package/dist/engine/session/repo-utils.d.ts +42 -4
  418. package/dist/engine/session/repo-utils.js +33 -5
  419. package/dist/engine/session/session.d.ts +41 -14
  420. package/dist/engine/session/session.js +96 -25
  421. package/dist/index.d.ts +21 -16
  422. package/dist/index.js +16 -10
  423. package/dist/orchestration/run-spec.d.ts +1 -1
  424. package/dist/orchestration/run-workflow-tool.d.ts +12 -9
  425. package/dist/orchestration/run-workflow-tool.js +15 -19
  426. package/dist/orchestration/workflow-governance.js +13 -21
  427. package/dist/orchestration/workflow-observe.d.ts +4 -3
  428. package/dist/orchestration/workflow-primitives.d.ts +1 -1
  429. package/dist/orchestration/workflow-record-artifact.d.ts +14 -0
  430. package/dist/orchestration/workflow-record-artifact.js +32 -0
  431. package/dist/orchestration/workflow-script-store.d.ts +9 -0
  432. package/dist/orchestration/workflow-script-store.js +20 -1
  433. package/dist/orchestration/workflow-types.d.ts +33 -3
  434. package/dist/orchestration/workflow.d.ts +24 -14
  435. package/dist/orchestration/workflow.js +52 -23
  436. package/dist/prompt-assembly/artifact.js +4 -8
  437. package/dist/prompt-assembly/catalog/engine.d.ts +263 -0
  438. package/dist/prompt-assembly/catalog/engine.js +30 -0
  439. package/dist/prompt-assembly/catalog/index.d.ts +1 -1
  440. package/dist/prompt-assembly/catalog/index.js +2 -2
  441. package/dist/prompt-assembly/catalog/locales/zh-Hans/engine.d.ts +1 -1
  442. package/dist/prompt-assembly/catalog/locales/zh-Hans/engine.js +29 -0
  443. package/dist/prompt-assembly/epoch.js +6 -8
  444. package/dist/prompt-assembly/turn-snapshot.js +8 -9
  445. package/dist/stores/file/background-agent-store.js +5 -6
  446. package/dist/stores/file/checkpoint-store.d.ts +0 -4
  447. package/dist/stores/file/checkpoint-store.js +7 -3
  448. package/dist/stores/file/file-history-store.d.ts +8 -0
  449. package/dist/stores/file/file-history-store.js +72 -0
  450. package/dist/stores/file/fs-atomic.js +17 -12
  451. package/dist/stores/file/index.js +11 -5
  452. package/dist/stores/file/mailbox-store.js +13 -4
  453. package/dist/stores/file/permission-rule-store.js +14 -13
  454. package/dist/stores/file/shared-ledger.d.ts +4 -0
  455. package/dist/stores/file/shared-ledger.js +4 -0
  456. package/dist/stores/file/task-list-store.js +12 -3
  457. package/dist/stores/file/workflow-run-store.js +1 -0
  458. package/dist/tools/fs/bash-program-position.d.ts +4 -2
  459. package/dist/tools/fs/bash-program-position.js +1 -1
  460. package/dist/tools/fs/bash-readonly-classifier.js +1 -1
  461. package/dist/tools/fs/bound-open.d.ts +97 -0
  462. package/dist/tools/fs/bound-open.js +103 -0
  463. package/dist/tools/fs/containment-face.d.ts +2 -2
  464. package/dist/tools/fs/fs-pdf.d.ts +7 -1
  465. package/dist/tools/fs/fs-pdf.js +31 -23
  466. package/dist/tools/fs/fs-read.d.ts +24 -17
  467. package/dist/tools/fs/fs-read.js +84 -53
  468. package/dist/tools/fs/fs-shared.d.ts +14 -12
  469. package/dist/tools/fs/fs-shared.js +5 -4
  470. package/dist/tools/fs/fs-write.d.ts +2 -2
  471. package/dist/tools/fs/fs-write.js +20 -12
  472. package/dist/tools/fs/index.d.ts +4 -4
  473. package/dist/tools/fs/index.js +2 -2
  474. package/dist/tools/fs/notebook.d.ts +1 -1
  475. package/dist/tools/fs/pdf.d.ts +12 -3
  476. package/dist/tools/fs/pdf.js +22 -9
  477. package/dist/tools/fs/read-deny-home.d.ts +3 -2
  478. package/dist/tools/fs/read-deny-home.js +8 -11
  479. package/dist/tools/fs/safety.d.ts +3 -2
  480. package/dist/tools/fs/shell-read-check.js +10 -9
  481. package/dist/tools/monitor.d.ts +6 -5
  482. package/dist/tools/task-list.d.ts +16 -6
  483. package/dist/tools/task-list.js +4 -0
  484. package/dist/tools/web.d.ts +9 -1
  485. package/dist/tools/web.js +8 -3
  486. package/dist/tools/worktree.d.ts +7 -5
  487. package/dist/tools/worktree.js +4 -3
  488. package/package.json +4 -3
  489. package/test/export-surface.snapshot.json +93 -7
  490. package/wire-changes/core-stores-sql@7.68.0.json +39 -0
  491. package/wire-changes/core-stores-sql@7.68.1.json +39 -0
  492. package/wire-changes/core@7.68.0.json +4257 -0
  493. package/wire-changes/core@7.68.1.json +95 -0
  494. package/wire-changes/mods-kernel@7.68.0.json +129 -0
  495. package/wire-changes/mods-kernel@7.68.1.json +39 -0
  496. package/wire-changes/primitives@7.68.0.json +253 -0
  497. package/wire-changes/primitives@7.68.1.json +39 -0
  498. package/wire-changes/wiki-gate@7.68.0.json +39 -0
  499. package/wire-changes/wiki-gate@7.68.1.json +39 -0
  500. package/dist/core/runner/credential-origin-seat.d.ts +0 -2
  501. package/dist/core/runner/credential-origin-seat.js +0 -20
@@ -1,12 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { types } from "node:util";
3
- import { appendSessionCheckout, readSessionCheckout } from "../engine/session/session.js";
3
+ import { appendSessionCheckout, checkoutDeclarationClosed, readSessionCheckout } from "../engine/session/session.js";
4
4
  import { sameOccupant } from "../engine/session/repo-utils.js";
5
5
  import { isSensitiveRecordKey } from "@sema-agent/primitives";
6
6
  import { branchLeftOf, managedAnchorOf, managedWorktreeBaseOf, managedWorktreeBranchOf, managedWorktreeDir, mintManagedWorktree, removeManagedWorktree, removeTreeIfClean, repositoryRootOf, resolveBaseCommit, shq, symlinkedLevel, WORKTREE_PARENT, worktreeNameProblem, } from "./git-worktree-env.js";
7
7
  import { describeFault, receive } from "./mods/kernel/receive.js";
8
8
  import { strayMembersOf } from "./own-property-receipt.js";
9
- import { thrownText } from "./thrown-value.js";
9
+ import { readMember, thrownText } from "./thrown-value.js";
10
+ import { isAbsence } from "../tools/fs/shell-read-environment.js";
10
11
  export const WORKTREE_INCAPABLE_REASONS = Object.freeze([
11
12
  "name_invalid",
12
13
  "git_unavailable",
@@ -20,8 +21,8 @@ export const WORKTREE_INCAPABLE_REASONS = Object.freeze([
20
21
  const refusal = (code, message) => Object.assign(new Error(message), { code });
21
22
  const invalid = (problem) => refusal("config.session_workspace_invalid", `TaskSpec.workspace ${problem}`);
22
23
  const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
23
- const SOURCE_MAX = 64;
24
- const DECLARATION_MEMBERS = Object.freeze(["isolation", "baseRef", "name", "sources"]);
24
+ const LIST_MAX = 64;
25
+ const DECLARATION_MEMBERS = Object.freeze(["isolation", "baseRef", "name", "sources", "roots"]);
25
26
  const SOURCE_MEMBERS = Object.freeze(["root", "remote", "sha", "ref"]);
26
27
  const DECLARATION_DATA = Object.freeze({ accessors: "refuse", depth: 4, others: "refuse", isProxy: (v) => types.isProxy(v) });
27
28
  const UNRESERVED_CHARACTER = /^[A-Za-z0-9\-._~]$/;
@@ -76,7 +77,7 @@ function screenRoot(root, at) {
76
77
  if (keys.length === 1 && keys[0] === "directory" && typeof directory === "string" && directory.startsWith("/"))
77
78
  return { directory };
78
79
  }
79
- throw invalid(`${at}.root must be "taskRoot" or { directory } naming an absolute additionalDirectories entry`);
80
+ throw invalid(`${at} must be "taskRoot" or { directory } naming an absolute additionalDirectories entry`);
80
81
  }
81
82
  const rootKey = (root) => (root === "taskRoot" ? "taskRoot" : `dir:${root.directory}`);
82
83
  export function screenWorkspaceDeclaration(value) {
@@ -95,8 +96,8 @@ export function screenWorkspaceDeclaration(value) {
95
96
  throw invalid('.isolation must be "worktree"');
96
97
  if (v.baseRef !== undefined && v.baseRef !== "fresh" && v.baseRef !== "head")
97
98
  throw invalid('.baseRef must be "fresh" or "head"');
98
- if ((v.baseRef !== undefined || v.name !== undefined) && v.isolation === undefined)
99
- throw invalid('.baseRef and .name only apply with isolation: "worktree"');
99
+ if ((v.baseRef !== undefined || v.name !== undefined || v.roots !== undefined) && v.isolation === undefined)
100
+ throw invalid('.baseRef, .name and .roots only apply with isolation: "worktree"');
100
101
  if (v.name !== undefined) {
101
102
  if (typeof v.name !== "string")
102
103
  throw invalid(".name must be a string");
@@ -104,10 +105,25 @@ export function screenWorkspaceDeclaration(value) {
104
105
  if (problem !== undefined)
105
106
  throw invalid(`.name: ${problem}`);
106
107
  }
108
+ let roots;
109
+ if (v.roots !== undefined) {
110
+ if (!Array.isArray(v.roots) || v.roots.length === 0 || v.roots.length > LIST_MAX)
111
+ throw invalid(`.roots must be a non-empty list of at most ${LIST_MAX} entries`);
112
+ const seen = new Set();
113
+ roots = v.roots.map((r, i) => {
114
+ const root = screenRoot(r, `.roots[${i}]`);
115
+ if (seen.has(rootKey(root)))
116
+ throw invalid(`.roots[${i}] names a root the list already names`);
117
+ seen.add(rootKey(root));
118
+ return root;
119
+ });
120
+ if (roots.length === 1 && roots[0] === "taskRoot")
121
+ roots = undefined;
122
+ }
107
123
  let sources;
108
124
  if (v.sources !== undefined) {
109
- if (!Array.isArray(v.sources) || v.sources.length === 0 || v.sources.length > SOURCE_MAX)
110
- throw invalid(`.sources must be a non-empty list of at most ${SOURCE_MAX} entries`);
125
+ if (!Array.isArray(v.sources) || v.sources.length === 0 || v.sources.length > LIST_MAX)
126
+ throw invalid(`.sources must be a non-empty list of at most ${LIST_MAX} entries`);
111
127
  sources = [];
112
128
  const seen = new Set();
113
129
  v.sources.forEach((s, i) => {
@@ -118,7 +134,7 @@ export function screenWorkspaceDeclaration(value) {
118
134
  const straySource = strayMembersOf(entry, { subject: `TaskSpec.workspace${at}`, unit: "member", moment: "when the leg starts" }, SOURCE_MEMBERS);
119
135
  if (straySource !== undefined)
120
136
  throw refusal("config.session_workspace_invalid", straySource.sentence);
121
- const root = screenRoot(entry.root, at);
137
+ const root = screenRoot(entry.root, `${at}.root`);
122
138
  if (seen.has(rootKey(root)))
123
139
  throw invalid(`${at}.root names a root another source already names`);
124
140
  seen.add(rootKey(root));
@@ -127,8 +143,6 @@ export function screenWorkspaceDeclaration(value) {
127
143
  throw invalid(`${at}.sha must be a full commit id (40 or 64 lowercase hex characters)`);
128
144
  if (entry.ref !== undefined && (typeof entry.ref !== "string" || entry.ref.length === 0 || entry.ref.length > 256))
129
145
  throw invalid(`${at}.ref must be a non-empty label of at most 256 characters`);
130
- if (root === "taskRoot" && v.isolation !== undefined && v.baseRef !== undefined)
131
- throw invalid(`${at}: a source for the isolated task root sets the tree's start; drop .baseRef`);
132
146
  sources.push({ root, remote, sha: entry.sha, ...(entry.ref !== undefined ? { ref: entry.ref } : {}) });
133
147
  });
134
148
  }
@@ -138,10 +152,12 @@ export function screenWorkspaceDeclaration(value) {
138
152
  ...(v.isolation !== undefined ? { isolation: "worktree" } : {}),
139
153
  ...(v.baseRef !== undefined ? { baseRef: v.baseRef } : {}),
140
154
  ...(v.name !== undefined ? { name: v.name } : {}),
155
+ ...(roots !== undefined ? { roots } : {}),
141
156
  ...(sources !== undefined ? { sources } : {}),
142
157
  };
143
158
  }
144
- const declaredDigest = (d) => JSON.stringify([d.isolation ?? null, d.baseRef ?? null, d.name ?? null, (d.sources ?? []).map((s) => [rootKey(s.root), s.remote, s.sha, s.ref ?? null])]);
159
+ const declaredDigest = (d) => JSON.stringify([d.isolation ?? null, d.baseRef ?? null, d.name ?? null, (d.sources ?? []).map((s) => [rootKey(s.root), s.remote, s.sha, s.ref ?? null]), ...(d.roots !== undefined ? [d.roots.map(rootKey)] : [])]);
160
+ const listedRootsOf = (d) => (d.isolation === undefined ? [] : d.roots ?? ["taskRoot"]);
145
161
  function legWorkspaceOf(raw) {
146
162
  if (raw === null)
147
163
  return { kind: "none" };
@@ -249,15 +265,8 @@ async function sessionRowOf(session, unread) {
249
265
  throw refusal("workspace.checkout_unavailable", `This session's row cannot be read (${thrownText(err).slice(0, 300)}), so whose session tree is whose cannot be told; ${unread}`);
250
266
  }
251
267
  }
252
- const overlaps = (path, top) => path === top || path.startsWith(`${top}/`) || top.startsWith(`${path === "/" ? "" : path}/`);
253
- async function refuseOverlap(env, base, additional) {
254
- const top = await canonicalOf(env, base);
255
- for (const directory of additional) {
256
- if (overlaps(await canonicalOf(env, directory), top)) {
257
- throw invalid(`isolates the task root's checkout ${top}, but additionalDirectories entry ${directory} reaches into it — writes there would land in the base checkout. Drop that directory, or work without isolation.`);
258
- }
259
- }
260
- }
268
+ const holds = (path, top) => path === top || top.startsWith(`${path === "/" ? "" : path}/`);
269
+ const inside = (path, top) => path.startsWith(`${top === "/" ? "" : top}/`);
261
270
  const canonicalOf = async (env, path) => {
262
271
  const r = await env.canonicalPath(path);
263
272
  return r.ok ? r.value : path;
@@ -266,12 +275,199 @@ async function checkoutTopOf(env, dir) {
266
275
  const top = await run(env, "git rev-parse --show-toplevel", dir);
267
276
  return top !== undefined && top.exitCode === 0 && top.stdout.trim().startsWith("/") ? canonicalOf(env, top.stdout.trim()) : undefined;
268
277
  }
269
- async function placeInTree(env, root, dir) {
270
- const canonical = await canonicalOf(env, root);
271
- const top = await checkoutTopOf(env, canonical);
272
- if (top === undefined || !(canonical === top || canonical.startsWith(`${top}/`)))
278
+ async function rootPlaceRead(env, root) {
279
+ try {
280
+ const own = await env.canonicalPath(root);
281
+ if (!own.ok)
282
+ return isAbsence(own.error.code) ? { none: true } : { unread: `${root} cannot be resolved (${own.error.code})` };
283
+ const answer = await run(env, "git rev-parse --show-toplevel --git-common-dir", own.value);
284
+ if (answer === undefined)
285
+ return { unread: `git could not be run at ${own.value}` };
286
+ if (answer.exitCode !== 0)
287
+ return (await gitEntryAtOrAbove(env, own.value)) ? { unread: `git exited ${answer.exitCode} at ${own.value}, below a .git entry` } : { none: true };
288
+ const [topSpelled, commonSpelled] = answer.stdout.split("\n").map((line) => line.trim());
289
+ const malformed = { unread: `git's answer at ${own.value} is not a checkout top and a common directory` };
290
+ if (topSpelled === undefined || !topSpelled.startsWith("/") || commonSpelled === undefined || commonSpelled === "")
291
+ return malformed;
292
+ const top = await env.canonicalPath(topSpelled);
293
+ const common = await env.canonicalPath(commonSpelled.startsWith("/") ? commonSpelled : `${own.value}/${commonSpelled}`);
294
+ if (!top.ok || !common.ok || !(own.value === top.value || own.value.startsWith(`${top.value}/`)))
295
+ return malformed;
296
+ return { place: { canonical: own.value, top: top.value, repository: common.value } };
297
+ }
298
+ catch (err) {
299
+ return { unread: `reading where ${root} stands threw (${thrownText(err)})` };
300
+ }
301
+ }
302
+ async function gitEntryAtOrAbove(env, dir) {
303
+ for (let at = dir;; at = at.slice(0, at.lastIndexOf("/")) || "/") {
304
+ const info = await env.fileInfo(`${at === "/" ? "" : at}/.git`);
305
+ if (info.ok || !isAbsence(info.error.code))
306
+ return true;
307
+ if (at === "/")
308
+ return false;
309
+ }
310
+ }
311
+ async function rootPlaceOf(env, root) {
312
+ const read = await rootPlaceRead(env, root);
313
+ return "place" in read ? read.place : undefined;
314
+ }
315
+ const stringListOf = (value) => (Array.isArray(value) && value.every((v) => typeof v === "string") ? value : undefined);
316
+ const treeOf = (root, trees) => (root.place === undefined ? undefined : trees.find((tree) => tree.repository === root.place.repository));
317
+ function effectiveOf(root, trees) {
318
+ const tree = treeOf(root, trees);
319
+ return tree === undefined ? root.declared : `${tree.dir}${root.place.canonical.slice(root.place.top.length)}`;
320
+ }
321
+ function unplacedLeg(input) {
322
+ const bare = (value) => stringListOf(value)?.map((declared) => ({ declared }));
323
+ return { taskRoot: { declared: input.baseRoot }, write: bare(input.additionalDirectories), read: bare(input.additionalReadDirectories) };
324
+ }
325
+ async function declaredPlaceOf(env, declared, role) {
326
+ const read = await rootPlaceRead(env, declared);
327
+ if ("unread" in read)
328
+ throw refusal("workspace.checkout_unavailable", `Where this leg's ${role} ${declared} stands in git cannot be read (${read.unread}), so it is not placed in or outside the session's trees; the leg was not started.`);
329
+ return "place" in read ? read.place : undefined;
330
+ }
331
+ const roleOf = (root) => (root === "taskRoot" ? "task root" : "additionalDirectories entry");
332
+ async function placeLeg(env, trees, input) {
333
+ if (trees.length === 0)
334
+ return unplacedLeg(input);
335
+ const placed = async (declared, role) => {
336
+ if (declared.trim() === "")
337
+ return { declared };
338
+ const place = await declaredPlaceOf(env, declared, role);
339
+ return place === undefined ? { declared } : { declared, place };
340
+ };
341
+ const list = async (value, role) => {
342
+ const entries = stringListOf(value);
343
+ if (entries === undefined)
344
+ return undefined;
345
+ const out = [];
346
+ for (const entry of entries)
347
+ out.push(await placed(entry, role));
348
+ return out;
349
+ };
350
+ return { taskRoot: await placed(input.baseRoot, "task root"), write: await list(input.additionalDirectories, "additionalDirectories entry"), read: await list(input.additionalReadDirectories, "additionalReadDirectories entry") };
351
+ }
352
+ async function refuseExposedBase(env, trees, leg) {
353
+ if (trees.length === 0)
354
+ return;
355
+ const writable = [leg.taskRoot, ...(leg.write ?? [])];
356
+ const isolatedTops = new Set();
357
+ for (const tree of trees)
358
+ isolatedTops.add(await canonicalOf(env, tree.anchor));
359
+ for (const root of writable)
360
+ if (treeOf(root, trees) !== undefined)
361
+ isolatedTops.add(root.place.top);
362
+ for (const root of writable) {
363
+ if (root.declared.trim() === "" || treeOf(root, trees) !== undefined)
364
+ continue;
365
+ const at = root.place?.canonical ?? (await canonicalOf(env, root.declared));
366
+ for (const top of isolatedTops) {
367
+ const which = root === leg.taskRoot ? `the task root ${root.declared}` : `additionalDirectories entry ${root.declared}`;
368
+ if (holds(at, top)) {
369
+ throw invalid(`isolates the checkout ${top}, but ${which} is in none of the session's trees and holds that checkout — writes there would land in the base checkout. Start from inside the isolated repository, drop that directory, or work without isolation.`);
370
+ }
371
+ if (root.place === undefined && inside(at, top)) {
372
+ throw invalid(`isolates the checkout ${top}, but ${which} lies inside it and git places it in no repository (it does not exist yet), so it cannot be placed in the session's tree — writes there could land in the base checkout. Drop that directory, or work without isolation.`);
373
+ }
374
+ }
375
+ }
376
+ }
377
+ const standingNamed = (label, root) => `${label} ${root.declared} (checkout ${root.place.top})`;
378
+ async function refuseSplitCheckout(env, trees, leg) {
379
+ const own = new Set();
380
+ for (const tree of trees)
381
+ own.add(await canonicalOf(env, tree.dir));
382
+ const named = [{ label: "the task root", root: leg.taskRoot }];
383
+ for (const root of leg.write ?? [])
384
+ named.push({ label: "additionalDirectories entry", root });
385
+ for (const root of leg.read ?? [])
386
+ named.push({ label: "additionalReadDirectories entry", root });
387
+ const first = new Map();
388
+ for (const { label, root } of named) {
389
+ if (root.place === undefined || treeOf(root, trees) === undefined || own.has(root.place.top))
390
+ continue;
391
+ const seen = first.get(root.place.repository);
392
+ if (seen === undefined) {
393
+ first.set(root.place.repository, { label, root });
394
+ continue;
395
+ }
396
+ if (seen.root.place.top === root.place.top)
397
+ continue;
398
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot hold both: ${standingNamed(seen.label, seen.root)} and ${standingNamed(label, root)} are two checkouts of one repository (${root.place.repository}), and one tree cannot stand in for both — the second root would be placed in a tree that is not its checkout. Declare the roots of one checkout, or work without isolation. The leg was not started.`);
399
+ }
400
+ }
401
+ async function resolvedIn(env, root, trees) {
402
+ const effective = effectiveOf(root, trees);
403
+ const at = await env.canonicalPath(effective);
404
+ if (!at.ok)
273
405
  return undefined;
274
- return `${dir}${canonical.slice(top.length)}`;
406
+ const tree = treeOf(root, trees);
407
+ if (tree !== undefined) {
408
+ const dir = await canonicalOf(env, tree.dir);
409
+ if (at.value !== dir && !inside(at.value, dir))
410
+ throw invalid(`places ${root.declared} at ${effective} in the session's tree ${tree.dir}, but that path resolves outside the tree (${at.value}) — a link in the tree leads it out. Drop that root, or work without isolation.`);
411
+ }
412
+ return at.value;
413
+ }
414
+ const reportedRootsOf = (leg) => [[leg.write, "write"], [leg.read, "read"]].flatMap(([list, access]) => (list ?? []).filter((root) => root.declared.trim() !== "").map((root) => ({ root, access })));
415
+ async function directoriesIn(env, trees, reported) {
416
+ const directories = [];
417
+ for (const { root, access } of reported) {
418
+ const at = await resolvedIn(env, root, trees);
419
+ if (at === undefined)
420
+ continue;
421
+ const tree = treeOf(root, trees);
422
+ directories.push({ declared: root.declared, at, access, ...(tree !== undefined ? { tree: tree.dir } : {}) });
423
+ }
424
+ return directories;
425
+ }
426
+ const mappedRoots = (trees, leg) => ({
427
+ taskRoot: effectiveOf(leg.taskRoot, trees),
428
+ ...(leg.write !== undefined ? { additionalDirectories: leg.write.map((root) => effectiveOf(root, trees)) } : {}),
429
+ ...(leg.read !== undefined ? { additionalReadDirectories: leg.read.map((root) => effectiveOf(root, trees)) } : {}),
430
+ });
431
+ const withDirectories = (roots, directories) => (directories.length > 0 ? { ...roots, directories } : roots);
432
+ async function rootsInSession(env, trees, leg) {
433
+ await resolvedIn(env, leg.taskRoot, trees);
434
+ return withDirectories(mappedRoots(trees, leg), await directoriesIn(env, trees, reportedRootsOf(leg)));
435
+ }
436
+ const rootNamed = (root, location) => (root === "taskRoot" ? `the task root ${location}` : `the additional directory ${location}`);
437
+ export async function sessionRootOf(input, refusedAs) {
438
+ try {
439
+ return (await openSessionCheckout({ ...legless(input), session: input.session, sessionId: input.sessionId })).taskRoot;
440
+ }
441
+ catch (err) {
442
+ throw keyedRefusal(err, refusedAs);
443
+ }
444
+ }
445
+ const legless = (input) => ({ env: input.env, declaration: undefined, baseRoot: input.baseRoot, additionalDirectories: undefined, additionalReadDirectories: undefined });
446
+ const keyedRefusal = (err, refusedAs) => {
447
+ const code = readMember(err, "code");
448
+ return refusal(typeof code === "string" && code !== "" ? code : "workspace.checkout_unavailable", `${refusedAs} The checkout's answer: ${thrownText(err)}`);
449
+ };
450
+ export async function recordedRootOf(input, source) {
451
+ const read = await readSessionCheckout(input.session, source);
452
+ const keyedAtBase = read.kind === "none" ? read.window === undefined : read.kind === "record" && !recordHoldsTree(read.record);
453
+ return keyedAtBase ? input.baseRoot : undefined;
454
+ }
455
+ export async function forkHasOwnTree(session, sessionId, forkedFrom) {
456
+ if (forkedFrom === undefined)
457
+ return false;
458
+ const read = await readSessionCheckout(session, sessionId);
459
+ if (read.kind === "unreadable") {
460
+ throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}), so whether this fork works in a tree of its own is not known; nothing was rewound and no file history was recorded.`);
461
+ }
462
+ return read.kind === "record" && recordHoldsTree(read.record);
463
+ }
464
+ const recordHoldsTree = (record) => record.checkouts.some((cell) => cell.dir !== undefined);
465
+ export function withEffectiveDirectories(spec, opened) {
466
+ return {
467
+ ...spec,
468
+ ...(opened.additionalDirectories !== undefined ? { additionalDirectories: [...opened.additionalDirectories] } : {}),
469
+ ...(opened.additionalReadDirectories !== undefined ? { additionalReadDirectories: [...opened.additionalReadDirectories] } : {}),
470
+ };
275
471
  }
276
472
  export async function openSessionCheckout(input) {
277
473
  const { session, sessionId } = input;
@@ -284,14 +480,20 @@ export async function openSessionCheckout(input) {
284
480
  if (read.kind === "record")
285
481
  return reopen(input, leg, read.record);
286
482
  if (leg.kind !== "declared")
287
- return { taskRoot: input.baseRoot };
483
+ return inPlace(input, atRoot(input.baseRoot));
288
484
  const declared = leg.declared;
289
- const forked = (await session.getMetadata()).forkedFrom !== undefined;
290
- if (!forked && (await session.getStorage().findEntries("message")).length > 0) {
291
- throw refusal("config.session_workspace_changed", "TaskSpec.workspace is declared on a session that already ran without it; a session's workspace is fixed by its first leg. Start a new session to work in a declared workspace.");
485
+ if (await checkoutDeclarationClosed(session.getStorage(), await session.getMetadata())) {
486
+ throw refusal("config.session_workspace_changed", "TaskSpec.workspace is declared on a session that already began without it (its log holds a turn or a compaction); a session's workspace is fixed at its birth. Start a new session to work in a declared workspace.");
292
487
  }
293
488
  return allocate(input, declared, observedLeaf);
294
489
  }
490
+ function inPlace(input, sessionRoot) {
491
+ const leg = unplacedLeg(input);
492
+ const roots = { ...mappedRoots([], leg), sessionRoot };
493
+ const reported = reportedRootsOf(leg);
494
+ return reported.length === 0 ? roots : directoriesIn(input.env, [], reported).then((directories) => ({ ...withDirectories(roots, directories), sessionRoot }));
495
+ }
496
+ const atRoot = (root) => () => Promise.resolve({ root });
295
497
  async function treeHoldingCwd(env, cwd, record) {
296
498
  const where = await canonicalOf(env, cwd);
297
499
  for (const cell of record.checkouts) {
@@ -313,16 +515,18 @@ async function reopen(input, leg, record) {
313
515
  if (standing !== undefined) {
314
516
  throw refusal("config.session_workspace_changed", `TaskSpec.workspace is null on a resumed leg whose pending action stands in the session's tree ${standing} (the checkpoint's working directory); it would run there while the leg reports no checkout. Resume it with the session's workspace (omit it, or send the declaration); send null on a leg that starts fresh.`);
315
517
  }
316
- return { taskRoot: input.baseRoot };
518
+ return inPlace(input, () => nullLegRootOf(input, record));
317
519
  }
318
520
  if (leg.kind === "declared" && declaredDigest(leg.declared) !== declaredDigest(record.declared)) {
319
521
  throw refusal("config.session_workspace_changed", `TaskSpec.workspace differs from the declaration this session's checkout was opened under (allocation ${record.allocationId}); a session's workspace is fixed by its first leg. Omit it (the leg takes the session's), send the same declaration, send null for a leg that wants no tree, or start a new session.`);
320
522
  }
321
- for (const cell of record.checkouts)
322
- if (cell.dir !== undefined)
323
- await refuseOverlap(env, cell.repository, input.additionalDirectories ?? []);
324
- const holder = record.checkouts.some((cell) => cell.dir !== undefined) ? { allocationId: record.allocationId, occupant: (await sessionRowOf(input.session, "the leg was not started.")).incarnation } : undefined;
325
- let taskRoot = input.baseRoot;
523
+ const roots = await placedInSession(input, record, await sessionTreesOf(input, record));
524
+ return { ...roots, record, sessionRoot: atRoot(roots.taskRoot) };
525
+ }
526
+ async function sessionTreesOf(input, record) {
527
+ const env = input.env;
528
+ const holder = recordHoldsTree(record) ? { allocationId: record.allocationId, occupant: (await sessionRowOf(input.session, "the leg was not started.")).incarnation } : undefined;
529
+ const trees = [];
326
530
  for (const cell of record.checkouts) {
327
531
  if (cell.dir === undefined)
328
532
  continue;
@@ -339,133 +543,222 @@ async function reopen(input, leg, record) {
339
543
  if (birth.kind !== "marked" || holder === undefined || !recordHoldsMark(holder, birth.mark)) {
340
544
  throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer the tree this session minted (its allocation mark is missing, or names another allocation or another occupant of this session id); the leg was not started. Release the session's checkout and start a new session.`);
341
545
  }
342
- if (cell.root === "taskRoot") {
343
- const placed = await placeInTree(env, input.baseRoot, cell.dir);
344
- const repository = await repositoryRootOf(env, input.baseRoot);
345
- if (placed === undefined || (repository !== undefined && (await canonicalOf(env, repository)) !== (await canonicalOf(env, cell.repository)))) {
346
- throw refusal("config.session_workspace_changed", `This leg's task root ${input.baseRoot} is not in the repository this session's tree was minted from (${cell.repository}).`);
347
- }
348
- taskRoot = placed;
546
+ const tree = await sessionTreeAt(env, cell.dir, cell.repository);
547
+ if (tree === undefined)
548
+ throw refusal("workspace.checkout_unavailable", `Which repository this session's tree ${cell.dir} belongs to cannot be read; the leg was not started.`);
549
+ trees.push(tree);
550
+ }
551
+ return trees;
552
+ }
553
+ async function sessionTreeAt(env, dir, anchor) {
554
+ const place = await rootPlaceOf(env, dir);
555
+ return place === undefined ? undefined : { repository: place.repository, dir, anchor };
556
+ }
557
+ async function placedInSession(input, record, trees) {
558
+ const env = input.env;
559
+ const placed = await placeLeg(env, trees, input);
560
+ for (const listed of listedRootsOf(record.declared)) {
561
+ const root = listed === "taskRoot" ? placed.taskRoot : placed.write?.find((entry) => entry.declared === listed.directory);
562
+ if (root !== undefined && treeOf(root, trees) === undefined) {
563
+ throw refusal("config.session_workspace_changed", `This leg's ${rootNamed(listed, root.declared)} is not in a repository this session's trees were minted from (${record.checkouts.flatMap((cell) => (cell.dir === undefined ? [] : [cell.repository])).join(", ")}).`);
349
564
  }
350
565
  }
351
- return { taskRoot, record };
566
+ await refuseExposedBase(env, trees, placed);
567
+ await refuseSplitCheckout(env, trees, placed);
568
+ return rootsInSession(env, trees, placed);
569
+ }
570
+ async function nullLegRootOf(input, record) {
571
+ const lead = `TaskSpec.workspace is null on a leg of session "${input.sessionId}"`;
572
+ const unkeyed = "A leg that records no file history (TaskSpec.fileHistory: \"disabled\", or capture off) does not read it.";
573
+ let trees;
574
+ try {
575
+ trees = await sessionTreesOf(input, record);
576
+ }
577
+ catch (err) {
578
+ throw keyedRefusal(err, `${lead}, whose file history is keyed to the session's own checkout, and that checkout cannot be resolved — this leg's edits could not be recorded where the session's rewinds read them back, so the leg was not started. ${unkeyed}`);
579
+ }
580
+ let keyed;
581
+ try {
582
+ const leg = await placeLeg(input.env, trees, legless(input));
583
+ if (trees.length === 0 || treeOf(leg.taskRoot, trees) !== undefined)
584
+ keyed = (await rootsInSession(input.env, trees, leg)).taskRoot;
585
+ }
586
+ catch (err) {
587
+ throw keyedRefusal(err, `${lead}: where its file history is keyed cannot be read, so the leg was not started. ${unkeyed}`);
588
+ }
589
+ if (keyed !== undefined)
590
+ return { root: keyed };
591
+ const where = `${lead} whose root ${input.baseRoot} stands outside the session's checkout, so this leg records no file history`;
592
+ const named = `The session's trees: ${trees.map((tree) => tree.dir).join(", ")}.`;
593
+ return {
594
+ outside: {
595
+ notice: `file history is not live for this leg — ${where}: its edits are not in the session's history and no rewind restores them. ${named}`,
596
+ refusal: refusal("config.session_workspace_changed", `${where} and cannot rewind the session's files; the leg was not started. Send the rewind on a leg that omits TaskSpec.workspace, or through Runner.rewindFiles. ${named}`),
597
+ },
598
+ };
352
599
  }
353
600
  async function allocate(input, declared, observedLeaf) {
354
601
  const { env, sessionId, baseRoot } = input;
355
- const additional = input.additionalDirectories ?? [];
356
- const sources = declared.sources ?? [];
357
- let isolatedRepository;
358
- if (declared.isolation === "worktree")
359
- await refuseOverlap(env, await managedAnchorOf(env, baseRoot), additional);
360
- const sourceCells = [];
361
- let taskRootSource;
362
- const seenRepositories = new Set();
363
- for (const source of sources) {
364
- if (source.root !== "taskRoot" && !additional.includes(source.root.directory)) {
365
- throw invalid(`source root ${source.root.directory} is not an additionalDirectories entry (the same spelling is required)`);
602
+ const additional = stringListOf(input.additionalDirectories) ?? [];
603
+ const locationOf = (root, what) => {
604
+ if (root === "taskRoot")
605
+ return baseRoot;
606
+ if (!additional.includes(root.directory))
607
+ throw invalid(`${what} root ${root.directory} is not an additionalDirectories entry (the same spelling is required)`);
608
+ return root.directory;
609
+ };
610
+ const isolated = [];
611
+ for (const root of listedRootsOf(declared)) {
612
+ const location = locationOf(root, "listed");
613
+ const probe = await probeWorktreeCapability(env, location);
614
+ if (!probe.worktreeCapable || probe.gitRoot === undefined) {
615
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(root, location)}: ${probe.detail ?? "the checkout cannot hold a managed tree"} (${probe.reason ?? "unknown"}). No tree was made and the leg was not started in the base checkout instead.`);
366
616
  }
367
- const location = source.root === "taskRoot" ? baseRoot : source.root.directory;
617
+ const place = await declaredPlaceOf(env, location, roleOf(root));
618
+ if (place === undefined)
619
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(root, location)}: git places it in no repository. No tree was made.`);
620
+ if (!isolated.some((r) => r.repository === place.repository))
621
+ isolated.push({ repository: place.repository, anchor: probe.gitRoot, root, location });
622
+ }
623
+ const sourceCells = [];
624
+ const sourced = new Set();
625
+ for (const source of declared.sources ?? []) {
626
+ const location = locationOf(source.root, "source");
627
+ const place = await declaredPlaceOf(env, location, roleOf(source.root));
368
628
  const repository = await repositoryRootOf(env, location);
369
- const top = await checkoutTopOf(env, await canonicalOf(env, location));
370
- if (repository === undefined || top === undefined)
629
+ if (repository === undefined || place === undefined)
371
630
  throw refusal("workspace.source_mismatch", `The declared source for ${location} names a repository, but ${location} is not in a git checkout.`);
372
- const key = await canonicalOf(env, repository);
373
- if (seenRepositories.has(key))
631
+ if (sourced.has(place.repository))
374
632
  throw invalid(`declares two sources for the repository at ${repository} (one source per repository)`);
375
- seenRepositories.add(key);
376
- if (source.root === "taskRoot" && declared.isolation === "worktree") {
377
- taskRootSource = source;
633
+ sourced.add(place.repository);
634
+ const tree = isolated.find((r) => r.repository === place.repository);
635
+ if (tree !== undefined) {
636
+ tree.source = source;
378
637
  continue;
379
638
  }
380
- const head = await run(env, "git rev-parse --verify --quiet 'HEAD^{commit}'", top);
639
+ const head = await run(env, "git rev-parse --verify --quiet 'HEAD^{commit}'", place.top);
381
640
  if (head === undefined || head.exitCode !== 0 || head.stdout.trim() !== source.sha) {
382
- throw refusal("workspace.source_mismatch", `The checkout at ${top} is not at the declared commit ${source.sha} (it is at ${head?.exitCode === 0 ? head.stdout.trim() : "an unreadable HEAD"}); the leg was not started.`);
641
+ throw refusal("workspace.source_mismatch", `The checkout at ${place.top} is not at the declared commit ${source.sha} (it is at ${head?.exitCode === 0 ? head.stdout.trim() : "an unreadable HEAD"}); the leg was not started.`);
383
642
  }
384
643
  sourceCells.push({ repository, root: source.root, baseSha: source.sha, source: { remote: source.remote, sha: source.sha, ...(source.ref !== undefined ? { ref: source.ref } : {}) } });
385
644
  }
386
- const allocationId = randomUUID();
387
- const checkouts = [];
388
- let taskRoot = baseRoot;
389
- if (declared.isolation === "worktree") {
390
- const name = declared.name ?? sessionTreeName(sessionId);
391
- const occupant = (await sessionRowOf(input.session, "the leg was not started.")).incarnation;
392
- const probe = await probeWorktreeCapability(env, baseRoot);
393
- if (!probe.worktreeCapable || probe.gitRoot === undefined) {
394
- throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${baseRoot}: ${probe.detail ?? "the checkout cannot hold a managed tree"} (${probe.reason ?? "unknown"}). The leg was not started in the base checkout instead.`);
395
- }
396
- isolatedRepository = probe.gitRoot;
397
- const dir = managedWorktreeDir(isolatedRepository, name);
398
- const placed = await placeInTree(env, baseRoot, dir);
399
- if (placed === undefined)
400
- throw refusal("workspace.isolation_unavailable", `The task root ${baseRoot} has no place in the session's tree ${dir}.`);
401
- let tree;
645
+ if (declared.baseRef !== undefined && isolated.length > 0 && isolated.every((r) => r.source !== undefined)) {
646
+ throw invalid(".baseRef starts no tree: every isolated repository starts at its declared source; drop .baseRef");
647
+ }
648
+ const name = declared.name ?? sessionTreeName(sessionId);
649
+ const planned = isolated.map((r) => ({ repository: r.repository, anchor: r.anchor, dir: managedWorktreeDir(r.anchor, name) }));
650
+ const placed = await placeLeg(env, planned, input);
651
+ await refuseExposedBase(env, planned, placed);
652
+ await refuseSplitCheckout(env, planned, placed);
653
+ const occupant = isolated.length === 0 ? undefined : (await sessionRowOf(input.session, "the leg was not started.")).incarnation;
654
+ const plans = [];
655
+ for (const repo of isolated) {
656
+ const dir = managedWorktreeDir(repo.anchor, name);
402
657
  const existing = await env.fileInfo(dir);
403
658
  if (existing.ok || existing.error.code !== "not_found") {
404
659
  const read = await readBirthMark(env, dir);
405
660
  const birth = read.kind === "marked" ? read.mark : undefined;
406
661
  if (birth === undefined || birth.sessionId !== sessionId || !sameOccupant(birth.incarnation, occupant)) {
407
- throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: a tree named "${name}" already exists at ${dir} and was not minted by this session (name_in_use). Declare another name — or, when no session's record holds that tree, release it with releaseOrphanSessionTree (listOrphanSessionTrees lists such trees).`);
662
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: a tree named "${name}" already exists at ${dir} and was not minted by this session (name_in_use). Declare another name — or, when no session's record holds that tree, release it with releaseOrphanSessionTree (listOrphanSessionTrees lists such trees).`);
408
663
  }
409
664
  if (birth.declared !== declaredDigest(declared)) {
410
- const atOtherCommit = taskRootSource !== undefined && birth.baseSha !== taskRootSource.sha;
411
- throw refusal(atOtherCommit ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made: the tree this session minted earlier at ${dir} was minted under another declaration${atOtherCommit ? ` (it starts at ${birth.baseSha}, not at the declared commit ${taskRootSource.sha})` : ""} (name_in_use). Declare what it was minted under, or another name.`);
665
+ const atOtherCommit = repo.source !== undefined && birth.baseSha !== repo.source.sha;
666
+ throw refusal(atOtherCommit ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: the tree this session minted earlier at ${dir} was minted under another declaration${atOtherCommit ? ` (it starts at ${birth.baseSha}, not at the declared commit ${repo.source.sha})` : ""} (name_in_use). Declare what it was minted under, or another name.`);
412
667
  }
413
- tree = { dir, branch: managedWorktreeBranchOf(dir) ?? `sema/${name}`, baseSha: birth.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId: birth.allocationId };
668
+ plans.push({ repo, dir, taken: { branch: managedWorktreeBranchOf(dir) ?? `sema/${name}`, baseSha: birth.baseSha, allocationId: birth.allocationId } });
669
+ continue;
670
+ }
671
+ const named = await probeWorktreeCapability(env, repo.location, { name });
672
+ if (!named.worktreeCapable) {
673
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: ${named.detail ?? "the name is taken"} (${named.reason ?? "unknown"}). Declare another name.`);
414
674
  }
675
+ let commit;
676
+ if (repo.source !== undefined)
677
+ commit = repo.source.sha;
415
678
  else {
416
- const named = await probeWorktreeCapability(env, baseRoot, { name });
417
- if (!named.worktreeCapable) {
418
- throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: ${named.detail ?? "the name is taken"} (${named.reason ?? "unknown"}). Declare another name.`);
419
- }
420
- let commit;
421
- if (taskRootSource !== undefined)
422
- commit = taskRootSource.sha;
423
- else {
424
- const base = await resolveBaseCommit(env, baseRoot, declared.baseRef ?? "fresh", undefined);
425
- if ("error" in base)
426
- throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: ${base.error}.`);
427
- commit = base.sha;
428
- }
429
- let minted;
430
- try {
431
- minted = await mintManagedWorktree(env, { repoRoot: baseRoot, sessionId, name, commit });
432
- }
433
- catch (err) {
434
- const why = thrownText(err);
435
- throw refusal(taskRootSource !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made${taskRootSource !== undefined ? ` at the declared commit ${taskRootSource.sha}` : ""}: ${why.slice(0, 600)}`);
436
- }
437
- const undo = async (why, code) => {
438
- const mark = await readBirthMark(env, minted.worktreeDir);
439
- if (mark.kind !== "absent")
440
- throw refusal(code, `${why} The tree is kept at ${minted.worktreeDir} (its allocation mark ${mark.kind === "marked" ? "was written" : "cannot be read"}); a tree no record holds is listed by listOrphanSessionTrees.`);
441
- const removed = await removeManagedWorktree(env, minted.anchor, minted.worktreeDir, minted.baseSha !== undefined ? { name: minted.branch, baseSha: minted.baseSha } : undefined, undefined, "clean");
442
- throw refusal(code, `${why}${removed.ok ? "" : ` The tree minted for it was left at ${minted.worktreeDir} (${removed.detail.trim().slice(0, 200)}).`}`);
443
- };
444
- if (minted.baseSha === undefined || (taskRootSource !== undefined && minted.baseSha !== taskRootSource.sha)) {
445
- return undo(`The session's tree is not at the declared commit${taskRootSource !== undefined ? ` ${taskRootSource.sha}` : ""}; the leg was not started.`, taskRootSource !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable");
679
+ const base = await resolveBaseCommit(env, repo.location, declared.baseRef ?? "fresh", undefined);
680
+ if ("error" in base)
681
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: ${base.error}.`);
682
+ commit = base.sha;
683
+ }
684
+ plans.push({ repo, dir, commit });
685
+ }
686
+ const takenAllocations = [...new Set(plans.flatMap((plan) => (plan.taken === undefined ? [] : [plan.taken.allocationId])))];
687
+ if (takenAllocations.length > 1) {
688
+ throw refusal("workspace.isolation_unavailable", `The session's trees cannot be taken back: the trees this session minted earlier name different allocations (${takenAllocations.join(", ")}) (name_in_use). Declare another name — or release them with releaseOrphanSessionTree (listOrphanSessionTrees lists such trees).`);
689
+ }
690
+ const allocationId = takenAllocations[0] ?? randomUUID();
691
+ const undo = async (why, code) => {
692
+ const kept = [];
693
+ const left = [];
694
+ for (const plan of plans) {
695
+ const tree = plan.minted;
696
+ if (tree === undefined)
697
+ continue;
698
+ const mark = await readBirthMark(env, tree.worktreeDir);
699
+ if (mark.kind !== "absent") {
700
+ kept.push(`The tree is kept at ${tree.worktreeDir} (its allocation mark ${mark.kind === "marked" ? "was written" : "cannot be read"})`);
701
+ continue;
446
702
  }
447
- const birthAt = await birthRecordPath(env, minted.worktreeDir);
448
- const wrote = birthAt === undefined ? undefined : await env.writeFile(birthAt, JSON.stringify({ allocationId, sessionId, ...(typeof occupant === "string" && occupant !== "" ? { incarnation: occupant } : {}), baseSha: minted.baseSha, declared: declaredDigest(declared) }));
449
- if (wrote === undefined || !wrote.ok)
450
- return undo("The session's tree could not be marked as this session's; the leg was not started.", "workspace.isolation_unavailable");
451
- tree = { dir: minted.worktreeDir, branch: minted.branch, baseSha: minted.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId };
703
+ const removed = await removeManagedWorktree(env, tree.anchor, tree.worktreeDir, tree.baseSha !== undefined ? { name: tree.branch, baseSha: tree.baseSha } : undefined, undefined, "clean");
704
+ if (!removed.ok)
705
+ left.push(` The tree minted for it was left at ${tree.worktreeDir} (${removed.detail.trim().slice(0, 200)}).`);
452
706
  }
453
- checkouts.push({
454
- repository: isolatedRepository,
455
- root: "taskRoot",
456
- baseSha: tree.baseSha,
457
- dir: tree.dir,
707
+ const keptSentence = kept.length === 0 ? "" : ` ${kept.join("; ")}; a tree no record holds is listed by listOrphanSessionTrees.`;
708
+ const leftSentence = left.join("");
709
+ throw refusal(code, `${why}${keptSentence}${leftSentence}`);
710
+ };
711
+ for (const plan of plans) {
712
+ if (plan.commit === undefined)
713
+ continue;
714
+ const source = plan.repo.source;
715
+ const code = source !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable";
716
+ let made;
717
+ try {
718
+ made = await mintManagedWorktree(env, { repoRoot: plan.repo.location, sessionId, name, commit: plan.commit });
719
+ }
720
+ catch (err) {
721
+ return undo(`The session's tree cannot be made for ${rootNamed(plan.repo.root, plan.repo.location)}${source !== undefined ? ` at the declared commit ${source.sha}` : ""}: ${thrownText(err).slice(0, 600)} No tree of this allocation was kept unless named below; the leg was not started.`, code);
722
+ }
723
+ plan.minted = { worktreeDir: made.worktreeDir, branch: made.branch, anchor: made.anchor, ...(made.baseSha !== undefined ? { baseSha: made.baseSha } : {}) };
724
+ if (made.baseSha === undefined || (source !== undefined && made.baseSha !== source.sha)) {
725
+ return undo(`The session's tree for ${rootNamed(plan.repo.root, plan.repo.location)} is not at ${source !== undefined ? `the declared commit ${source.sha}` : "a readable base commit"}; the leg was not started.`, code);
726
+ }
727
+ }
728
+ for (const plan of plans) {
729
+ if (plan.minted === undefined)
730
+ continue;
731
+ const birthAt = await birthRecordPath(env, plan.minted.worktreeDir);
732
+ const wrote = birthAt === undefined ? undefined : await env.writeFile(birthAt, JSON.stringify({ allocationId, sessionId, ...(typeof occupant === "string" && occupant !== "" ? { incarnation: occupant } : {}), baseSha: plan.minted.baseSha, declared: declaredDigest(declared) }));
733
+ if (wrote === undefined || !wrote.ok)
734
+ return undo(`The session's tree ${plan.minted.worktreeDir} could not be marked as this session's; the leg was not started.`, "workspace.isolation_unavailable");
735
+ }
736
+ const trees = [];
737
+ const cells = [];
738
+ for (const plan of plans) {
739
+ const dir = plan.minted?.worktreeDir ?? plan.dir;
740
+ const source = plan.repo.source;
741
+ trees.push({ repository: plan.repo.repository, anchor: plan.repo.anchor, dir });
742
+ cells.push({
743
+ repository: plan.repo.anchor,
744
+ root: plan.repo.root,
745
+ baseSha: plan.minted?.baseSha ?? plan.taken.baseSha,
746
+ dir,
458
747
  name,
459
- branch: tree.branch,
460
- baseRef: tree.baseRef,
461
- ...(taskRootSource !== undefined ? { source: { remote: taskRootSource.remote, sha: taskRootSource.sha, ...(taskRootSource.ref !== undefined ? { ref: taskRootSource.ref } : {}) } } : {}),
748
+ branch: plan.minted?.branch ?? plan.taken.branch,
749
+ baseRef: source !== undefined ? "source" : declared.baseRef ?? "fresh",
750
+ ...(source !== undefined ? { source: { remote: source.remote, sha: source.sha, ...(source.ref !== undefined ? { ref: source.ref } : {}) } } : {}),
462
751
  });
463
- taskRoot = `${tree.dir}${placed.slice(dir.length)}`;
464
- const record = { allocationId: tree.allocationId, sessionId, declared, checkouts: [...checkouts, ...sourceCells] };
465
- return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
466
752
  }
467
- const record = { allocationId, sessionId, declared, checkouts: sourceCells };
468
- return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
753
+ let roots;
754
+ try {
755
+ roots = await rootsInSession(env, trees, placed);
756
+ }
757
+ catch (err) {
758
+ return undo(`TaskSpec.workspace ${thrownText(err).replace(/^TaskSpec\.workspace /, "")} The leg was not started.`, "config.session_workspace_invalid");
759
+ }
760
+ const record = await recordNow(input.session, { allocationId, sessionId, declared, checkouts: [...cells, ...sourceCells] }, observedLeaf);
761
+ return { ...roots, record, sessionRoot: atRoot(roots.taskRoot) };
469
762
  }
470
763
  async function recordNow(session, record, observedLeaf) {
471
764
  try {
@@ -550,7 +843,13 @@ async function standingOf(env, dir, sessionOf) {
550
843
  if (checkout.kind === "none") {
551
844
  return checkout.window === undefined ? orphan("unrecorded") : orphan("record_unreadable", `the session's log is loaded from a bounded window (floor ${checkout.window.floor}); a checkout record below the floor cannot be ruled out`);
552
845
  }
553
- return recordHoldsMark({ allocationId: checkout.record.allocationId, occupant }, mark) ? { kind: "held", mark } : orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId}`);
846
+ if (!recordHoldsMark({ allocationId: checkout.record.allocationId, occupant }, mark))
847
+ return orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId}`);
848
+ const own = await canonicalOf(env, dir);
849
+ for (const cell of checkout.record.checkouts)
850
+ if (cell.dir !== undefined && (await canonicalOf(env, cell.dir)) === own)
851
+ return { kind: "held", mark };
852
+ return orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId} without this tree`);
554
853
  }
555
854
  function lookupOf(door, opts) {
556
855
  const sessionOf = opts !== null && typeof opts === "object" ? opts.sessionOf : undefined;
@@ -622,6 +921,6 @@ export function sessionFrameOf(record) {
622
921
  const d = record.declared;
623
922
  return {
624
923
  session: record.checkouts.map((cell) => ({ ...cell, root: rootCopy(cell.root), ...(cell.source !== undefined ? { source: { ...cell.source } } : {}) })),
625
- declaration: { ...d, ...(d.sources !== undefined ? { sources: d.sources.map((source) => ({ ...source, root: rootCopy(source.root) })) } : {}) },
924
+ declaration: { ...d, ...(d.roots !== undefined ? { roots: d.roots.map(rootCopy) } : {}), ...(d.sources !== undefined ? { sources: d.sources.map((source) => ({ ...source, root: rootCopy(source.root) })) } : {}) },
626
925
  };
627
926
  }