@sema-agent/core 7.62.0 → 7.64.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 (320) hide show
  1. package/CHANGELOG.md +936 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  23. package/dist/agents/subagent-transcript-placement.js +14 -0
  24. package/dist/agents/subagent.js +102 -54
  25. package/dist/brain/route-adjudicator.js +9 -4
  26. package/dist/core/allow-entry.d.ts +4 -0
  27. package/dist/core/approval-object.js +1 -1
  28. package/dist/core/arg-summary.js +1 -1
  29. package/dist/core/ask-origin.d.ts +1 -1
  30. package/dist/core/ask-origin.js +2 -2
  31. package/dist/core/ask-question.d.ts +2 -2
  32. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  33. package/dist/core/ask-unresolvable-notice.js +10 -3
  34. package/dist/core/auto-compaction.d.ts +7 -5
  35. package/dist/core/background-agent-store.d.ts +7 -0
  36. package/dist/core/background-agent-store.js +3 -0
  37. package/dist/core/canonical-json.d.ts +23 -13
  38. package/dist/core/canonical-json.js +4 -4
  39. package/dist/core/checkpoint-queries.d.ts +50 -4
  40. package/dist/core/checkpoint-queries.js +42 -17
  41. package/dist/core/checkpoint-requirements.d.ts +3 -3
  42. package/dist/core/checkpoint-requirements.js +2 -1
  43. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  44. package/dist/core/checkpoint-row-verdict.js +22 -2
  45. package/dist/core/checkpoint-store.d.ts +28 -11
  46. package/dist/core/checkpoint-store.js +45 -4
  47. package/dist/core/compliance.d.ts +6 -2
  48. package/dist/core/compliance.js +3 -3
  49. package/dist/core/context-settings.d.ts +40 -9
  50. package/dist/core/context-settings.js +32 -10
  51. package/dist/core/engine-attestation.d.ts +27 -7
  52. package/dist/core/engine-attestation.js +5 -1
  53. package/dist/core/engine-notice.d.ts +43 -5
  54. package/dist/core/extension-requester.d.ts +9 -0
  55. package/dist/core/extension-requester.js +7 -0
  56. package/dist/core/file-history-store.d.ts +28 -0
  57. package/dist/core/file-history-store.js +48 -5
  58. package/dist/core/fs-write-gate-policy.js +1 -1
  59. package/dist/core/gate-fold.js +2 -0
  60. package/dist/core/gate-lanes.js +2 -0
  61. package/dist/core/gate-outcome.d.ts +39 -2
  62. package/dist/core/gate-outcome.js +20 -1
  63. package/dist/core/git-worktree-env.d.ts +62 -3
  64. package/dist/core/git-worktree-env.js +91 -30
  65. package/dist/core/governance-codes.d.ts +9 -3
  66. package/dist/core/governance-codes.js +17 -3
  67. package/dist/core/leg-identity.d.ts +19 -1
  68. package/dist/core/leg-identity.js +12 -0
  69. package/dist/core/mailbox-store.d.ts +39 -4
  70. package/dist/core/mailbox-store.js +14 -2
  71. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  72. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  73. package/dist/core/memory-engine/consolidation.d.ts +74 -10
  74. package/dist/core/memory-engine/consolidation.js +183 -11
  75. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  76. package/dist/core/memory-engine/control-objects.js +151 -0
  77. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  78. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  79. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  80. package/dist/core/memory-engine/data-plane.js +11 -6
  81. package/dist/core/memory-engine/delegation-settlement.d.ts +58 -40
  82. package/dist/core/memory-engine/delegation-settlement.js +270 -85
  83. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  84. package/dist/core/memory-engine/dual-root.js +11 -7
  85. package/dist/core/memory-engine/engine.d.ts +136 -58
  86. package/dist/core/memory-engine/engine.js +491 -394
  87. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  88. package/dist/core/memory-engine/entry-scan.js +3 -0
  89. package/dist/core/memory-engine/file-backend.d.ts +62 -60
  90. package/dist/core/memory-engine/file-backend.js +122 -198
  91. package/dist/core/memory-engine/index.d.ts +8 -7
  92. package/dist/core/memory-engine/index.js +7 -6
  93. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  94. package/dist/core/memory-engine/landing-admission.js +3 -3
  95. package/dist/core/memory-engine/layout.d.ts +127 -46
  96. package/dist/core/memory-engine/layout.js +264 -109
  97. package/dist/core/memory-engine/memory-backend-contract.d.ts +26 -1
  98. package/dist/core/memory-engine/memory-backend-contract.js +476 -0
  99. package/dist/core/memory-engine/memory-deployment.d.ts +42 -11
  100. package/dist/core/memory-engine/memory-deployment.js +54 -15
  101. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  102. package/dist/core/memory-engine/origin-clearance.js +68 -9
  103. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  104. package/dist/core/memory-engine/scope-contract.js +68 -19
  105. package/dist/core/memory-engine/session-write-home.d.ts +37 -2
  106. package/dist/core/memory-engine/session-write-home.js +38 -11
  107. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  108. package/dist/core/memory-engine/sync-client.js +7 -0
  109. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  110. package/dist/core/memory-engine/sync-report.js +6 -2
  111. package/dist/core/memory-engine/tools.d.ts +2 -2
  112. package/dist/core/memory-engine/tools.js +10 -10
  113. package/dist/core/memory-engine/types.d.ts +155 -19
  114. package/dist/core/memory-engine/types.js +2 -0
  115. package/dist/core/memory.js +15 -6
  116. package/dist/core/mode-policy.js +3 -3
  117. package/dist/core/mods/agent-stations.d.ts +18 -0
  118. package/dist/core/mods/agent-stations.js +8 -6
  119. package/dist/core/mods/extension-call.d.ts +4 -0
  120. package/dist/core/mods/extension-call.js +8 -0
  121. package/dist/core/mods/stations.d.ts +20 -1
  122. package/dist/core/mods/stations.js +21 -2
  123. package/dist/core/mods/tool-call.js +3 -4
  124. package/dist/core/parent-spec-seat.d.ts +2 -2
  125. package/dist/core/park-selfcheck.js +2 -2
  126. package/dist/core/pause-registry.d.ts +2 -0
  127. package/dist/core/pause-registry.js +3 -0
  128. package/dist/core/peer-channel.d.ts +5 -0
  129. package/dist/core/permission-rule-consent.d.ts +26 -8
  130. package/dist/core/permission-rule-consent.js +76 -36
  131. package/dist/core/permission-rule-store.d.ts +72 -13
  132. package/dist/core/permission-rule-store.js +29 -8
  133. package/dist/core/read-only-shell.js +3 -2
  134. package/dist/core/redaction-marks.d.ts +8 -0
  135. package/dist/core/redaction-marks.js +6 -0
  136. package/dist/core/refusal-echo.d.ts +20 -0
  137. package/dist/core/refusal-echo.js +33 -0
  138. package/dist/core/remote-env.d.ts +12 -1
  139. package/dist/core/remote-env.js +3 -0
  140. package/dist/core/retention.d.ts +180 -10
  141. package/dist/core/retention.js +45 -0
  142. package/dist/core/retired-keys.d.ts +5 -0
  143. package/dist/core/retired-keys.js +3 -0
  144. package/dist/core/rule-offer-read.d.ts +0 -4
  145. package/dist/core/rule-offer-read.js +2 -18
  146. package/dist/core/runner/child-tree.d.ts +29 -3
  147. package/dist/core/runner/child-tree.js +39 -16
  148. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  149. package/dist/core/runner/classifier-ladder.js +4 -2
  150. package/dist/core/runner/compact-session.js +10 -7
  151. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  152. package/dist/core/runner/compaction-call-options.js +3 -2
  153. package/dist/core/runner/contracts.d.ts +39 -11
  154. package/dist/core/runner/delegation-owner.d.ts +10 -3
  155. package/dist/core/runner/delegation-owner.js +4 -1
  156. package/dist/core/runner/gate-exit.d.ts +6 -0
  157. package/dist/core/runner/gate-exit.js +13 -4
  158. package/dist/core/runner/inherited-ask-grants.js +1 -1
  159. package/dist/core/runner/memory-consolidation-driver.d.ts +10 -5
  160. package/dist/core/runner/memory-consolidation-driver.js +12 -9
  161. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  162. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  163. package/dist/core/runner/person-path-rows.d.ts +8 -3
  164. package/dist/core/runner/person-path-rows.js +5 -1
  165. package/dist/core/runner/placement-fence.d.ts +12 -0
  166. package/dist/core/runner/placement-fence.js +20 -6
  167. package/dist/core/runner/prepare-ask-lane.js +5 -5
  168. package/dist/core/runner/prepare-caps-and-workflow.d.ts +7 -2
  169. package/dist/core/runner/prepare-caps-and-workflow.js +7 -4
  170. package/dist/core/runner/prepare-config-doors.js +4 -0
  171. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  172. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  173. package/dist/core/runner/prepare-execution-env.js +17 -6
  174. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  175. package/dist/core/runner/prepare-gate-stations.js +5 -5
  176. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  177. package/dist/core/runner/prepare-hands-readface.js +5 -4
  178. package/dist/core/runner/prepare-inherited-gate.d.ts +13 -9
  179. package/dist/core/runner/prepare-inherited-gate.js +12 -6
  180. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  181. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  182. package/dist/core/runner/prepare-memory.d.ts +7 -2
  183. package/dist/core/runner/prepare-memory.js +41 -39
  184. package/dist/core/runner/prepare-park-ask.js +4 -3
  185. package/dist/core/runner/prepare-policy-chain.js +7 -7
  186. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  187. package/dist/core/runner/prepare-task.js +26 -18
  188. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  189. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  190. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  191. package/dist/core/runner/resume-admission.d.ts +2 -2
  192. package/dist/core/runner/resume-admission.js +2 -23
  193. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  194. package/dist/core/runner/role-resolution-table.js +62 -0
  195. package/dist/core/runner/run-compaction-machinery.js +2 -2
  196. package/dist/core/runner/run-identity-wiring.js +12 -9
  197. package/dist/core/runner/run-leg.js +9 -5
  198. package/dist/core/runner/run-notification-lane.js +22 -22
  199. package/dist/core/runner/run-recovery-lanes.js +3 -3
  200. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  201. package/dist/core/runner/run-terminal-adoption.js +1 -1
  202. package/dist/core/runner/run-turn-boundary.js +14 -15
  203. package/dist/core/runner/runtask.js +1 -1
  204. package/dist/core/runner/terminal-account.js +1 -1
  205. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  206. package/dist/core/runner/tool-occurrence.js +2 -2
  207. package/dist/core/runner-deps.d.ts +7 -3
  208. package/dist/core/secret-env.d.ts +1 -1
  209. package/dist/core/secret-env.js +4 -4
  210. package/dist/core/session-checkout.d.ts +168 -0
  211. package/dist/core/session-checkout.js +579 -0
  212. package/dist/core/session-store.d.ts +12 -4
  213. package/dist/core/session-store.js +23 -3
  214. package/dist/core/session.d.ts +16 -2
  215. package/dist/core/session.js +3 -0
  216. package/dist/core/shell-read-silence.js +8 -0
  217. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  218. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  219. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  220. package/dist/core/store-contracts/session-store-contract.js +39 -0
  221. package/dist/core/task-event.d.ts +30 -5
  222. package/dist/core/task-notification.d.ts +119 -32
  223. package/dist/core/task-notification.js +186 -100
  224. package/dist/core/task-registry-agent.d.ts +25 -2
  225. package/dist/core/task-registry-agent.js +56 -22
  226. package/dist/core/task-registry-shared.d.ts +33 -11
  227. package/dist/core/task-registry.d.ts +33 -9
  228. package/dist/core/task-registry.js +36 -18
  229. package/dist/core/task-spec-members.js +1 -1
  230. package/dist/core/task-spec.d.ts +27 -2
  231. package/dist/core/tool-errors.d.ts +14 -6
  232. package/dist/core/tool-errors.js +1 -1
  233. package/dist/core/tool-policy.d.ts +32 -13
  234. package/dist/core/tool-policy.js +27 -17
  235. package/dist/core/tool-result-store.d.ts +20 -0
  236. package/dist/core/tool-spec.d.ts +42 -19
  237. package/dist/core/trace.d.ts +3 -2
  238. package/dist/core/types.d.ts +1 -1
  239. package/dist/core/untrusted-egress.d.ts +15 -4
  240. package/dist/core/untrusted-egress.js +23 -22
  241. package/dist/core/workflow-journal-store.d.ts +11 -0
  242. package/dist/core/workflow-journal-store.js +7 -0
  243. package/dist/core/workflow-run-store.d.ts +9 -0
  244. package/dist/core/workflow-run-store.js +6 -0
  245. package/dist/core/workspace-snapshot.d.ts +3 -1
  246. package/dist/core/workspace-snapshot.js +1 -0
  247. package/dist/engine/compaction/compaction.d.ts +2 -1
  248. package/dist/engine/harness/types.d.ts +67 -1
  249. package/dist/engine/harness/types.js +108 -0
  250. package/dist/engine/session/import-validate.js +6 -1
  251. package/dist/engine/session/session.d.ts +30 -1
  252. package/dist/engine/session/session.js +48 -1
  253. package/dist/index.d.ts +12 -7
  254. package/dist/index.js +12 -7
  255. package/dist/internal/harness-types.d.ts +1 -1
  256. package/dist/orchestration/run-workflow-tool.d.ts +8 -1
  257. package/dist/orchestration/run-workflow-tool.js +8 -0
  258. package/dist/orchestration/workflow-types.d.ts +2 -1
  259. package/dist/orchestration/workflow.d.ts +6 -0
  260. package/dist/orchestration/workflow.js +5 -2
  261. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  262. package/dist/stores/file/checkpoint-store.js +4 -1
  263. package/dist/stores/file/file-history-store.d.ts +13 -0
  264. package/dist/stores/file/file-history-store.js +75 -13
  265. package/dist/stores/file/index.d.ts +11 -1
  266. package/dist/stores/file/index.js +7 -11
  267. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  268. package/dist/stores/file/permission-rule-store.js +75 -7
  269. package/dist/stores/file/session-store.js +2 -1
  270. package/dist/stores/file/tool-result-store.d.ts +14 -0
  271. package/dist/stores/file/tool-result-store.js +39 -2
  272. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  273. package/dist/stores/file/workflow-journal-store.js +17 -0
  274. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  275. package/dist/stores/file/workflow-run-store.js +15 -0
  276. package/dist/tools/fs/bash-program-position.js +3 -3
  277. package/dist/tools/fs/program-read-model.d.ts +34 -10
  278. package/dist/tools/fs/program-read-model.js +37 -7
  279. package/dist/tools/fs/program-read-model.rows.js +13 -2
  280. package/dist/tools/fs/read-deny.d.ts +28 -3
  281. package/dist/tools/fs/read-deny.js +18 -2
  282. package/dist/tools/fs/removal-targets.js +3 -3
  283. package/dist/tools/fs/safety.d.ts +2 -0
  284. package/dist/tools/fs/safety.js +1 -1
  285. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  286. package/dist/tools/fs/shell-read-argv.js +34 -29
  287. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  288. package/dist/tools/fs/shell-read-bindings.js +5 -1
  289. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  290. package/dist/tools/fs/shell-read-brace.js +79 -0
  291. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  292. package/dist/tools/fs/shell-read-check.js +16 -14
  293. package/dist/tools/fs/shell-read-establish.js +23 -16
  294. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  295. package/dist/tools/fs/shell-read-judge.js +3 -3
  296. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  297. package/dist/tools/fs/shell-read-plan.js +189 -93
  298. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  299. package/dist/tools/fs/shell-read-start.js +20 -12
  300. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  301. package/dist/tools/fs/shell-read-word.js +9 -5
  302. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  303. package/dist/tools/fs/shell-read-workdir.js +73 -12
  304. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  305. package/dist/tools/worktree.d.ts +3 -2
  306. package/dist/tools/worktree.js +7 -35
  307. package/package.json +3 -2
  308. package/test/export-surface.snapshot.json +135 -11
  309. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  310. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  311. package/wire-changes/core@7.63.0.json +3523 -0
  312. package/wire-changes/core@7.64.0.json +2653 -0
  313. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  314. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  315. package/wire-changes/primitives@7.63.0.json +445 -0
  316. package/wire-changes/primitives@7.64.0.json +30 -0
  317. package/dist/core/credential-vocabulary.d.ts +0 -176
  318. package/dist/core/credential-vocabulary.js +0 -190
  319. package/dist/core/redaction-passes.d.ts +0 -82
  320. package/dist/core/redaction-passes.js +0 -377
