@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
@@ -523,6 +523,21 @@ export interface FileHistoryStore {
523
523
  * reference — the arm the commit paths already validate for.
524
524
  */
525
525
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
526
+ /**
527
+ * Erase the WHOLE scope — every boundary, every version record INCLUDING the v1 pristine baselines `reap` keeps while a scope
528
+ * lives, its consumed-id ledger — and the blobs no other scope references: the session-tree cascade's leg for a deleted session
529
+ * (the scope is the session id; {@link import("./retention.js").RETENTION_CASCADE}). Answers how many boundaries and version
530
+ * records it removed (a damaged record is erased all the same and counts once; a scope with no history answers 0, so a repeat
531
+ * is harmless). The scope then reads as one that never had
532
+ * history: an id registered again later starts a new one. Refused (thrown, `conflict`) while THIS store runs a write of the scope
533
+ * — a capture, a first-touch record, a retraction or an import, counted from the call, so one parked before its first record is
534
+ * counted — since a cascade runs on a session with no leg running; another process's writes are the caller's precondition to
535
+ * hold. A store fault throws: a deletion face that cannot delete is loud, never a quiet 0 — the blob pass included, so a backend
536
+ * that cannot collect every blob only the scope referenced (another scope's history it cannot judge, a blob that will not unlink)
537
+ * throws after the records are gone, and a repeat runs that pass again. OPTIONAL: absent ⇒ this store cannot complete a session
538
+ * deletion (only `reap` remains, which keeps the baselines), and the deployment owns that gap.
539
+ */
540
+ deleteBySession?(scope: string): Promise<number>;
526
541
  /**
527
542
  * Cross-session carry (CC copyFileHistoryForResume): make `toScope` see `fromScope`'s boundaries
528
543
  * + versions (content-addressed backends copy references, zero bytes). Same-scope call is a
@@ -882,6 +897,9 @@ export declare class InMemoryFileHistoryStore implements FileHistoryStore {
882
897
  * (adversarial round): two concurrent captures can lease the same new hash, and the first
883
898
  * attempt's release must not strip the second attempt's liveness. */
884
899
  private readonly inFlightBlobs;
900
+ /** Per scope, the history writes (`trackEdit`, `annulTrack`, `snapshot`, `importHistory`) this store is running, from call to
901
+ * settle: `deleteBySession` refuses while a scope has one, an import still fetching its blobs included. */
902
+ private readonly writers;
885
903
  constructor(options?: InMemoryFileHistoryStoreOptions);
886
904
  /**
887
905
  * The RETENTION pass, run after a boundary commits (design/381 §片2 — see {@link FileHistoryStore.reap}
@@ -902,22 +920,32 @@ export declare class InMemoryFileHistoryStore implements FileHistoryStore {
902
920
  /** PROTECTED COMMIT SEAM (fault-injectable): publish a captured boundary in ONE synchronous step
903
921
  * — version records + mapping become visible together or not at all (atomic visibility). */
904
922
  protected publishBoundary(scope: string, entryId: string, staged: Map<string, StagedFileCapture>): void;
923
+ /** One history write of `scope`, counted in {@link writers} for its whole run. */
924
+ private writing;
905
925
  trackEdit(scope: string, absPath: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryTrackResult>;
926
+ private trackEditCounted;
906
927
  annulTrack(scope: string, absPath: string, root: string, verify?: {
907
928
  env: ExecutionEnv;
908
929
  signal?: AbortSignal;
909
930
  }): Promise<FileHistoryResult>;
931
+ private annulTrackCounted;
910
932
  snapshot(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryResult>;
933
+ private snapshotCounted;
911
934
  restore(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryRestoreResult>;
912
935
  canRestore(scope: string, entryId: string): Promise<boolean>;
913
936
  diffStats(scope: string, entryId: string, env: ExecutionEnv, root: string): Promise<FileHistoryDiffStats | null>;
914
937
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
938
+ deleteBySession(scope: string): Promise<number>;
939
+ /** Blob GC: live = referenced by ANY scope's retained version records, or in-flight. Synchronous (no await), so it runs
940
+ * atomically vs an in-flight capture parked at an await. */
941
+ private collectBlobs;
915
942
  adoptScope(fromScope: string, toScope: string): Promise<FileHistoryResult>;
916
943
  exportHistory(scope: string): Promise<FileHistoryExportResult>;
917
944
  /** The export projection as a SYNCHRONOUS function — the import's final claim needs to compare a
918
945
  * target's identity without yielding (see the publish step). */
919
946
  private exportOf;
920
947
  importHistory(scope: string, data: FileHistoryExport, srcGetBlob: (hash: string) => Promise<Uint8Array | undefined>): Promise<FileHistoryResult>;
948
+ private importHistoryCounted;
921
949
  /** The import body inside the blob lease (see {@link importHistory}). */
922
950
  private importStaged;
923
951
  }
@@ -445,6 +445,7 @@ export class InMemoryFileHistoryStore {
445
445
  boundaryKeep;
446
446
  blobs = new Map();
447
447
  inFlightBlobs = new Map();
448
+ writers = new Map();
448
449
  constructor(options) {
449
450
  const opts = receiveOptions(options, "InMemoryFileHistoryStore", IN_MEMORY_FILE_HISTORY_STORE_OPTION_KEYS);
450
451
  this.boundaryKeep = resolveFileHistoryRetention("InMemoryFileHistoryStore", opts.retention);
@@ -513,7 +514,23 @@ export class InMemoryFileHistoryStore {
513
514
  }
514
515
  sc.boundaries.set(entryId, mapping);
515
516
  }
516
- async trackEdit(scope, absPath, env, root, signal) {
517
+ async writing(scope, write) {
518
+ this.writers.set(scope, (this.writers.get(scope) ?? 0) + 1);
519
+ try {
520
+ return await write();
521
+ }
522
+ finally {
523
+ const left = (this.writers.get(scope) ?? 1) - 1;
524
+ if (left === 0)
525
+ this.writers.delete(scope);
526
+ else
527
+ this.writers.set(scope, left);
528
+ }
529
+ }
530
+ trackEdit(scope, absPath, env, root, signal) {
531
+ return this.writing(scope, () => this.trackEditCounted(scope, absPath, env, root, signal));
532
+ }
533
+ async trackEditCounted(scope, absPath, env, root, signal) {
517
534
  try {
518
535
  const { key, ...keyDesc } = describeTrackKey(root, absPath);
519
536
  const sc = this.scope(scope);
@@ -562,7 +579,10 @@ export class InMemoryFileHistoryStore {
562
579
  return { ok: false, error: { code: "track_failed", message: `first-touch record for ${absPath} could not be persisted: ${thrownText(err)}`, ...caughtFault(err) } };
563
580
  }
564
581
  }
565
- async annulTrack(scope, absPath, root, verify) {
582
+ annulTrack(scope, absPath, root, verify) {
583
+ return this.writing(scope, () => this.annulTrackCounted(scope, absPath, root, verify));
584
+ }
585
+ async annulTrackCounted(scope, absPath, root, verify) {
566
586
  try {
567
587
  const key = trackKeyOf(root, absPath);
568
588
  const sc = this.scopes.get(scope);
@@ -602,7 +622,10 @@ export class InMemoryFileHistoryStore {
602
622
  return { ok: false, error: { code: "track_failed", message: `annulling the first-touch record for ${absPath} failed: ${thrownText(err)}`, ...caughtFault(err) } };
603
623
  }
604
624
  }
605
- async snapshot(scope, entryId, env, root, signal) {
625
+ snapshot(scope, entryId, env, root, signal) {
626
+ return this.writing(scope, () => this.snapshotCounted(scope, entryId, env, root, signal));
627
+ }
628
+ async snapshotCounted(scope, entryId, env, root, signal) {
606
629
  const sc = this.scope(scope);
607
630
  if (sc.boundaries.has(entryId))
608
631
  return { ok: true };
@@ -824,6 +847,24 @@ export class InMemoryFileHistoryStore {
824
847
  const refs = referenced.get(key);
825
848
  t.versions = t.versions.filter((v) => v.version === 1 || (refs?.has(v.version) ?? false));
826
849
  }
850
+ this.collectBlobs();
851
+ return removed;
852
+ }
853
+ async deleteBySession(scope) {
854
+ if (this.writers.has(scope)) {
855
+ throw Object.assign(new Error(`file history scope "${scope}" has a write in flight in this store (a capture, a first-touch record, a retraction or an import) — a session's history is erased when no leg of it runs`), { code: "conflict" });
856
+ }
857
+ const sc = this.scopes.get(scope);
858
+ if (sc === undefined)
859
+ return 0;
860
+ let removed = sc.boundaries.size;
861
+ for (const t of sc.tracked.values())
862
+ removed += t.versions.length;
863
+ this.scopes.delete(scope);
864
+ this.collectBlobs();
865
+ return removed;
866
+ }
867
+ collectBlobs() {
827
868
  const live = new Set(this.inFlightBlobs.keys());
828
869
  for (const s of this.scopes.values()) {
829
870
  for (const t of s.tracked.values())
@@ -834,7 +875,6 @@ export class InMemoryFileHistoryStore {
834
875
  for (const h of [...this.blobs.keys()])
835
876
  if (!live.has(h))
836
877
  this.blobs.delete(h);
837
- return removed;
838
878
  }
839
879
  async adoptScope(fromScope, toScope) {
840
880
  try {
@@ -886,7 +926,10 @@ export class InMemoryFileHistoryStore {
886
926
  .map(([entryId, mapping]) => ({ entryId, files: [...mapping.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) })),
887
927
  };
888
928
  }
889
- async importHistory(scope, data, srcGetBlob) {
929
+ importHistory(scope, data, srcGetBlob) {
930
+ return this.writing(scope, () => this.importHistoryCounted(scope, data, srcGetBlob));
931
+ }
932
+ async importHistoryCounted(scope, data, srcGetBlob) {
890
933
  try {
891
934
  const shaped = validateFileHistoryExport(data);
892
935
  if (!shaped.ok)
@@ -134,7 +134,7 @@ export function createFsWriteGatePolicy(opts) {
134
134
  if (note !== undefined)
135
135
  return ask(`approve write to "${path}"?${note}`);
136
136
  const generic = `approve write to "${path}"?`;
137
- return attest(ask(generic), req, { genericQuestion: generic });
137
+ return attest(ask(generic), req, { sentence: { text: generic, generic: true, echoed: [Object.freeze({ kind: "path", value: path })] } });
138
138
  },
139
139
  };
140
140
  }
@@ -225,6 +225,8 @@ function applyShellReadVerdict(pass, answer, toolName, shellGated) {
225
225
  pass.deniedBy = "read_boundary";
226
226
  if (verdict.details !== undefined)
227
227
  pass.denyDetails = verdict.details;
228
+ if (verdict.echoed !== undefined)
229
+ pass.denyEchoed = verdict.echoed;
228
230
  return;
229
231
  }
230
232
  if (reading.kind === "silence") {
@@ -839,6 +839,8 @@ export async function runGateLanes(pass) {
839
839
  pass.deniedBy = "read_boundary";
840
840
  if (reading.verdict.details !== undefined)
841
841
  pass.denyDetails = reading.verdict.details;
842
+ if (reading.verdict.echoed !== undefined)
843
+ pass.denyEchoed = reading.verdict.echoed;
842
844
  }
843
845
  }
844
846
  }
@@ -11,6 +11,7 @@ import { type AskClass, type AskOrigin, type AssertAllKeysHandled, type ModeRele
11
11
  import { type AutoModeClassifierRound, type AutoModeFallbackCause } from "./auto-mode.js";
12
12
  import { type AllowRuleClearance } from "./allow-rule-shadow.js";
13
13
  import type { ResolvedOutcome } from "./checkpoint-store.js";
14
+ import { type RefusalEcho } from "./refusal-echo.js";
14
15
  /**
15
16
  * How the wait an ask was in ENDED — the closed set. One word per way a wait can end; the `who` on the
16
17
  * record says which party ended it and is fixed BY the word (see {@link Settlement}).
@@ -402,6 +403,24 @@ export declare const DENIED_BY_MAY_NAME_EXTENSION: {
402
403
  };
403
404
  /** Compile-time fence: `never` while every deny layer has an extension-naming row. */
404
405
  export type ExtensionTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedBy, keyof typeof DENIED_BY_MAY_NAME_EXTENSION>>;
406
+ /** Which deny layers may carry the literals their refusal sentence quotes ({@link GateDisposition}'s `echoed`): the read station,
407
+ * whose deny sentence is minted with them from one finding; an ask's resolution, whose refusal sentence quotes the question the
408
+ * engine composed with its literals. The mint reads it as the producer and the screen (invariant I13) as the archive: one table,
409
+ * two readers. Module-level only; not part of the package root. */
410
+ export declare const DENIED_BY_MAY_ECHO: {
411
+ readonly policy: false;
412
+ readonly hook: false;
413
+ readonly org: false;
414
+ readonly persisted_rule: false;
415
+ readonly classifier: false;
416
+ readonly compliance: false;
417
+ readonly write_protection: false;
418
+ readonly ask_resolution: true;
419
+ readonly read_boundary: true;
420
+ readonly mode: false;
421
+ };
422
+ /** Compile-time fence: `never` while every deny layer has an echo row. */
423
+ export type EchoTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedBy, keyof typeof DENIED_BY_MAY_ECHO>>;
405
424
  /** The final disposition of a gate pass. `cause` is present exactly when the deny came out of an auto-mode
406
425
  * classifier round that did not RULE ({@link ClassifierDenyCause}); a ruling block and every non-classifier
407
426
  * deny carry none. Invariant I5 ({@link screenGateOutcome}): a cause stands only beside a layer word in
@@ -436,7 +455,21 @@ export type ExtensionTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<Den
436
455
  * refusing handler's registration is known; ABSENT beside every other layer word (an ancestor leg's screening reaches a
437
456
  * descendant as a `policy` refusal, and a refusal an inherited installation's question settled is that question's), and beside
438
457
  * a `hook` refusal that names no registration (the engine's own failed raise, a cancel). A display and audit fact: the call is
439
- * refused whatever the name. Additive. Invariant I12 ({@link screenGateOutcome}) screens its shape. */
458
+ * refused whatever the name. Additive. Invariant I12 ({@link screenGateOutcome}) screens its shape.
459
+ *
460
+ * `echoed` — on the denied arm only: the literals the refusal's sentence quotes — the path (with its canonical target where the
461
+ * sentence names one), the view of it the deny row actually matched when that is another spelling, and the pattern — in the order
462
+ * the sentence quotes them, each whole (the sentence elides the middle of a long one, this list never does). Minted with the
463
+ * sentence from one finding, so a consumer reads WHICH path, command or pattern was refused from here and never by taking the
464
+ * sentence apart. Present when `deniedBy` is `read_boundary` and the refusal is a deny-row hit, and when `deniedBy` is
465
+ * `ask_resolution` and the refusal quotes a question the engine composed with its literals (a write gate's or the plan mode's
466
+ * generic question about a path: the list then holds that path as the call spells it — not a canonical one) while the refusal's
467
+ * sentence is still the one the resolver composed ({@link DENIED_BY_MAY_ECHO}). ABSENT beside every other layer word, on a
468
+ * read-boundary refusal that quotes no deny row (a containment or identity finding), and on a resolution refusal whose question
469
+ * was anyone else's words or was rewritten or appended to on the way (a hook's, a persisted rule's, a card's added sentence): the
470
+ * sentence is then the whole account, and a consumer that finds the member absent reads it as it always did — what was asked is
471
+ * the call's own arguments. The member's presence says nothing about the layer: read the layer off `deniedBy`. Additive.
472
+ * Invariant I13 ({@link screenGateOutcome}) screens its shape. */
440
473
  export type GateDisposition = {
441
474
  kind: "allowed";
442
475
  classifier?: AutoModeClassifierRound;
@@ -451,6 +484,7 @@ export type GateDisposition = {
451
484
  askClass?: AskClass;
452
485
  classes?: readonly AskClass[];
453
486
  extension?: string;
487
+ echoed?: readonly RefusalEcho[];
454
488
  };
455
489
  /**
456
490
  * A permission MODE released a surviving ask — the allowed disposition's account of the question it did not put
@@ -511,6 +545,9 @@ export interface ModeRefusal {
511
545
  * I10 `settlement.when` present ⇒ a finite number (epoch ms — the moment the wait ended is a value a reader can order);
512
546
  * I12 `disposition.extension` present ⇒ the denied arm, a layer word {@link DENIED_BY_MAY_NAME_EXTENSION} admits (the hook layer),
513
547
  * and a non-empty string (a registration's name);
548
+ * I13 `disposition.echoed` present ⇒ the denied arm, a layer word {@link DENIED_BY_MAY_ECHO} admits (the read station, an ask's resolution), and a
549
+ * non-empty list of echoes ({@link refusalEchoDefects}): a kind of the closed set, a non-empty `value`, and a `canonical`
550
+ * only on a path;
514
551
  * I11 a winner's `decision` stated beside the record (the caller reads a durable row: `winnerDecision`) ⇒ a word a winner holds,
515
552
  * and its direction (allow: `allow` / `approve` / `edit`; refusal: `deny` / `reject`) is the direction of the record's
516
553
  * settlement ({@link SETTLEMENT_IS_REFUSAL}) and of its disposition (`allowed` / `denied`) — one decision, one direction.
@@ -582,7 +619,7 @@ export declare function isRetiredMember<S extends MemberSet>(set: S, word: unkno
582
619
  */
583
620
  export declare function releasePolicyDefects(g: unknown): string[];
584
621
  /** The members only the denied arm of a {@link GateDisposition} carries. */
585
- declare const DENY_ONLY_MEMBERS: readonly ["deniedBy", "cause", "mode", "askClass", "classes", "extension"];
622
+ declare const DENY_ONLY_MEMBERS: readonly ["deniedBy", "cause", "mode", "askClass", "classes", "extension", "echoed"];
586
623
  type DenyOnlyMember = Exclude<keyof Extract<GateDisposition, {
587
624
  kind: "denied";
588
625
  }>, keyof Extract<GateDisposition, {
@@ -1,6 +1,7 @@
1
1
  import { isAskClass, isAskOrigin, isModeReleaseReason, isPermissionMode, isPersistedRuleMandate, ASK_FACES, releasableAskClassesFor } from "./ask-origin.js";
2
2
  import { isAutoModeFallbackCause } from "./auto-mode.js";
3
3
  import { ALLOW_RULE_MEMBERS } from "./allow-rule-shadow.js";
4
+ import { refusalEchoDefects } from "./refusal-echo.js";
4
5
  export const SETTLEMENT_KINDS = Object.freeze([
5
6
  "human_allowed",
6
7
  "human_refused",
@@ -141,6 +142,18 @@ export const DENIED_BY_MAY_NAME_EXTENSION = {
141
142
  read_boundary: false,
142
143
  mode: false,
143
144
  };
145
+ export const DENIED_BY_MAY_ECHO = {
146
+ policy: false,
147
+ hook: false,
148
+ org: false,
149
+ persisted_rule: false,
150
+ classifier: false,
151
+ compliance: false,
152
+ write_protection: false,
153
+ ask_resolution: true,
154
+ read_boundary: true,
155
+ mode: false,
156
+ };
144
157
  const retired = (word, retiredIn) => Object.freeze({ word, retiredIn });
145
158
  export const RETIRED_MEMBERS = Object.freeze({
146
159
  askClass: Object.freeze([retired("write_protection_unresolved", "7.49.0"), retired("governance_unavailable", "7.51.0")]),
@@ -211,7 +224,7 @@ function clearanceDefects(v, settled, released) {
211
224
  }
212
225
  return out;
213
226
  }
214
- const DENY_ONLY_MEMBERS = Object.freeze(["deniedBy", "cause", "mode", "askClass", "classes", "extension"]);
227
+ const DENY_ONLY_MEMBERS = Object.freeze(["deniedBy", "cause", "mode", "askClass", "classes", "extension", "echoed"]);
215
228
  function objectOf(v) {
216
229
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
217
230
  }
@@ -331,6 +344,12 @@ export function screenGateOutcome(g, opts) {
331
344
  if (layer && !(isDeniedBy(denied.deniedBy) && DENIED_BY_MAY_NAME_EXTENSION[denied.deniedBy]))
332
345
  defects.push(`I12: an extension cannot be named beside deniedBy "${String(denied.deniedBy)}"`);
333
346
  }
347
+ if (denied.echoed !== undefined) {
348
+ for (const defect of refusalEchoDefects(denied.echoed))
349
+ defects.push(`I13: disposition.${defect}`);
350
+ if (layer && !(isDeniedBy(denied.deniedBy) && DENIED_BY_MAY_ECHO[denied.deniedBy]))
351
+ defects.push(`I13: quoted literals cannot be filed beside deniedBy "${String(denied.deniedBy)}"`);
352
+ }
334
353
  if (denied.askClass !== undefined && !member("askClass", denied.askClass))
335
354
  defects.push(outside("disposition.askClass", "askClass", denied.askClass));
336
355
  if (denied.classes !== undefined && !classList(denied.classes))
@@ -1,4 +1,5 @@
1
1
  import type { ExecutionEnv, ReadFloor } from "../internal/harness-types.js";
2
+ import { type RepositoryProbe } from "../tools/fs/shell-read-object-path.js";
2
3
  /** The managed parent (under the repository root) that holds every managed worktree — the reference implementation's
3
4
  * `.claude/worktrees/` under this project's brand — so {@link pruneWorktrees} and a userland reaper find orphans by one known
4
5
  * location. Every tree the engine mints lives at `<repoRoot>/.sema/worktrees/<slug>` (see {@link managedWorktreeDir}). */
@@ -11,11 +12,33 @@ export declare function managedWorktreeDir(repoRoot: string, name: string): stri
11
12
  * when `dir` is not shaped as a managed tree. Literal, byte-exact segments (no case fold): this answer EXEMPTS, and a fold
12
13
  * would widen an exemption. */
13
14
  export declare function managedWorktreeBaseOf(dir: string): string | undefined;
15
+ /** The managed tree `dir` is in — `dir` itself, or its nearest ancestor shaped as one (a task root in `pkg/` of a session's tree
16
+ * sits at `<tree>/pkg`) — as its root and the checkout it was minted under; `undefined` when no level is a managed tree or a
17
+ * level below the tree is `.` / `..` (where that lands is not decided lexically, and this answer exempts). */
18
+ export declare function managedTreeAt(dir: string): {
19
+ readonly root: string;
20
+ readonly base: string;
21
+ } | undefined;
22
+ /**
23
+ * THE repository root the managed parent is anchored at (the path law): the root of the checkout `dir` belongs
24
+ * to, read through the one repository-top reader ({@link repositoryTopOf} — no second walk). A managed tree is checked out
25
+ * BELOW the repository root it was minted under and its `.git` is a `gitdir:` file, which the top reader answers `undefined`
26
+ * for; so a `dir` at or below a managed tree (its root, a subdirectory of it, a symlink alias of either — read on the
27
+ * canonical spelling) is first peeled to the root before the marker's outermost occurrence (a tree minted by an older engine
28
+ * under another tree peels all the way out). `undefined` where the reader has no answer — not a repository, a linked work tree
29
+ * of the person's own, a submodule, a lookup the environment did not answer; the caller then stays at the root it was given.
30
+ */
31
+ export declare function repositoryRootOf(env: RepositoryProbe, dir: string, signal?: AbortSignal): Promise<string | undefined>;
32
+ /** Where the managed parent hangs for a mint asked at `root`: the repository root when the reader names one, spelled as the
33
+ * caller spelled `root` whenever that is the same directory (a consumer comparing the tree's path with its own root's keeps
34
+ * one spelling); `root` itself when no repository root is named. */
35
+ export declare function managedAnchorOf(env: ExecutionEnv, root: string): Promise<string>;
14
36
  /** The branch the path law gives the managed tree at `dir` (`sema/<slug>`), or `undefined` when `dir` is not a managed tree —
15
37
  * what a recorded branch must equal before anything deletes it (a record cannot name some other branch for removal). */
16
38
  export declare function managedWorktreeBranchOf(dir: string): string | undefined;
17
39
  export interface AddWorktreeOptions {
18
- /** The base repository root — where `git worktree add` runs (the base env's cwd is typically this). */
40
+ /** Where the mint is asked (the caller's task root — a checkout of the repository, typically its root). The managed parent
41
+ * hangs at the REPOSITORY root that checkout belongs to ({@link repositoryRootOf}); with no repository root named, here. */
19
42
  repoRoot: string;
20
43
  /** Stable per-task identity: with no {@link name}, the tree's name is this (sanitized) plus a random suffix — a fresh name
21
44
  * per mint, for the lanes that mint one tree per child. */
@@ -36,6 +59,14 @@ export interface AddWorktreeOptions {
36
59
  * step's failure (the add's refuses the mint before anything exists). Absent ⇒ the starts carry none (no run). */
37
60
  readFloor?: () => ReadFloor | undefined;
38
61
  }
62
+ /** Single-quote a path for the `exec` command STRING (the Shell API takes a command string, not argv). */
63
+ export declare function shq(s: string): string;
64
+ /**
65
+ * THE path law's symlink half: from `.sema` down to the tree's own directory, NO level may be a symlink — a link committed to
66
+ * the repository at any of them would redirect the mint outside it. Three levels exactly (the slug is one directory, see
67
+ * {@link slugOf}); a level that does not exist yet is fine (git creates it), and a level whose kind cannot be read refuses.
68
+ */
69
+ export declare function symlinkedLevel(env: ExecutionEnv, repoRoot: string, worktreeDir: string): Promise<string | undefined>;
39
70
  /**
40
71
  * Remove a managed worktree and — by the ONE branch rule — its branch: the branch is deleted only when its tip is still the
41
72
  * commit the tree was minted at (it carries nothing the tree made); otherwise it is kept, so commits made in the tree stay
@@ -47,10 +78,13 @@ export interface AddWorktreeOptions {
47
78
  * deregisters worktrees whose directory is gone). Check the result, retry once (the observed failures are transient),
48
79
  * and report the outcome.
49
80
  */
50
- export declare function removeManagedWorktree(baseEnv: ExecutionEnv, repoRoot: string, worktreeDir: string, branch?: {
81
+ export declare function removeManagedWorktree(baseEnv: ExecutionEnv, repoRoot: string, worktreeDir: string, branch: {
51
82
  readonly name: string;
52
83
  readonly baseSha: string;
53
- }, readFloor?: () => ReadFloor | undefined): Promise<{
84
+ } | undefined, readFloor: (() => ReadFloor | undefined) | undefined,
85
+ /** `"discard"` removes the tree whatever it holds (`--force`: the caller already decided its changes go); `"clean"` lets git
86
+ * refuse a tree with changes (no `--force`: whatever lands between the caller's own check and the removal keeps the tree). */
87
+ how: "discard" | "clean"): Promise<{
54
88
  ok: true;
55
89
  branchDeleted?: string;
56
90
  branchKept?: string;
@@ -81,6 +115,31 @@ export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOpti
81
115
  branch: string;
82
116
  baseSha?: string;
83
117
  }>;
118
+ /**
119
+ * THE managed-tree mint with no environment attached: judges the name, anchors the managed parent at the repository root,
120
+ * refuses a symlinked level, runs `git worktree add` (a name whose directory or branch exists is refused) and registers the
121
+ * parent in the repository-local ignore file. {@link addWorktree} wraps it with a tree-rooted env whose destroy removes the
122
+ * tree; a session checkout keeps the tree past every env and removes it only on release.
123
+ */
124
+ export declare function mintManagedWorktree(baseEnv: ExecutionEnv, opts: Pick<AddWorktreeOptions, "repoRoot" | "sessionId" | "name" | "commit" | "readFloor">): Promise<{
125
+ worktreeDir: string;
126
+ name: string;
127
+ branch: string;
128
+ anchor: string;
129
+ baseSha?: string;
130
+ }>;
131
+ /**
132
+ * Resolve the commit a new tree starts from, by the base words EnterWorktree and the session declaration share: `"head"` =
133
+ * the current local HEAD; `"fresh"` = the default branch tip (origin's HEAD symbolic ref → local main → local master → HEAD,
134
+ * the fallback named in `note`). Run where the mint is asked (`repoRoot`).
135
+ */
136
+ export declare function resolveBaseCommit(env: ExecutionEnv, repoRoot: string, baseRef: "fresh" | "head", readFloor: ReadFloor | undefined): Promise<{
137
+ sha: string;
138
+ label: string;
139
+ note?: string;
140
+ } | {
141
+ error: string;
142
+ }>;
84
143
  /** Reap orphaned worktrees (after a crash removed their dirs) — `git worktree prune` deregisters them. A userland
85
144
  * reaper calls this periodically against the base repo; core ships no post-kill Runner hook.
86
145
  *
@@ -1,5 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { thrownLabel, thrownText } from "./thrown-value.js";
3
+ import { repositoryTopOf } from "../tools/fs/shell-read-object-path.js";
4
+ import { pathFamilyOf } from "../tools/fs/safety.js";
3
5
  export const WORKTREE_PARENT = ".sema/worktrees";
4
6
  const WORKTREE_BRANCH_PREFIX = "sema";
5
7
  const NAME_SEGMENT = /^[a-zA-Z0-9._-]+$/;
@@ -33,15 +35,41 @@ export function managedWorktreeBaseOf(dir) {
33
35
  const base = parts.slice(0, -3).join("/");
34
36
  return base === "" ? "/" : base;
35
37
  }
38
+ export function managedTreeAt(dir) {
39
+ const parts = dir.split("/");
40
+ for (let end = parts.length; end >= 4; end--) {
41
+ const root = parts.slice(0, end).join("/");
42
+ const base = managedWorktreeBaseOf(root);
43
+ if (base === undefined)
44
+ continue;
45
+ return parts.slice(end).some((s) => s === "." || s === "..") ? undefined : { root, base };
46
+ }
47
+ return undefined;
48
+ }
49
+ const MANAGED_MARKER = `/${WORKTREE_PARENT}/`;
50
+ export async function repositoryRootOf(env, dir, signal) {
51
+ const canonical = await env.canonicalPath(dir, signal);
52
+ const spelled = canonical.ok ? canonical.value : dir;
53
+ const at = spelled.indexOf(MANAGED_MARKER);
54
+ const base = at < 0 ? dir : at === 0 ? "/" : spelled.slice(0, at);
55
+ return repositoryTopOf(env, base, pathFamilyOf({ root: base }), signal);
56
+ }
57
+ export async function managedAnchorOf(env, root) {
58
+ const top = await repositoryRootOf(env, root);
59
+ if (top === undefined)
60
+ return root;
61
+ const own = await env.canonicalPath(root);
62
+ return own.ok && own.value === top ? root : top;
63
+ }
36
64
  export function managedWorktreeBranchOf(dir) {
37
65
  if (managedWorktreeBaseOf(dir) === undefined)
38
66
  return undefined;
39
67
  return `${WORKTREE_BRANCH_PREFIX}/${dir.slice(dir.lastIndexOf("/") + 1)}`;
40
68
  }
41
- function shq(s) {
69
+ export function shq(s) {
42
70
  return `'${s.replace(/'/g, "'\\''")}'`;
43
71
  }
44
- async function symlinkedLevel(env, repoRoot, worktreeDir) {
72
+ export async function symlinkedLevel(env, repoRoot, worktreeDir) {
45
73
  for (const level of [`${repoRoot}/.sema`, `${repoRoot}/${WORKTREE_PARENT}`, worktreeDir]) {
46
74
  const info = await env.fileInfo(level);
47
75
  if (!info.ok) {
@@ -55,13 +83,13 @@ async function symlinkedLevel(env, repoRoot, worktreeDir) {
55
83
  }
56
84
  return undefined;
57
85
  }
58
- export async function removeManagedWorktree(baseEnv, repoRoot, worktreeDir, branch, readFloor) {
86
+ export async function removeManagedWorktree(baseEnv, repoRoot, worktreeDir, branch, readFloor, how) {
59
87
  const readFloorNow = () => { const f = readFloor?.(); return f !== undefined ? { readFloor: f } : {}; };
60
88
  let detail = "";
61
89
  let removed = false;
62
90
  for (let attempt = 0; attempt < 2 && !removed; attempt++) {
63
91
  try {
64
- const r = await baseEnv.exec(`git worktree remove --force ${shq(worktreeDir)}`, { cwd: repoRoot, ...readFloorNow() });
92
+ const r = await baseEnv.exec(`git worktree remove ${how === "discard" ? "--force " : ""}${shq(worktreeDir)}`, { cwd: repoRoot, ...readFloorNow() });
65
93
  if (r.ok && r.value.exitCode === 0)
66
94
  removed = true;
67
95
  else
@@ -93,13 +121,42 @@ export async function removeManagedWorktree(baseEnv, repoRoot, worktreeDir, bran
93
121
  }
94
122
  }
95
123
  export async function addWorktree(baseEnv, opts) {
124
+ const { worktreeDir, name, branch, anchor, baseSha } = await mintManagedWorktree(baseEnv, opts);
125
+ const branchRule = baseSha !== undefined ? { name: branch, baseSha } : undefined;
126
+ let inner;
127
+ try {
128
+ inner = await opts.rootEnvAt(worktreeDir);
129
+ }
130
+ catch (err) {
131
+ await removeManagedWorktree(baseEnv, anchor, worktreeDir, branchRule, opts.readFloor, "discard");
132
+ throw err;
133
+ }
134
+ const innerDestroy = inner.destroy;
135
+ const env = inner;
136
+ env.destroy = async () => {
137
+ try {
138
+ if (typeof innerDestroy === "function")
139
+ await innerDestroy.call(inner);
140
+ }
141
+ finally {
142
+ const removed = await removeManagedWorktree(baseEnv, anchor, worktreeDir, branchRule, opts.readFloor, "discard");
143
+ if (!removed.ok) {
144
+ throw new Error(`git worktree remove failed twice — ${worktreeDir} is now an orphan (dir + registration remain; ` +
145
+ `\`git worktree prune\` cannot reclaim it while the dir exists — remove it manually): ${removed.detail}`);
146
+ }
147
+ }
148
+ };
149
+ return { env, worktreeDir, name, branch, ...(baseSha !== undefined ? { baseSha } : {}) };
150
+ }
151
+ export async function mintManagedWorktree(baseEnv, opts) {
96
152
  const name = opts.name ?? `${(opts.sessionId || "task").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 50)}-${randomUUID().slice(0, 8)}`;
97
153
  const nameProblem = worktreeNameProblem(name);
98
154
  if (nameProblem !== undefined)
99
155
  throw new Error(nameProblem);
100
- const worktreeDir = managedWorktreeDir(opts.repoRoot, name);
156
+ const anchor = await managedAnchorOf(baseEnv, opts.repoRoot);
157
+ const worktreeDir = managedWorktreeDir(anchor, name);
101
158
  const branch = `${WORKTREE_BRANCH_PREFIX}/${slugOf(name)}`;
102
- const symlinked = await symlinkedLevel(baseEnv, opts.repoRoot, worktreeDir);
159
+ const symlinked = await symlinkedLevel(baseEnv, anchor, worktreeDir);
103
160
  if (symlinked !== undefined)
104
161
  throw new Error(symlinked);
105
162
  const readFloorNow = () => { const readFloor = opts.readFloor?.(); return readFloor !== undefined ? { readFloor } : {}; };
@@ -114,37 +171,41 @@ export async function addWorktree(baseEnv, opts) {
114
171
  const excludeLine = shq(`/${WORKTREE_PARENT}/`);
115
172
  await Promise.resolve()
116
173
  .then(() => baseEnv.exec(`ex="$(git rev-parse --git-path info/exclude)" && mkdir -p "$(dirname "$ex")" && ` +
117
- `{ grep -qxF ${excludeLine} "$ex" 2>/dev/null || printf '%s\\n' ${excludeLine} >> "$ex"; }`, { cwd: opts.repoRoot, ...readFloorNow() }))
174
+ `{ grep -qxF ${excludeLine} "$ex" 2>/dev/null || printf '%s\\n' ${excludeLine} >> "$ex"; }`, { cwd: anchor, ...readFloorNow() }))
118
175
  .catch(() => undefined);
119
176
  const baseSha = await Promise.resolve()
120
177
  .then(() => baseEnv.exec("git rev-parse HEAD", { cwd: worktreeDir, ...readFloorNow() }))
121
178
  .then((r) => (r.ok && r.value.exitCode === 0 && r.value.stdout.trim() !== "" ? r.value.stdout.trim() : undefined))
122
179
  .catch(() => undefined);
123
- const branchRule = baseSha !== undefined ? { name: branch, baseSha } : undefined;
124
- let inner;
125
- try {
126
- inner = await opts.rootEnvAt(worktreeDir);
127
- }
128
- catch (err) {
129
- await removeManagedWorktree(baseEnv, opts.repoRoot, worktreeDir, branchRule, opts.readFloor);
130
- throw err;
180
+ return { worktreeDir, name, branch, anchor, ...(baseSha !== undefined ? { baseSha } : {}) };
181
+ }
182
+ export async function resolveBaseCommit(env, repoRoot, baseRef, readFloor) {
183
+ const rev = async (ref) => {
184
+ const r = await env.exec(`git rev-parse --verify --quiet ${shq(`${ref}^{commit}`)}`, { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
185
+ return r.ok && r.value.exitCode === 0 ? r.value.stdout.trim() : undefined;
186
+ };
187
+ if (baseRef === "head") {
188
+ const sha = await rev("HEAD");
189
+ return sha ? { sha, label: "HEAD" } : { error: "cannot resolve HEAD (empty repository with no commits?)" };
131
190
  }
132
- const innerDestroy = inner.destroy;
133
- const env = inner;
134
- env.destroy = async () => {
135
- try {
136
- if (typeof innerDestroy === "function")
137
- await innerDestroy.call(inner);
191
+ const sym = await env.exec("git symbolic-ref --quiet refs/remotes/origin/HEAD", { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
192
+ if (sym.ok && sym.value.exitCode === 0) {
193
+ const branch = sym.value.stdout.trim().replace(/^refs\/remotes\//, "");
194
+ if (branch) {
195
+ const sha = await rev(branch);
196
+ if (sha)
197
+ return { sha, label: branch };
138
198
  }
139
- finally {
140
- const removed = await removeManagedWorktree(baseEnv, opts.repoRoot, worktreeDir, branchRule, opts.readFloor);
141
- if (!removed.ok) {
142
- throw new Error(`git worktree remove failed twice — ${worktreeDir} is now an orphan (dir + registration remain; ` +
143
- `\`git worktree prune\` cannot reclaim it while the dir exists — remove it manually): ${removed.detail}`);
144
- }
145
- }
146
- };
147
- return { env, worktreeDir, name, branch, ...(baseSha !== undefined ? { baseSha } : {}) };
199
+ }
200
+ for (const candidate of ["main", "master"]) {
201
+ const sha = await rev(candidate);
202
+ if (sha)
203
+ return { sha, label: candidate };
204
+ }
205
+ const sha = await rev("HEAD");
206
+ return sha
207
+ ? { sha, label: "HEAD", note: " (no remote default branch or local main/master found — fell back to HEAD)" }
208
+ : { error: "cannot resolve a fresh base (no default branch and no HEAD)" };
148
209
  }
149
210
  export async function pruneWorktrees(baseEnv, repoRoot, readFloor) {
150
211
  try {