@@ -0,0 +1,579 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { appendSessionCheckout, readSessionCheckout } from "../engine/session/session.js";
3
+ import { isSensitiveRecordKey } from "@sema-agent/primitives";
4
+ import { managedAnchorOf, managedWorktreeBaseOf, managedWorktreeBranchOf, managedWorktreeDir, mintManagedWorktree, removeManagedWorktree, repositoryRootOf, resolveBaseCommit, shq, symlinkedLevel, WORKTREE_PARENT, worktreeNameProblem, } from "./git-worktree-env.js";
5
+ import { strayMembersOf } from "./own-property-receipt.js";
6
+ import { thrownText } from "./thrown-value.js";
7
+ export const WORKTREE_INCAPABLE_REASONS = Object.freeze([
8
+ "git_unavailable",
9
+ "not_a_repository",
10
+ "bare_repository",
11
+ "no_commit",
12
+ "managed_parent_symlinked",
13
+ "parent_not_writable",
14
+ "name_in_use",
15
+ ]);
16
+ const refusal = (code, message) => Object.assign(new Error(message), { code });
17
+ const invalid = (problem) => refusal("config.session_workspace_invalid", `TaskSpec.workspace ${problem}`);
18
+ const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
19
+ const SOURCE_MAX = 64;
20
+ const DECLARATION_MEMBERS = Object.freeze(["isolation", "baseRef", "name", "sources"]);
21
+ const SOURCE_MEMBERS = Object.freeze(["root", "remote", "sha", "ref"]);
22
+ function normalizeRemote(remote, at) {
23
+ if (typeof remote !== "string" || remote.length === 0 || remote.length > 2048)
24
+ throw invalid(`${at}.remote must be an https repository URL`);
25
+ let url;
26
+ try {
27
+ url = new URL(remote);
28
+ }
29
+ catch {
30
+ throw invalid(`${at}.remote is not a URL`);
31
+ }
32
+ if (url.protocol !== "https:")
33
+ throw invalid(`${at}.remote must be an https URL (got a ${url.protocol.replace(/:$/, "")} URL)`);
34
+ if (url.username !== "" || url.password !== "")
35
+ throw invalid(`${at}.remote carries a user name or password (${url.origin}); credentials never ride the declaration`);
36
+ const fragment = new URLSearchParams(url.hash.replace(/^#/, ""));
37
+ for (const params of [url.searchParams, fragment]) {
38
+ for (const name of params.keys()) {
39
+ if (isSensitiveRecordKey(name))
40
+ throw invalid(`${at}.remote carries a credential parameter (${url.origin}); credentials never ride the declaration`);
41
+ }
42
+ }
43
+ const path = url.pathname.replace(/\/+$/, "").replace(/\.git$/, "");
44
+ if (path === "" || path === "/")
45
+ throw invalid(`${at}.remote names no repository (${url.origin})`);
46
+ return `https://${url.host.toLowerCase()}${path}`;
47
+ }
48
+ function screenRoot(root, at) {
49
+ if (root === "taskRoot")
50
+ return "taskRoot";
51
+ if (root !== null && typeof root === "object" && !Array.isArray(root)) {
52
+ const keys = Object.keys(root);
53
+ const directory = root.directory;
54
+ if (keys.length === 1 && keys[0] === "directory" && typeof directory === "string" && directory.startsWith("/"))
55
+ return { directory };
56
+ }
57
+ throw invalid(`${at}.root must be "taskRoot" or { directory } naming an absolute additionalDirectories entry`);
58
+ }
59
+ const rootKey = (root) => (root === "taskRoot" ? "taskRoot" : `dir:${root.directory}`);
60
+ export function screenWorkspaceDeclaration(value) {
61
+ if (value === undefined)
62
+ return undefined;
63
+ if (value === null || typeof value !== "object" || Array.isArray(value))
64
+ throw invalid("must be an object");
65
+ const v = value;
66
+ const stray = strayMembersOf(v, { subject: "TaskSpec.workspace", unit: "member", moment: "when the leg starts" }, DECLARATION_MEMBERS);
67
+ if (stray !== undefined)
68
+ throw refusal("config.session_workspace_invalid", stray.sentence);
69
+ if (v.isolation !== undefined && v.isolation !== "worktree")
70
+ throw invalid('.isolation must be "worktree"');
71
+ if (v.baseRef !== undefined && v.baseRef !== "fresh" && v.baseRef !== "head")
72
+ throw invalid('.baseRef must be "fresh" or "head"');
73
+ if ((v.baseRef !== undefined || v.name !== undefined) && v.isolation === undefined)
74
+ throw invalid('.baseRef and .name only apply with isolation: "worktree"');
75
+ if (v.name !== undefined) {
76
+ if (typeof v.name !== "string")
77
+ throw invalid(".name must be a string");
78
+ const problem = worktreeNameProblem(v.name);
79
+ if (problem !== undefined)
80
+ throw invalid(`.name: ${problem}`);
81
+ }
82
+ let sources;
83
+ if (v.sources !== undefined) {
84
+ if (!Array.isArray(v.sources) || v.sources.length === 0 || v.sources.length > SOURCE_MAX)
85
+ throw invalid(`.sources must be a non-empty list of at most ${SOURCE_MAX} entries`);
86
+ sources = [];
87
+ const seen = new Set();
88
+ v.sources.forEach((s, i) => {
89
+ const at = `.sources[${i}]`;
90
+ if (s === null || typeof s !== "object" || Array.isArray(s))
91
+ throw invalid(`${at} must be an object`);
92
+ const entry = s;
93
+ const straySource = strayMembersOf(entry, { subject: `TaskSpec.workspace${at}`, unit: "member", moment: "when the leg starts" }, SOURCE_MEMBERS);
94
+ if (straySource !== undefined)
95
+ throw refusal("config.session_workspace_invalid", straySource.sentence);
96
+ const root = screenRoot(entry.root, at);
97
+ if (seen.has(rootKey(root)))
98
+ throw invalid(`${at}.root names a root another source already names`);
99
+ seen.add(rootKey(root));
100
+ const remote = normalizeRemote(entry.remote, at);
101
+ if (typeof entry.sha !== "string" || !FULL_SHA.test(entry.sha))
102
+ throw invalid(`${at}.sha must be a full commit id (40 or 64 lowercase hex characters)`);
103
+ if (entry.ref !== undefined && (typeof entry.ref !== "string" || entry.ref.length === 0 || entry.ref.length > 256))
104
+ throw invalid(`${at}.ref must be a non-empty label of at most 256 characters`);
105
+ if (root === "taskRoot" && v.isolation !== undefined && v.baseRef !== undefined)
106
+ throw invalid(`${at}: a source for the isolated task root sets the tree's start; drop .baseRef`);
107
+ sources.push({ root, remote, sha: entry.sha, ...(entry.ref !== undefined ? { ref: entry.ref } : {}) });
108
+ });
109
+ }
110
+ if (v.isolation === undefined && sources === undefined)
111
+ throw invalid('declares nothing (give isolation: "worktree", sources, or both)');
112
+ return {
113
+ ...(v.isolation !== undefined ? { isolation: "worktree" } : {}),
114
+ ...(v.baseRef !== undefined ? { baseRef: v.baseRef } : {}),
115
+ ...(v.name !== undefined ? { name: v.name } : {}),
116
+ ...(sources !== undefined ? { sources } : {}),
117
+ };
118
+ }
119
+ const declaredDigest = (d) => JSON.stringify(d === undefined ? null : [d.isolation ?? null, d.baseRef ?? null, d.name ?? null, (d.sources ?? []).map((s) => [rootKey(s.root), s.remote, s.sha, s.ref ?? null])]);
120
+ async function run(env, command, cwd) {
121
+ try {
122
+ const r = await env.exec(command, { cwd });
123
+ return r.ok ? r.value : undefined;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ }
129
+ function sessionTreeName(sessionId) {
130
+ const slug = sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
131
+ return slug === "" ? "session" : slug;
132
+ }
133
+ export async function probeWorktreeCapability(env, cwd, opts) {
134
+ const no = (reason, detail, gitRoot) => ({ worktreeCapable: false, reason, detail, ...(gitRoot !== undefined ? { gitRoot } : {}) });
135
+ const version = await run(env, "git --version", cwd);
136
+ if (version === undefined || version.exitCode !== 0)
137
+ return no("git_unavailable", "git cannot be run in this environment");
138
+ const bare = await run(env, "git rev-parse --is-bare-repository", cwd);
139
+ if (bare === undefined || bare.exitCode !== 0)
140
+ return no("not_a_repository", `${cwd} is not inside a git repository`);
141
+ if (bare.stdout.trim() === "true")
142
+ return no("bare_repository", `${cwd} is a bare repository (it has no working tree to branch from)`);
143
+ const inside = await run(env, "git rev-parse --is-inside-work-tree", cwd);
144
+ if (inside === undefined || inside.exitCode !== 0 || inside.stdout.trim() !== "true")
145
+ return no("not_a_repository", `${cwd} is not inside a git work tree`);
146
+ const head = await run(env, "git rev-parse --verify --quiet 'HEAD^{commit}'", cwd);
147
+ if (head === undefined || head.exitCode !== 0)
148
+ return no("no_commit", `the repository at ${cwd} has no commit yet`);
149
+ const gitRoot = await managedAnchorOf(env, cwd);
150
+ const leaf = opts?.name !== undefined ? managedWorktreeDir(gitRoot, opts.name) : `${gitRoot}/${WORKTREE_PARENT}`;
151
+ const symlinked = await symlinkedLevel(env, gitRoot, leaf);
152
+ if (symlinked !== undefined)
153
+ return no("managed_parent_symlinked", symlinked, gitRoot);
154
+ let writable = gitRoot;
155
+ for (const level of [`${gitRoot}/${WORKTREE_PARENT}`, `${gitRoot}/.sema`]) {
156
+ const info = await env.fileInfo(level);
157
+ if (info.ok) {
158
+ writable = level;
159
+ break;
160
+ }
161
+ }
162
+ const canWrite = await run(env, `test -w ${shq(writable)}`, cwd);
163
+ if (canWrite === undefined || canWrite.exitCode !== 0)
164
+ return no("parent_not_writable", `${writable} cannot be written`, gitRoot);
165
+ if (opts?.name !== undefined) {
166
+ const dir = managedWorktreeDir(gitRoot, opts.name);
167
+ const at = await env.fileInfo(dir);
168
+ if (at.ok || at.error.code !== "not_found")
169
+ return no("name_in_use", `a tree named "${opts.name}" already exists at ${dir}`, gitRoot);
170
+ const branch = managedWorktreeBranchOf(dir);
171
+ const ref = branch === undefined ? undefined : await run(env, `git rev-parse --verify --quiet ${shq(`refs/heads/${branch}`)}`, gitRoot);
172
+ if (ref !== undefined && ref.exitCode === 0)
173
+ return no("name_in_use", `the branch ${branch} already exists`, gitRoot);
174
+ }
175
+ return { worktreeCapable: true, gitRoot };
176
+ }
177
+ async function birthRecordPath(env, dir) {
178
+ const gitDir = await run(env, "git rev-parse --absolute-git-dir", dir);
179
+ return gitDir !== undefined && gitDir.exitCode === 0 && gitDir.stdout.trim().startsWith("/") ? `${gitDir.stdout.trim()}/sema-allocation` : undefined;
180
+ }
181
+ async function readBirthMark(env, dir) {
182
+ const unreadable = (detail) => ({ kind: "unreadable", detail });
183
+ const own = await env.canonicalPath(dir);
184
+ const top = await checkoutTopOf(env, dir);
185
+ if (!own.ok || top === undefined)
186
+ return unreadable(`git cannot say which checkout ${dir} is`);
187
+ if (top !== own.value)
188
+ return { kind: "absent" };
189
+ const at = await birthRecordPath(env, dir);
190
+ if (at === undefined)
191
+ return unreadable(`git does not name the private directory of ${dir}`);
192
+ const text = await env.readTextFile(at);
193
+ if (!text.ok)
194
+ return text.error.code === "not_found" ? { kind: "absent" } : unreadable(`its allocation mark cannot be read (${thrownText(text.error).slice(0, 200)})`);
195
+ try {
196
+ const v = JSON.parse(text.value);
197
+ if (typeof v.allocationId === "string" && typeof v.sessionId === "string" && typeof v.baseSha === "string" && FULL_SHA.test(v.baseSha) && typeof v.declared === "string") {
198
+ return { kind: "marked", mark: { allocationId: v.allocationId, sessionId: v.sessionId, baseSha: v.baseSha, declared: v.declared } };
199
+ }
200
+ }
201
+ catch {
202
+ }
203
+ return unreadable("its allocation mark is not a valid record");
204
+ }
205
+ const recordHoldsMark = (holder, mark) => holder.allocationId === mark.allocationId;
206
+ const overlaps = (path, top) => path === top || path.startsWith(`${top}/`) || top.startsWith(`${path === "/" ? "" : path}/`);
207
+ async function refuseOverlap(env, base, additional) {
208
+ const top = await canonicalOf(env, base);
209
+ for (const directory of additional) {
210
+ if (overlaps(await canonicalOf(env, directory), top)) {
211
+ 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.`);
212
+ }
213
+ }
214
+ }
215
+ const canonicalOf = async (env, path) => {
216
+ const r = await env.canonicalPath(path);
217
+ return r.ok ? r.value : path;
218
+ };
219
+ async function checkoutTopOf(env, dir) {
220
+ const top = await run(env, "git rev-parse --show-toplevel", dir);
221
+ return top !== undefined && top.exitCode === 0 && top.stdout.trim().startsWith("/") ? canonicalOf(env, top.stdout.trim()) : undefined;
222
+ }
223
+ async function placeInTree(env, root, dir) {
224
+ const canonical = await canonicalOf(env, root);
225
+ const top = await checkoutTopOf(env, canonical);
226
+ if (top === undefined || !(canonical === top || canonical.startsWith(`${top}/`)))
227
+ return undefined;
228
+ return `${dir}${canonical.slice(top.length)}`;
229
+ }
230
+ export async function openSessionCheckout(input) {
231
+ const { session, sessionId } = input;
232
+ const declared = screenWorkspaceDeclaration(input.declaration);
233
+ const observedLeaf = declared !== undefined ? await session.getStorage().getLeafId() : null;
234
+ const read = await readSessionCheckout(session, sessionId);
235
+ if (read.kind === "unreadable") {
236
+ throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}); the leg was not started rather than run outside the session's checkout.`);
237
+ }
238
+ if (read.kind === "record")
239
+ return reopen(input, declared, read.record);
240
+ if (declared === undefined)
241
+ return { taskRoot: input.baseRoot };
242
+ const forked = (await session.getMetadata()).forkedFrom !== undefined;
243
+ if (!forked && (await session.getStorage().findEntries("message")).length > 0) {
244
+ 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.");
245
+ }
246
+ return allocate(input, declared, observedLeaf);
247
+ }
248
+ async function reopen(input, declared, record) {
249
+ const env = input.env;
250
+ if (record.released === true) {
251
+ throw refusal("config.session_workspace_changed", "This session's checkout was released; a released session runs no further leg. Start a new session.");
252
+ }
253
+ if (declaredDigest(declared) !== declaredDigest(record.declared)) {
254
+ 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. Send the same declaration on every leg, or start a new session.`);
255
+ }
256
+ for (const cell of record.checkouts)
257
+ if (cell.dir !== undefined)
258
+ await refuseOverlap(env, cell.repository, input.additionalDirectories ?? []);
259
+ let taskRoot = input.baseRoot;
260
+ for (const cell of record.checkouts) {
261
+ if (cell.dir === undefined)
262
+ continue;
263
+ const info = await env.fileInfo(cell.dir);
264
+ if (!info.ok) {
265
+ if (info.error.code === "not_found") {
266
+ throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} no longer exists; the leg was not started (it is never run in the base checkout instead). Release the session's checkout (releaseSessionCheckout) and start a new session.`);
267
+ }
268
+ throw refusal("workspace.checkout_unavailable", `This session's tree ${cell.dir} cannot be read (${thrownText(info.error)}); the leg was not started.`);
269
+ }
270
+ if (info.value.kind !== "directory")
271
+ throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer a directory; the leg was not started.`);
272
+ const birth = await readBirthMark(env, cell.dir);
273
+ if (birth.kind !== "marked" || !recordHoldsMark(record, birth.mark)) {
274
+ 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); the leg was not started. Release the session's checkout and start a new session.`);
275
+ }
276
+ if (cell.root === "taskRoot") {
277
+ const placed = await placeInTree(env, input.baseRoot, cell.dir);
278
+ const repository = await repositoryRootOf(env, input.baseRoot);
279
+ if (placed === undefined || (repository !== undefined && (await canonicalOf(env, repository)) !== (await canonicalOf(env, cell.repository)))) {
280
+ 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}).`);
281
+ }
282
+ taskRoot = placed;
283
+ }
284
+ }
285
+ return { taskRoot, record };
286
+ }
287
+ async function allocate(input, declared, observedLeaf) {
288
+ const { env, sessionId, baseRoot } = input;
289
+ const additional = input.additionalDirectories ?? [];
290
+ const sources = declared.sources ?? [];
291
+ let isolatedRepository;
292
+ if (declared.isolation === "worktree")
293
+ await refuseOverlap(env, await managedAnchorOf(env, baseRoot), additional);
294
+ const sourceCells = [];
295
+ let taskRootSource;
296
+ const seenRepositories = new Set();
297
+ for (const source of sources) {
298
+ if (source.root !== "taskRoot" && !additional.includes(source.root.directory)) {
299
+ throw invalid(`source root ${source.root.directory} is not an additionalDirectories entry (the same spelling is required)`);
300
+ }
301
+ const location = source.root === "taskRoot" ? baseRoot : source.root.directory;
302
+ const repository = await repositoryRootOf(env, location);
303
+ const top = await checkoutTopOf(env, await canonicalOf(env, location));
304
+ if (repository === undefined || top === undefined)
305
+ throw refusal("workspace.source_mismatch", `The declared source for ${location} names a repository, but ${location} is not in a git checkout.`);
306
+ const key = await canonicalOf(env, repository);
307
+ if (seenRepositories.has(key))
308
+ throw invalid(`declares two sources for the repository at ${repository} (one source per repository)`);
309
+ seenRepositories.add(key);
310
+ if (source.root === "taskRoot" && declared.isolation === "worktree") {
311
+ taskRootSource = source;
312
+ continue;
313
+ }
314
+ const head = await run(env, "git rev-parse --verify --quiet 'HEAD^{commit}'", top);
315
+ if (head === undefined || head.exitCode !== 0 || head.stdout.trim() !== source.sha) {
316
+ 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.`);
317
+ }
318
+ sourceCells.push({ repository, root: source.root, baseSha: source.sha, source: { remote: source.remote, sha: source.sha, ...(source.ref !== undefined ? { ref: source.ref } : {}) } });
319
+ }
320
+ const allocationId = randomUUID();
321
+ const checkouts = [];
322
+ let taskRoot = baseRoot;
323
+ if (declared.isolation === "worktree") {
324
+ const name = declared.name ?? sessionTreeName(sessionId);
325
+ const probe = await probeWorktreeCapability(env, baseRoot);
326
+ if (!probe.worktreeCapable || probe.gitRoot === undefined) {
327
+ 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.`);
328
+ }
329
+ isolatedRepository = probe.gitRoot;
330
+ const dir = managedWorktreeDir(isolatedRepository, name);
331
+ const placed = await placeInTree(env, baseRoot, dir);
332
+ if (placed === undefined)
333
+ throw refusal("workspace.isolation_unavailable", `The task root ${baseRoot} has no place in the session's tree ${dir}.`);
334
+ let tree;
335
+ const existing = await env.fileInfo(dir);
336
+ if (existing.ok || existing.error.code !== "not_found") {
337
+ const read = await readBirthMark(env, dir);
338
+ const birth = read.kind === "marked" ? read.mark : undefined;
339
+ if (birth === undefined || birth.sessionId !== sessionId) {
340
+ 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).`);
341
+ }
342
+ if (birth.declared !== declaredDigest(declared)) {
343
+ const atOtherCommit = taskRootSource !== undefined && birth.baseSha !== taskRootSource.sha;
344
+ 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.`);
345
+ }
346
+ tree = { dir, branch: managedWorktreeBranchOf(dir) ?? `sema/${name}`, baseSha: birth.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId: birth.allocationId };
347
+ }
348
+ else {
349
+ const named = await probeWorktreeCapability(env, baseRoot, { name });
350
+ if (!named.worktreeCapable) {
351
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: ${named.detail ?? "the name is taken"} (${named.reason ?? "unknown"}). Declare another name.`);
352
+ }
353
+ let commit;
354
+ if (taskRootSource !== undefined)
355
+ commit = taskRootSource.sha;
356
+ else {
357
+ const base = await resolveBaseCommit(env, baseRoot, declared.baseRef ?? "fresh", undefined);
358
+ if ("error" in base)
359
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: ${base.error}.`);
360
+ commit = base.sha;
361
+ }
362
+ let minted;
363
+ try {
364
+ minted = await mintManagedWorktree(env, { repoRoot: baseRoot, sessionId, name, commit });
365
+ }
366
+ catch (err) {
367
+ const why = thrownText(err);
368
+ 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)}`);
369
+ }
370
+ const undo = async (why, code) => {
371
+ const mark = await readBirthMark(env, minted.worktreeDir);
372
+ if (mark.kind !== "absent")
373
+ 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.`);
374
+ const removed = await removeManagedWorktree(env, minted.anchor, minted.worktreeDir, minted.baseSha !== undefined ? { name: minted.branch, baseSha: minted.baseSha } : undefined, undefined, "clean");
375
+ throw refusal(code, `${why}${removed.ok ? "" : ` The tree minted for it was left at ${minted.worktreeDir} (${removed.detail.trim().slice(0, 200)}).`}`);
376
+ };
377
+ if (minted.baseSha === undefined || (taskRootSource !== undefined && minted.baseSha !== taskRootSource.sha)) {
378
+ 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");
379
+ }
380
+ const birthAt = await birthRecordPath(env, minted.worktreeDir);
381
+ const wrote = birthAt === undefined ? undefined : await env.writeFile(birthAt, JSON.stringify({ allocationId, sessionId, baseSha: minted.baseSha, declared: declaredDigest(declared) }));
382
+ if (wrote === undefined || !wrote.ok)
383
+ return undo("The session's tree could not be marked as this session's; the leg was not started.", "workspace.isolation_unavailable");
384
+ tree = { dir: minted.worktreeDir, branch: minted.branch, baseSha: minted.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId };
385
+ }
386
+ checkouts.push({
387
+ repository: isolatedRepository,
388
+ root: "taskRoot",
389
+ baseSha: tree.baseSha,
390
+ dir: tree.dir,
391
+ name,
392
+ branch: tree.branch,
393
+ baseRef: tree.baseRef,
394
+ ...(taskRootSource !== undefined ? { source: { remote: taskRootSource.remote, sha: taskRootSource.sha, ...(taskRootSource.ref !== undefined ? { ref: taskRootSource.ref } : {}) } } : {}),
395
+ });
396
+ taskRoot = `${tree.dir}${placed.slice(dir.length)}`;
397
+ const record = { allocationId: tree.allocationId, sessionId, declared, checkouts: [...checkouts, ...sourceCells] };
398
+ return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
399
+ }
400
+ const record = { allocationId, sessionId, declared, checkouts: sourceCells };
401
+ return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
402
+ }
403
+ async function recordNow(session, record, observedLeaf) {
404
+ try {
405
+ await appendSessionCheckout(session, record, observedLeaf);
406
+ }
407
+ catch (err) {
408
+ const dirs = record.checkouts.flatMap((cell) => (cell.dir === undefined ? [] : [cell.dir]));
409
+ const kept = dirs.length === 0
410
+ ? ""
411
+ : ` The tree is kept at ${dirs.join(", ")}. If the record was written, the next leg reopens it and releaseSessionCheckout releases it; if not, the next leg of this session with the same declaration takes it back; a tree no record holds is listed by listOrphanSessionTrees.`;
412
+ throw refusal("workspace.checkout_unavailable", `This session's checkout could not be recorded (${thrownText(err).slice(0, 300)}); the leg was not started.${kept}`);
413
+ }
414
+ return record;
415
+ }
416
+ export async function releaseSessionCheckout(env, session, opts) {
417
+ const onExit = opts?.onExit ?? "keep-if-dirty";
418
+ if (onExit !== "keep-if-dirty" && onExit !== "keep") {
419
+ throw refusal("config.invalid_argument", `releaseSessionCheckout: onExit must be "keep-if-dirty" or "keep" (a removal that discards changes is not offered)`);
420
+ }
421
+ const sessionId = (await session.getMetadata()).id;
422
+ const read = await readSessionCheckout(session, sessionId);
423
+ if (read.kind === "unreadable")
424
+ throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}); nothing was removed.`);
425
+ if (read.kind === "none")
426
+ return { trees: [] };
427
+ const record = read.record;
428
+ const trees = [];
429
+ for (const cell of record.checkouts) {
430
+ if (cell.dir === undefined || cell.branch === undefined)
431
+ continue;
432
+ trees.push(await releaseTree(env, { path: cell.dir, repository: cell.repository, branch: cell.branch, baseSha: cell.baseSha }, record, onExit));
433
+ }
434
+ if (record.released !== true)
435
+ await appendSessionCheckout(session, { ...record, released: true });
436
+ return { trees };
437
+ }
438
+ const IGNORED_NAMED = 5;
439
+ function ignoredDetail(paths) {
440
+ const named = paths.slice(0, IGNORED_NAMED).map((p) => p.slice(0, 120)).join(", ");
441
+ const more = paths.length > IGNORED_NAMED ? ` and ${paths.length - IGNORED_NAMED} more` : "";
442
+ return `the tree holds files git ignores (${named}${more}), which removing it would delete — delete or move them, then release again`;
443
+ }
444
+ async function branchLeftOf(env, tree) {
445
+ const ref = await run(env, `git rev-parse --verify --quiet ${shq(`refs/heads/${tree.branch}`)}`, tree.repository);
446
+ return ref !== undefined && ref.exitCode === 0 ? { branch: tree.branch } : {};
447
+ }
448
+ async function goneTree(env, tree) {
449
+ await run(env, "git worktree prune", tree.repository);
450
+ return { path: tree.path, removed: true, ...(await branchLeftOf(env, tree)) };
451
+ }
452
+ async function releaseTree(env, tree, holder, onExit) {
453
+ const { path, repository, branch, baseSha } = tree;
454
+ const at = await env.fileInfo(path);
455
+ if (!at.ok) {
456
+ if (at.error.code !== "not_found")
457
+ return { path, removed: false, kept: "unverifiable", branch, detail: thrownText(at.error).slice(0, 300) };
458
+ return goneTree(env, tree);
459
+ }
460
+ const held = async () => {
461
+ const mark = await readBirthMark(env, path);
462
+ return mark.kind === "marked" && recordHoldsMark(holder, mark.mark);
463
+ };
464
+ if (!(await held()))
465
+ return { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, tree)) };
466
+ if (onExit === "keep")
467
+ return { path, removed: false, kept: "requested", branch };
468
+ const status = await run(env, "git status --porcelain --ignored --untracked-files=normal", path);
469
+ if (status === undefined || status.exitCode !== 0)
470
+ return { path, removed: false, kept: "unverifiable", branch };
471
+ const entries = status.stdout.split("\n").filter((line) => line !== "");
472
+ if (entries.some((line) => !line.startsWith("!! ")))
473
+ return { path, removed: false, kept: "dirty", branch };
474
+ if (entries.length > 0)
475
+ return { path, removed: false, kept: "ignored", branch, detail: ignoredDetail(entries.map((line) => line.slice(3))) };
476
+ const ahead = await run(env, `git rev-list --count ${shq(`${baseSha}..HEAD`)}`, path);
477
+ const commits = ahead !== undefined && ahead.exitCode === 0 ? Number.parseInt(ahead.stdout.trim(), 10) : Number.NaN;
478
+ if (!Number.isFinite(commits))
479
+ return { path, removed: false, kept: "unverifiable", branch };
480
+ if (commits > 0)
481
+ return { path, removed: false, kept: "commits", branch };
482
+ if (!(await held()))
483
+ return { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, tree)) };
484
+ const removed = await removeManagedWorktree(env, repository, path, { name: branch, baseSha }, undefined, "clean");
485
+ if (!removed.ok)
486
+ return { path, removed: false, kept: "unverifiable", branch, detail: removed.detail.trim().slice(0, 300) };
487
+ return { path, removed: true, ...(await branchLeftOf(env, tree)) };
488
+ }
489
+ async function standingOf(env, dir, sessionOf) {
490
+ const read = await readBirthMark(env, dir);
491
+ if (read.kind !== "marked")
492
+ return { kind: "unmarked", read };
493
+ const mark = read.mark;
494
+ const orphan = (why, detail) => ({ kind: "orphan", mark, why, ...(detail !== undefined ? { detail: detail.slice(0, 300) } : {}) });
495
+ let checkout;
496
+ try {
497
+ const session = await sessionOf(mark.sessionId);
498
+ if (session === undefined)
499
+ return orphan("unrecorded");
500
+ checkout = await readSessionCheckout(session, mark.sessionId);
501
+ }
502
+ catch (err) {
503
+ return orphan("record_unreadable", `the session ${mark.sessionId} could not be read (${thrownText(err)})`);
504
+ }
505
+ if (checkout.kind === "unreadable")
506
+ return orphan("record_unreadable", checkout.detail);
507
+ if (checkout.kind === "none") {
508
+ 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`);
509
+ }
510
+ return recordHoldsMark(checkout.record, mark) ? { kind: "held", mark } : orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId}`);
511
+ }
512
+ function lookupOf(door, opts) {
513
+ const sessionOf = opts !== null && typeof opts === "object" ? opts.sessionOf : undefined;
514
+ if (typeof sessionOf !== "function")
515
+ throw refusal("config.invalid_argument", `${door}: opts.sessionOf must be a function (the host's lookup of a session by id in its durable store)`);
516
+ return sessionOf;
517
+ }
518
+ export async function listOrphanSessionTrees(env, root, opts) {
519
+ const sessionOf = lookupOf("listOrphanSessionTrees", opts);
520
+ if (typeof root !== "string" || !root.startsWith("/"))
521
+ throw refusal("config.invalid_argument", "listOrphanSessionTrees: root must be an absolute path");
522
+ const repository = await managedAnchorOf(env, root);
523
+ const parent = `${repository}/${WORKTREE_PARENT}`;
524
+ const listed = await env.listDir(parent);
525
+ if (!listed.ok) {
526
+ if (listed.error.code === "not_found")
527
+ return { repository, trees: [] };
528
+ throw refusal("workspace.checkout_unavailable", `listOrphanSessionTrees: the managed parent ${parent} cannot be listed (${thrownText(listed.error).slice(0, 200)}); nothing was judged.`);
529
+ }
530
+ const trees = [];
531
+ for (const child of [...listed.value].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
532
+ if (child.kind !== "directory")
533
+ continue;
534
+ const path = managedWorktreeDir(repository, child.name);
535
+ const standing = await standingOf(env, path, sessionOf);
536
+ if (standing.kind !== "orphan")
537
+ continue;
538
+ const { mark, why, detail } = standing;
539
+ const branch = managedWorktreeBranchOf(path);
540
+ trees.push({
541
+ path,
542
+ ...(branch !== undefined ? await branchLeftOf(env, { repository, branch }) : {}),
543
+ sessionId: mark.sessionId,
544
+ allocationId: mark.allocationId,
545
+ baseSha: mark.baseSha,
546
+ why,
547
+ ...(detail !== undefined ? { detail } : {}),
548
+ modifiedAt: child.mtimeMs,
549
+ });
550
+ }
551
+ return { repository, trees };
552
+ }
553
+ export async function releaseOrphanSessionTree(env, path, opts) {
554
+ const sessionOf = lookupOf("releaseOrphanSessionTree", opts);
555
+ const repository = typeof path === "string" ? managedWorktreeBaseOf(path) : undefined;
556
+ const branch = repository !== undefined ? managedWorktreeBranchOf(path) : undefined;
557
+ if (repository === undefined || branch === undefined) {
558
+ throw refusal("config.invalid_argument", `releaseOrphanSessionTree: ${String(path).slice(0, 200)} is not a managed tree path (<repository root>/${WORKTREE_PARENT}/<name>)`);
559
+ }
560
+ const at = await env.fileInfo(path);
561
+ if (!at.ok)
562
+ return at.error.code === "not_found" ? goneTree(env, { path, repository, branch }) : { path, removed: false, kept: "unverifiable", branch, detail: thrownText(at.error).slice(0, 300) };
563
+ const standing = await standingOf(env, path, sessionOf);
564
+ if (standing.kind === "unmarked") {
565
+ return standing.read.kind === "absent"
566
+ ? { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, { repository, branch })), detail: "it carries no allocation mark: it is no session tree" }
567
+ : { path, removed: false, kept: "unverifiable", branch, detail: standing.read.detail };
568
+ }
569
+ if (standing.kind === "held")
570
+ return { path, removed: false, kept: "not_owned", branch, detail: "a session's record holds this tree; releaseSessionCheckout releases it" };
571
+ if (standing.why === "record_unreadable")
572
+ return { path, removed: false, kept: "unverifiable", branch, ...(standing.detail !== undefined ? { detail: standing.detail } : {}) };
573
+ return releaseTree(env, { path, repository, branch, baseSha: standing.mark.baseSha }, standing.mark, "keep-if-dirty");
574
+ }
575
+ export function sessionFrameOf(record) {
576
+ if (record === undefined || record.checkouts.length === 0)
577
+ return undefined;
578
+ return record.checkouts.map((cell) => ({ ...cell, root: cell.root === "taskRoot" ? "taskRoot" : { directory: cell.root.directory }, ...(cell.source !== undefined ? { source: { ...cell.source } } : {}) }));
579
+ }
@@ -81,10 +81,11 @@ export interface TtlSessionStoreOptions {
81
81
  * session — host-listable, never really-deleted, the declared full tier falsified in silence. On
82
82
  * a store that DECLARES the partition (`capability.subagentPlacement`; an ignoring store legally drops
83
83
  * placements), an acquire carrying a placement must therefore come back with a PERSISTED tuple whose
84
- * join identity matches the declaration — a missing or foreign tuple refuses loudly.
84
+ * join identity matches the declaration — a missing or foreign tuple refuses loudly. A placed `fork` is judged by the
85
+ * same direction on the row it created (no squat can win a fork's fresh id, but a repo that drops the tuple can).
85
86
  *
86
87
  * @param persisted the tuple the backend holds for `sessionId` as resolved (`undefined`: an unplaced session).
87
- * @param request the `acquire` options the caller passed.
88
+ * @param request the `acquire` options the caller passed (a placed `fork`: its placement).
88
89
  * @param capability whether the store declares the subagent placement partition. `subagentPlacement` is read once,
89
90
  * and only when the mirror direction is judged (a placement request that is not the read form, after `request`'s
90
91
  * members are read), so a store may pass a getter over its live declaration.
@@ -92,7 +93,7 @@ export interface TtlSessionStoreOptions {
92
93
  */
93
94
  export declare function admitSessionPlacement(sessionId: string, persisted: SessionPlacementRecord | undefined, request: {
94
95
  requireExisting?: boolean;
95
- placement?: SessionPlacement;
96
+ placement?: Omit<SessionPlacement, "owner">;
96
97
  }, capability: {
97
98
  subagentPlacement: boolean;
98
99
  }): void;
@@ -237,8 +238,15 @@ export declare class TtlSessionStore implements SessionStore {
237
238
  *
238
239
  * Adding this method is what makes {@link hasSessionFork} true for a `TtlSessionStore` wrapping ANY repo, so the
239
240
  * fork capability mounts (it was INERT before — the durable repo had `fork` but the store never exposed it).
241
+ *
242
+ * `opts.placement` forks INTO the placement partition ({@link SessionStore.fork}): the tuple rides the repo's fork verbatim, as a
243
+ * placed create's does, and the cache entry carries the persisted tuple so the obligations arm at cache speed. On a store that
244
+ * declares the partition the created row is judged by the placement admission's mirror direction; a refusal removes the row
245
+ * first (nobody else holds the fresh id), so a dropped tuple leaves no ordinary copy of the source's history behind.
240
246
  */
241
- fork(sourceId: string, owner?: string | null): Promise<string | null>;
247
+ fork(sourceId: string, owner?: string | null, opts?: {
248
+ placement?: Omit<SessionPlacement, "owner">;
249
+ }): Promise<string | null>;
242
250
  /** Drop a session from the live set. With a durable repo (`evict: "forget"`) the history is kept. A release that rejects leaves the
243
251
  * session where it was: the store keeps no view of it and retries nothing on its own, and a placed row is found again by the
244
252
  * partition-GC leg's `listPlaced` — except one whose header is damaged, which `listPlaced` skips and every release of it rejects