@sema-agent/core 7.57.0 → 7.59.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 (399) hide show
  1. package/CHANGELOG.md +1161 -0
  2. package/README.md +6 -4
  3. package/dist/agents/cc-peer-directory.js +8 -8
  4. package/dist/agents/child-model-seat.d.ts +4 -2
  5. package/dist/agents/child-model-seat.js +5 -3
  6. package/dist/agents/peer-directory.d.ts +9 -0
  7. package/dist/agents/peer-directory.js +6 -2
  8. package/dist/agents/send-message-tool.js +21 -12
  9. package/dist/agents/subagent-steps.js +2 -4
  10. package/dist/agents/subagent.js +33 -34
  11. package/dist/brain/anthropic.js +161 -45
  12. package/dist/brain/errors.d.ts +9 -3
  13. package/dist/brain/errors.js +7 -1
  14. package/dist/brain/failover.js +2 -1
  15. package/dist/brain/open-responses.js +3 -3
  16. package/dist/brain/openai.js +103 -53
  17. package/dist/brain/provider-dialect.d.ts +11 -0
  18. package/dist/brain/provider-dialect.js +5 -2
  19. package/dist/brain/reasoning-request.js +5 -4
  20. package/dist/brain/reasoning.d.ts +19 -0
  21. package/dist/brain/reasoning.js +17 -2
  22. package/dist/brain/request-route.d.ts +4 -1
  23. package/dist/brain/request-route.js +4 -1
  24. package/dist/brain/route-adjudicator.d.ts +84 -18
  25. package/dist/brain/route-adjudicator.js +89 -22
  26. package/dist/brain/route-conformance.js +1 -1
  27. package/dist/brain/stream-engine.js +84 -49
  28. package/dist/brain/stream-shared.d.ts +30 -0
  29. package/dist/brain/stream-shared.js +34 -1
  30. package/dist/brain/timeout.d.ts +62 -5
  31. package/dist/brain/timeout.js +93 -6
  32. package/dist/core/a2a.d.ts +2 -1
  33. package/dist/core/a2a.js +23 -10
  34. package/dist/core/account-row.d.ts +61 -0
  35. package/dist/core/account-row.js +51 -0
  36. package/dist/core/advisor-verdict.d.ts +2 -1
  37. package/dist/core/advisor-verdict.js +1 -1
  38. package/dist/core/allow-entry.d.ts +20 -7
  39. package/dist/core/allow-entry.js +18 -9
  40. package/dist/core/approval-object.d.ts +29 -15
  41. package/dist/core/approval-object.js +47 -19
  42. package/dist/core/ask-origin.d.ts +21 -2
  43. package/dist/core/ask-origin.js +5 -1
  44. package/dist/core/auto-compaction.d.ts +4 -0
  45. package/dist/core/auto-compaction.js +2 -2
  46. package/dist/core/auto-mode-directive.d.ts +29 -5
  47. package/dist/core/auto-mode-directive.js +38 -8
  48. package/dist/core/background-agent-store.d.ts +16 -3
  49. package/dist/core/checkpoint-requirements.d.ts +19 -1
  50. package/dist/core/checkpoint-requirements.js +5 -1
  51. package/dist/core/checkpoint-store.d.ts +85 -23
  52. package/dist/core/checkpoint-store.js +31 -9
  53. package/dist/core/child-clamp-seats.d.ts +29 -0
  54. package/dist/core/child-clamp-seats.js +56 -1
  55. package/dist/core/compliance.d.ts +2 -2
  56. package/dist/core/compliance.js +1 -1
  57. package/dist/core/effective-path-target.d.ts +8 -2
  58. package/dist/core/effective-path-target.js +8 -3
  59. package/dist/core/engine-notice.d.ts +99 -9
  60. package/dist/core/engine-notice.js +19 -5
  61. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  62. package/dist/core/fs-write-gate-policy.js +7 -3
  63. package/dist/core/gate-fold.js +7 -4
  64. package/dist/core/gate-lanes.js +19 -6
  65. package/dist/core/gate-outcome.d.ts +32 -3
  66. package/dist/core/gate-outcome.js +19 -1
  67. package/dist/core/git-worktree-env.d.ts +53 -11
  68. package/dist/core/git-worktree-env.js +96 -12
  69. package/dist/core/governance-codes.d.ts +9 -1
  70. package/dist/core/governance-codes.js +13 -0
  71. package/dist/core/hooks.d.ts +35 -4
  72. package/dist/core/hooks.js +17 -11
  73. package/dist/core/human-input-projection.d.ts +1 -0
  74. package/dist/core/human-input-projection.js +3 -0
  75. package/dist/core/image-admission.d.ts +6 -5
  76. package/dist/core/image-admission.js +18 -14
  77. package/dist/core/locked-config.d.ts +20 -3
  78. package/dist/core/locked-config.js +40 -3
  79. package/dist/core/mailbox-store.d.ts +45 -1
  80. package/dist/core/mailbox-store.js +53 -9
  81. package/dist/core/mcp-call-meta.d.ts +66 -0
  82. package/dist/core/mcp-call-meta.js +103 -0
  83. package/dist/core/mcp-connection-pool.d.ts +3 -1
  84. package/dist/core/mcp-connection-pool.js +3 -1
  85. package/dist/core/mcp-failure.d.ts +117 -15
  86. package/dist/core/mcp-failure.js +71 -3
  87. package/dist/core/mcp-probe.d.ts +4 -0
  88. package/dist/core/mcp-probe.js +1 -1
  89. package/dist/core/mcp-server-link.d.ts +27 -3
  90. package/dist/core/mcp-server-link.js +25 -1
  91. package/dist/core/mcp-server-spec.d.ts +46 -18
  92. package/dist/core/mcp-server-spec.js +1 -18
  93. package/dist/core/mcp.d.ts +16 -20
  94. package/dist/core/mcp.js +112 -55
  95. package/dist/core/memory-engine/consolidation-driver.d.ts +2 -4
  96. package/dist/core/memory-engine/consolidation-driver.js +3 -3
  97. package/dist/core/memory-engine/consolidation.d.ts +4 -0
  98. package/dist/core/memory-engine/consolidation.js +1 -0
  99. package/dist/core/memory-engine/delegation-settlement.js +5 -12
  100. package/dist/core/memory-engine/distiller.js +2 -2
  101. package/dist/core/memory-engine/dual-root.d.ts +50 -1
  102. package/dist/core/memory-engine/dual-root.js +44 -1
  103. package/dist/core/memory-engine/engine.d.ts +67 -14
  104. package/dist/core/memory-engine/engine.js +384 -212
  105. package/dist/core/memory-engine/export-bundle.d.ts +23 -0
  106. package/dist/core/memory-engine/export-bundle.js +23 -4
  107. package/dist/core/memory-engine/file-backend.d.ts +128 -55
  108. package/dist/core/memory-engine/file-backend.js +290 -117
  109. package/dist/core/memory-engine/index.d.ts +1 -1
  110. package/dist/core/memory-engine/layout.d.ts +59 -11
  111. package/dist/core/memory-engine/layout.js +190 -40
  112. package/dist/core/memory-engine/memory-backend-contract.d.ts +1 -1
  113. package/dist/core/memory-engine/memory-backend-contract.js +39 -2
  114. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  115. package/dist/core/memory-engine/scope-contract.js +80 -11
  116. package/dist/core/memory-engine/sync-client.d.ts +9 -1
  117. package/dist/core/memory-engine/sync-client.js +31 -8
  118. package/dist/core/memory-engine/sync.d.ts +5 -0
  119. package/dist/core/memory-engine/types.d.ts +6 -0
  120. package/dist/core/mode-policy.d.ts +8 -5
  121. package/dist/core/mode-policy.js +5 -4
  122. package/dist/core/mods/classic-events.d.ts +5 -1
  123. package/dist/core/mods/host.js +1 -1
  124. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  125. package/dist/core/mods/kernel/dispatch.js +12 -9
  126. package/dist/core/mods/kernel/events.d.ts +6 -1
  127. package/dist/core/mods/kernel/events.js +2 -2
  128. package/dist/core/mods/kernel/registration.d.ts +9 -1
  129. package/dist/core/mods/kernel/registration.js +3 -0
  130. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  131. package/dist/core/mods/kernel/site-rules.js +10 -0
  132. package/dist/core/mods/package.d.ts +23 -0
  133. package/dist/core/mods/package.js +118 -0
  134. package/dist/core/mods/stations.d.ts +33 -12
  135. package/dist/core/mods/stations.js +45 -11
  136. package/dist/core/mods/tool-call.d.ts +5 -1
  137. package/dist/core/mods/tool-call.js +13 -4
  138. package/dist/core/parent-spec-seat.d.ts +8 -3
  139. package/dist/core/parent-spec-seat.js +2 -0
  140. package/dist/core/park-selfcheck.js +6 -0
  141. package/dist/core/path-guard-rows.d.ts +20 -0
  142. package/dist/core/path-guard-rows.js +11 -0
  143. package/dist/core/peer-seat.d.ts +248 -0
  144. package/dist/core/peer-seat.js +439 -0
  145. package/dist/core/permission-rule-consent.js +10 -4
  146. package/dist/core/permission-rule-model.d.ts +16 -0
  147. package/dist/core/permission-rule-model.js +1 -1
  148. package/dist/core/present-plan-tool.d.ts +20 -3
  149. package/dist/core/present-plan-tool.js +48 -4
  150. package/dist/core/protocol-http-auth.d.ts +40 -29
  151. package/dist/core/protocol-http-auth.js +30 -32
  152. package/dist/core/redaction-marks.d.ts +16 -0
  153. package/dist/core/redaction-marks.js +16 -0
  154. package/dist/core/redaction-passes.js +8 -9
  155. package/dist/core/resume-startup-cause.js +1 -0
  156. package/dist/core/retention.d.ts +41 -15
  157. package/dist/core/retention.js +59 -12
  158. package/dist/core/rewrite-rejudge.d.ts +38 -0
  159. package/dist/core/rewrite-rejudge.js +42 -2
  160. package/dist/core/roles.d.ts +34 -2
  161. package/dist/core/roles.js +43 -4
  162. package/dist/core/run-origin.d.ts +40 -0
  163. package/dist/core/run-origin.js +37 -0
  164. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  165. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  166. package/dist/core/runner/announce-once-ledger.d.ts +5 -4
  167. package/dist/core/runner/announce-once-ledger.js +4 -2
  168. package/dist/core/runner/call-hook-stations.js +2 -2
  169. package/dist/core/runner/compaction-restate.d.ts +15 -6
  170. package/dist/core/runner/compaction-restate.js +28 -2
  171. package/dist/core/runner/contracts.d.ts +33 -21
  172. package/dist/core/runner/credential-origin-seat.js +4 -3
  173. package/dist/core/runner/cwd-alignment-probe.d.ts +20 -0
  174. package/dist/core/runner/cwd-alignment-probe.js +21 -0
  175. package/dist/core/runner/decide-continuation.d.ts +2 -2
  176. package/dist/core/runner/gate-exit.d.ts +30 -8
  177. package/dist/core/runner/gate-exit.js +15 -8
  178. package/dist/core/runner/image-removed-seat.d.ts +12 -0
  179. package/dist/core/runner/image-removed-seat.js +19 -0
  180. package/dist/core/runner/inline-image.js +1 -1
  181. package/dist/core/runner/memory-consolidation-driver.js +3 -3
  182. package/dist/core/runner/park-commit.d.ts +1 -1
  183. package/dist/core/runner/park-commit.js +3 -0
  184. package/dist/core/runner/prepare-ask-lane.d.ts +1 -1
  185. package/dist/core/runner/prepare-ask-lane.js +2 -1
  186. package/dist/core/runner/prepare-boundary-parks.js +2 -2
  187. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -5
  188. package/dist/core/runner/prepare-caps-and-workflow.js +3 -1
  189. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  190. package/dist/core/runner/prepare-config-doors.js +14 -10
  191. package/dist/core/runner/prepare-context-lane.js +2 -0
  192. package/dist/core/runner/prepare-delegation-surface.d.ts +8 -0
  193. package/dist/core/runner/prepare-delegation-surface.js +16 -18
  194. package/dist/core/runner/prepare-gate-stations.js +1 -1
  195. package/dist/core/runner/prepare-hands-readface.d.ts +11 -3
  196. package/dist/core/runner/prepare-hands-readface.js +9 -1
  197. package/dist/core/runner/prepare-inherited-gate.d.ts +1 -3
  198. package/dist/core/runner/prepare-inherited-gate.js +14 -27
  199. package/dist/core/runner/prepare-memory.d.ts +3 -0
  200. package/dist/core/runner/prepare-memory.js +26 -37
  201. package/dist/core/runner/prepare-park-ask.d.ts +1 -1
  202. package/dist/core/runner/prepare-park-ask.js +2 -1
  203. package/dist/core/runner/prepare-policy-chain.d.ts +7 -7
  204. package/dist/core/runner/prepare-policy-chain.js +18 -15
  205. package/dist/core/runner/prepare-project-context.d.ts +2 -2
  206. package/dist/core/runner/prepare-project-context.js +2 -2
  207. package/dist/core/runner/prepare-prompt-inputs.d.ts +1 -1
  208. package/dist/core/runner/prepare-prompt-inputs.js +8 -19
  209. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  210. package/dist/core/runner/prepare-protocol-tools.js +11 -3
  211. package/dist/core/runner/prepare-run-refs.d.ts +2 -3
  212. package/dist/core/runner/prepare-run-refs.js +4 -1
  213. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  214. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  215. package/dist/core/runner/prepare-task.js +28 -13
  216. package/dist/core/runner/prepare-wiring-manifest.d.ts +2 -1
  217. package/dist/core/runner/prepare-wiring-manifest.js +4 -3
  218. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  219. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  220. package/dist/core/runner/reply-pricing.d.ts +30 -0
  221. package/dist/core/runner/reply-pricing.js +19 -0
  222. package/dist/core/runner/resume-admission.js +5 -3
  223. package/dist/core/runner/resume-apply.js +6 -1
  224. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  225. package/dist/core/runner/resume-policy-outcome.js +5 -5
  226. package/dist/core/runner/role-seat-defaulted.d.ts +44 -0
  227. package/dist/core/runner/role-seat-defaulted.js +40 -0
  228. package/dist/core/runner/run-brain-sinks.js +2 -0
  229. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  230. package/dist/core/runner/run-harness-handlers.js +1 -8
  231. package/dist/core/runner/run-identity-wiring.d.ts +2 -5
  232. package/dist/core/runner/run-identity-wiring.js +6 -4
  233. package/dist/core/runner/run-leg.d.ts +2 -0
  234. package/dist/core/runner/run-leg.js +42 -29
  235. package/dist/core/runner/run-notification-lane.js +3 -0
  236. package/dist/core/runner/run-stop-and-final-verify.js +2 -2
  237. package/dist/core/runner/run-terminal-adoption.d.ts +2 -5
  238. package/dist/core/runner/run-terminal-adoption.js +9 -3
  239. package/dist/core/runner/run-turn-boundary.js +77 -70
  240. package/dist/core/runner/runtask.d.ts +1 -1
  241. package/dist/core/runner/runtask.js +2 -2
  242. package/dist/core/runner/side-call-account.d.ts +1 -1
  243. package/dist/core/runner/side-call-account.js +3 -18
  244. package/dist/core/runner/sub-agent-deny-lists.d.ts +24 -0
  245. package/dist/core/runner/sub-agent-deny-lists.js +10 -0
  246. package/dist/core/runner/terminal-account.js +3 -3
  247. package/dist/core/runner/tool-end-body.js +2 -1
  248. package/dist/core/runner/tool-occurrence.d.ts +5 -2
  249. package/dist/core/runner/tool-occurrence.js +4 -3
  250. package/dist/core/runner/turn-attachments.d.ts +26 -22
  251. package/dist/core/runner/turn-attachments.js +24 -26
  252. package/dist/core/runner/write-protection-station.d.ts +8 -2
  253. package/dist/core/runner/write-protection-station.js +2 -0
  254. package/dist/core/runner-deps.d.ts +3 -3
  255. package/dist/core/secret-env.d.ts +32 -2
  256. package/dist/core/secret-env.js +65 -3
  257. package/dist/core/sensitive-path-policy.js +9 -10
  258. package/dist/core/session-log-transfer.d.ts +24 -0
  259. package/dist/core/session-log-transfer.js +166 -0
  260. package/dist/core/session-policy-store.d.ts +3 -1
  261. package/dist/core/session-policy-store.js +13 -9
  262. package/dist/core/session-store.d.ts +86 -24
  263. package/dist/core/session-store.js +162 -24
  264. package/dist/core/session.d.ts +92 -1
  265. package/dist/core/shell-read-silence.js +1 -0
  266. package/dist/core/side-query.d.ts +11 -1
  267. package/dist/core/side-query.js +9 -0
  268. package/dist/core/skill-grant-binding.d.ts +31 -2
  269. package/dist/core/skill-grant-binding.js +31 -1
  270. package/dist/core/skill-grant.d.ts +8 -5
  271. package/dist/core/skill-grant.js +6 -6
  272. package/dist/core/steer-replay.d.ts +4 -2
  273. package/dist/core/steer-replay.js +2 -1
  274. package/dist/core/store-contracts/background-agent-store-contract.js +27 -0
  275. package/dist/core/store-contracts/checkpoint-store-contract.js +20 -2
  276. package/dist/core/store-contracts/mailbox-store-contract.js +31 -1
  277. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  278. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  279. package/dist/core/store-contracts/session-store-contract.js +236 -2
  280. package/dist/core/synthetic-read-verdict.js +2 -1
  281. package/dist/core/task-event.d.ts +92 -8
  282. package/dist/core/task-notification.js +16 -10
  283. package/dist/core/task-registry-agent.js +1 -0
  284. package/dist/core/task-registry-shared.d.ts +7 -1
  285. package/dist/core/task-spec.d.ts +49 -1
  286. package/dist/core/task-stream.d.ts +2 -1
  287. package/dist/core/terminal-cause.d.ts +11 -1
  288. package/dist/core/tool-catalog-entries.js +1 -0
  289. package/dist/core/tool-check-reading.d.ts +1 -0
  290. package/dist/core/tool-check-reading.js +3 -3
  291. package/dist/core/tool-policy.d.ts +16 -0
  292. package/dist/core/tool-result-store.d.ts +17 -10
  293. package/dist/core/tool-result-store.js +3 -1
  294. package/dist/core/tool-roster.d.ts +112 -5
  295. package/dist/core/tool-roster.js +42 -1
  296. package/dist/core/tool-spec.d.ts +3 -1
  297. package/dist/core/types.d.ts +3 -3
  298. package/dist/core/types.js +1 -1
  299. package/dist/core/untrusted-egress.d.ts +0 -2
  300. package/dist/core/untrusted-egress.js +10 -14
  301. package/dist/core/user-attachment.js +1 -1
  302. package/dist/core/wiring-manifest.d.ts +18 -6
  303. package/dist/core/wiring-manifest.js +4 -3
  304. package/dist/core/workspace-snapshot.d.ts +44 -0
  305. package/dist/core/workspace-snapshot.js +34 -0
  306. package/dist/core/write-protect.d.ts +43 -3
  307. package/dist/core/write-protect.js +43 -16
  308. package/dist/engine/compaction/compaction.js +29 -3
  309. package/dist/engine/execution-env/node-execution-env.d.ts +4 -3
  310. package/dist/engine/execution-env/node-execution-env.js +24 -23
  311. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  312. package/dist/engine/harness/agent-harness.d.ts +30 -2
  313. package/dist/engine/harness/agent-harness.js +43 -12
  314. package/dist/engine/harness/messages.d.ts +3 -1
  315. package/dist/engine/harness/messages.js +3 -2
  316. package/dist/engine/harness/types.d.ts +56 -7
  317. package/dist/engine/harness/types.js +5 -1
  318. package/dist/engine/llm/rejected-images.d.ts +46 -0
  319. package/dist/engine/llm/rejected-images.js +54 -0
  320. package/dist/engine/llm/tool-turns.d.ts +2 -1
  321. package/dist/engine/llm/types.d.ts +30 -10
  322. package/dist/engine/llm/types.js +1 -1
  323. package/dist/engine/loop/agent-loop.d.ts +8 -0
  324. package/dist/engine/loop/agent-loop.js +52 -15
  325. package/dist/engine/loop/types.d.ts +3 -1
  326. package/dist/engine/session/import-validate.js +3 -0
  327. package/dist/engine/session/memory-repo.d.ts +17 -9
  328. package/dist/engine/session/memory-repo.js +44 -34
  329. package/dist/engine/session/path-to-root.d.ts +38 -0
  330. package/dist/engine/session/path-to-root.js +39 -0
  331. package/dist/engine/session/repo-utils.d.ts +22 -4
  332. package/dist/engine/session/repo-utils.js +49 -1
  333. package/dist/engine/session/storage-base.d.ts +10 -1
  334. package/dist/engine/session/storage-base.js +11 -22
  335. package/dist/index.d.ts +29 -16
  336. package/dist/index.js +21 -11
  337. package/dist/internal/harness-types.d.ts +2 -2
  338. package/dist/internal/harness.d.ts +3 -2
  339. package/dist/internal/harness.js +2 -2
  340. package/dist/internal/llm.d.ts +1 -0
  341. package/dist/orchestration/workflow-observe.d.ts +17 -1
  342. package/dist/orchestration/workflow-observe.js +20 -0
  343. package/dist/orchestration/workflow-types.d.ts +32 -7
  344. package/dist/orchestration/workflow.js +739 -489
  345. package/dist/shell/counting-pass.d.ts +50 -0
  346. package/dist/shell/counting-pass.js +502 -0
  347. package/dist/shell/lex.d.ts +4 -2
  348. package/dist/shell/lex.js +93 -34
  349. package/dist/shell/shell-words.d.ts +1 -1
  350. package/dist/shell/shell-words.js +7 -6
  351. package/dist/stores/file/index.d.ts +4 -1
  352. package/dist/stores/file/index.js +4 -1
  353. package/dist/stores/file/mailbox-store.js +6 -10
  354. package/dist/stores/file/session-store.d.ts +15 -8
  355. package/dist/stores/file/session-store.js +28 -13
  356. package/dist/tools/fs/fs-bash.d.ts +6 -0
  357. package/dist/tools/fs/fs-bash.js +6 -3
  358. package/dist/tools/fs/fs-write.d.ts +6 -3
  359. package/dist/tools/fs/fs-write.js +8 -7
  360. package/dist/tools/fs/index.d.ts +3 -0
  361. package/dist/tools/fs/index.js +7 -3
  362. package/dist/tools/fs/program-read-model.d.ts +13 -0
  363. package/dist/tools/fs/program-read-model.js +15 -0
  364. package/dist/tools/fs/program-read-model.rows.js +1 -1
  365. package/dist/tools/fs/read-deny.d.ts +13 -10
  366. package/dist/tools/fs/read-deny.js +25 -5
  367. package/dist/tools/fs/read-floor.d.ts +19 -0
  368. package/dist/tools/fs/read-floor.js +23 -0
  369. package/dist/tools/fs/safety.js +40 -8
  370. package/dist/tools/fs/search.js +6 -24
  371. package/dist/tools/fs/shell-read-check.d.ts +9 -2
  372. package/dist/tools/fs/shell-read-check.js +61 -16
  373. package/dist/tools/fs/shell-read-establish.js +2 -1
  374. package/dist/tools/fs/shell-read-identity.js +1 -1
  375. package/dist/tools/fs/shell-read-judge.d.ts +26 -9
  376. package/dist/tools/fs/shell-read-judge.js +10 -6
  377. package/dist/tools/fs/shell-read-plan.d.ts +6 -1
  378. package/dist/tools/fs/shell-read-plan.js +22 -15
  379. package/dist/tools/fs/shell-read-start.js +1 -0
  380. package/dist/tools/fs/shell-reentry-text.d.ts +15 -1
  381. package/dist/tools/fs/shell-reentry-text.js +25 -3
  382. package/dist/tools/monitor.d.ts +4 -0
  383. package/dist/tools/monitor.js +2 -0
  384. package/dist/tools/worktree.d.ts +42 -15
  385. package/dist/tools/worktree.js +60 -32
  386. package/package.json +5 -2
  387. package/test/export-surface.snapshot.json +149 -1
  388. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  389. package/wire-changes/core-stores-sql@7.59.0.json +29 -0
  390. package/wire-changes/core@7.58.0.json +2188 -0
  391. package/wire-changes/core@7.59.0.json +2459 -0
  392. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  393. package/wire-changes/mods-kernel@7.59.0.json +29 -0
  394. package/wire-changes/primitives@7.58.0.json +29 -0
  395. package/wire-changes/primitives@7.59.0.json +29 -0
  396. package/dist/primitives/credential-ref.d.ts +0 -89
  397. package/dist/primitives/credential-ref.js +0 -125
  398. package/dist/primitives/index.d.ts +0 -2
  399. package/dist/primitives/index.js +0 -1
@@ -20,8 +20,10 @@ export interface FsWriteGatePolicyOptions {
20
20
  * the `acceptDirs`/`exemptDirs` entries below always resolve against THIS value. */
21
21
  rootPath?: string;
22
22
  /** Writes whose canonical target lands inside one of these dirs are ALLOWED (the accept-session
23
- * domain, e.g. the cwd subtree after "allow all edits during this session"). */
24
- acceptDirs?: readonly string[];
23
+ * domain, e.g. the cwd subtree after "allow all edits during this session"). A getter is read once per
24
+ * call — a leg's live write roots, which move with its write location — and its entries are CANONICAL
25
+ * identities, compared as keys (a fixed list is resolved per call, as before). */
26
+ acceptDirs?: readonly string[] | (() => readonly string[]);
25
27
  /** Writes whose canonical target lands inside one of these dirs are ALLOWED and never asked
26
28
  * (auto-approved working areas: the scratchpad dir, plan files). Checked before `acceptDirs`
27
29
  * (same verdict — the split is intent/observability, exemptions are structural not session-won).
@@ -42,7 +42,11 @@ function assertExemptDirsDoNotCoverRoot(exemptDirs, rootLexical) {
42
42
  }
43
43
  export function createFsWriteGatePolicy(opts) {
44
44
  const { env, rootPath, defaultWrite } = opts;
45
- const acceptDirs = opts.acceptDirs && opts.acceptDirs.length > 0 ? opts.acceptDirs : undefined;
45
+ const acceptDirsSeat = opts.acceptDirs;
46
+ const acceptDirsNow = () => {
47
+ const dirs = typeof acceptDirsSeat === "function" ? acceptDirsSeat() : acceptDirsSeat;
48
+ return dirs !== undefined && dirs.length > 0 ? dirs : undefined;
49
+ };
46
50
  const exemptDirs = opts.exemptDirs && opts.exemptDirs.length > 0 ? opts.exemptDirs : undefined;
47
51
  const rootLexical = absoluteRootOf(rootPath, env.cwd);
48
52
  assertExemptDirsDoNotCoverRoot(exemptDirs, rootLexical);
@@ -80,12 +84,12 @@ export function createFsWriteGatePolicy(opts) {
80
84
  let refusedDomain;
81
85
  for (const [dirs, structural] of [
82
86
  [exemptDirs, true],
83
- [acceptDirs, false],
87
+ [acceptDirsNow(), false],
84
88
  ]) {
85
89
  if (!dirs)
86
90
  continue;
87
91
  for (const raw of dirs) {
88
- const dir = await canonicalizeTarget(env, raw, signal, pathFamilyOf({ root: rootPath ?? env.cwd }), rootPath);
92
+ const dir = !structural && typeof acceptDirsSeat === "function" ? { ok: true, key: raw } : await canonicalizeTarget(env, raw, signal, pathFamilyOf({ root: rootPath ?? env.cwd }), rootPath);
89
93
  if (!dir.ok)
90
94
  continue;
91
95
  if (structural) {
@@ -3,9 +3,9 @@ import { markTightenMessage } from "./safety-axis-vocab.js";
3
3
  import { PROBE_REASON_MAX, normalizeProbeCause } from "./checkpoint-store.js";
4
4
  import { normalizeReadRootCandidate } from "./read-root-candidate.js";
5
5
  import { engineFailClosedExit, hookDenyExit } from "./runner/gate-exit.js";
6
- import { readRejudge, screenRewrite } from "./rewrite-rejudge.js";
6
+ import { noteRewrite, POLICY_AUTHOR, readRejudge, screenRewrite } from "./rewrite-rejudge.js";
7
7
  import { traceHookCrash } from "./gate-crash-trace.js";
8
- import { writeProtectionMandated, writeProtectionTightenDecision } from "./write-protect.js";
8
+ import { writeProtectionMandated, writeProtectionReachOf, writeProtectionTightenDecision } from "./write-protect.js";
9
9
  import { createGateDeadline, awaitWriteProtectionJudgment, gateWaitFailureOf, withGateTimeout } from "./gate-bounded-await.js";
10
10
  import { shellReadFaceWords } from "../tools/fs/shell-read-face.js";
11
11
  import { failedJudgmentDeny } from "./runner/policy-throw.js";
@@ -45,7 +45,7 @@ export async function runGateFold(pass) {
45
45
  const second = await screenRewrite(pass.screening, pass.req, rewritten.form, `the rewritten call to "${toolName}"`);
46
46
  if (second.kind === "refused") {
47
47
  pass.currentInput = rewritten.form;
48
- return second.by === "hook" ? hookDenyExit(pass, second.reason) : await engineFailClosedExit(pass, second.reason);
48
+ return second.by === "hook" ? hookDenyExit(pass, second.reason, second.extension) : await engineFailClosedExit(pass, second.reason, second.extension);
49
49
  }
50
50
  if (second.answer?.additionalContext)
51
51
  pass.preToolContext.push(second.answer.additionalContext);
@@ -54,6 +54,7 @@ export async function runGateFold(pass) {
54
54
  }
55
55
  if ((pass.decision.action === "allow" || pass.decision.action === "ask") && pass.decision.updatedInput !== undefined) {
56
56
  pass.policyRewrite = argsAsTheToolReads(pass.req, pass.decision.updatedInput);
57
+ noteRewrite(pass.rewrites, pass.req, pass.currentInput, pass.policyRewrite, POLICY_AUTHOR);
57
58
  }
58
59
  else if (pass.hookAsk?.updatedInput !== undefined) {
59
60
  pass.policyRewrite = argsAsTheToolReads(pass.req, pass.hookAsk.updatedInput);
@@ -170,7 +171,7 @@ export async function runGateFold(pass) {
170
171
  traceHookCrash(input, new Error(`write-protection judge ${kind === "timeout" ? "timed out" : "threw"} for tool "${toolName}" (toolCallId ${toolCallId}) — this call's write target could not be judged: ${thrownText(err)}`), notifier);
171
172
  });
172
173
  if (verdict !== undefined && writeProtectionMandated(verdict))
173
- pass.writeProtected = true;
174
+ pass[writeProtectionReachOf(verdict) === "spelling" ? "writeProtected" : "writeProtectedOnDisk"] = true;
174
175
  const decision = verdict === undefined ? undefined : writeProtectionTightenDecision(toolName, verdict);
175
176
  if (decision !== undefined && (writeProtectionStanding === "allow" || decision.action === "deny")) {
176
177
  pass.decision = decision;
@@ -208,6 +209,8 @@ function applyShellReadVerdict(pass, answer, toolName, shellGated) {
208
209
  pass.shellWritesPlaced = true;
209
210
  if (verdict.writeProtected === true)
210
211
  pass.writeProtected = true;
212
+ if (verdict.writeProtectedOnDisk === true)
213
+ pass.writeProtectedOnDisk = true;
211
214
  if (verdict.targetUnresolved === true)
212
215
  pass.targetUnresolved = true;
213
216
  if (verdict.unplacedOptions !== undefined)
@@ -1,6 +1,6 @@
1
1
  import { argsAsTheToolReads, withArgsReading } from "./effective-path-target.js";
2
2
  import { attest, attestationOf, bindableArgsOf, decisionText, foldHookAsk, refusalOf, refuseOutOfContractDecision } from "./tool-policy.js";
3
- import { outletAsk, readRejudge, rewriteChasedSentence, screenRewrite } from "./rewrite-rejudge.js";
3
+ import { APPROVER_AUTHOR, extensionAuthors, noteRewrite, outletAsk, POLICY_AUTHOR, readRejudge, rewriteChasedSentence, screenRewrite } from "./rewrite-rejudge.js";
4
4
  import { arbitrateByMode, classifyAsk, decisionAskClassesOf, dontAskRefusalMessage, fileCommandOptionsSentence, persistedRuleMandateOf, safetyAxisOf, stampAskOrigin } from "./ask-origin.js";
5
5
  import { classifierParseFailureDenyMessage, denialLimitFallbackMessage, rungDidNotRule, unarmedWindow } from "./auto-mode.js";
6
6
  import { classifierNoRulingArm, settleNoRulingAsk } from "./classifier-unavailable-arm.js";
@@ -77,6 +77,7 @@ export async function runGateLanes(pass) {
77
77
  requiresUserInteraction: input.requiresUserInteraction,
78
78
  probeUnanswered: pass.probeUnanswered === true,
79
79
  writeProtected: pass.writeProtected === true,
80
+ writeProtectedOnDisk: pass.writeProtectedOnDisk === true,
80
81
  targetUnresolved: pass.targetUnresolved === true,
81
82
  });
82
83
  const readFaceNow = input.readFace?.();
@@ -201,9 +202,10 @@ export async function runGateLanes(pass) {
201
202
  };
202
203
  return await readToolChecks(chains, standing, { toolName, judged: args, rewrite, request: Object.freeze({ ...pass.req, args }), signal }, project);
203
204
  };
204
- const refuseByExtension = (deny) => {
205
+ const refuseByExtension = (deny, by) => {
205
206
  pass.decision = deny;
206
207
  pass.deniedBy = settledRefusal?.deniedBy ?? "hook";
208
+ pass.deniedExtension = settledRefusal === undefined ? by : undefined;
207
209
  pass.denyCause = settledRefusal?.cause;
208
210
  };
209
211
  if (pass.decision.action === "allow") {
@@ -211,7 +213,7 @@ export async function runGateLanes(pass) {
211
213
  if (read !== undefined)
212
214
  pass.toolCheckRaised = true;
213
215
  if (read?.kind === "denied")
214
- refuseByExtension(read.deny);
216
+ refuseByExtension(read.deny, read.by);
215
217
  else if (read?.kind === "asked")
216
218
  pass.decision = read.ask;
217
219
  else if (read?.kind === "approved")
@@ -352,7 +354,7 @@ export async function runGateLanes(pass) {
352
354
  if (pass.toolCheckRaised !== true && pass.decision.action !== "deny") {
353
355
  const read = await checkTool(pass.decision, pass.currentInput, orgAnswer.org, pass.policyRewrite, allowMayClear);
354
356
  if (read?.kind === "denied")
355
- refuseByExtension(read.deny);
357
+ refuseByExtension(read.deny, read.by);
356
358
  else if (read?.kind === "cleared")
357
359
  pass.decision = await clearAs("hook", { entries: read.entries, clear: () => read.allow, afterClear: async () => undefined });
358
360
  else if (read?.kind === "asked") {
@@ -553,6 +555,7 @@ export async function runGateLanes(pass) {
553
555
  }
554
556
  if (approvedWithArgs && pass.decision.action === "allow" && pass.decision.updatedInput !== undefined) {
555
557
  let editArgs = pass.decision.updatedInput;
558
+ let shownToApprover = { bytes: pass.policyRewrite ?? pass.currentInput };
556
559
  let editDenied;
557
560
  let editAnswer = pass.decision;
558
561
  let unanswered;
@@ -567,6 +570,9 @@ export async function runGateLanes(pass) {
567
570
  return await untakenValueExit(pass, { value: editArgs, message: taken.refusal, deniedBy: "ask_resolution" });
568
571
  }
569
572
  editArgs = argsAsTheToolReads(pass.req, taken.value);
573
+ if (shownToApprover !== undefined)
574
+ noteRewrite(pass.rewrites, pass.req, shownToApprover.bytes, editArgs, APPROVER_AUTHOR);
575
+ shownToApprover = undefined;
570
576
  if (round >= 3) {
571
577
  editDenied = {
572
578
  action: "deny",
@@ -578,10 +584,11 @@ export async function runGateLanes(pass) {
578
584
  let editHookAsk;
579
585
  let rewrittenEdit = false;
580
586
  if (screening !== undefined) {
581
- const screened = await screening.screen(editArgs, `the approved edit for "${toolName}"`);
587
+ const screened = await screening.screen(editArgs, `the approved edit for "${toolName}"`, pass.req);
582
588
  if (screened.kind === "refused") {
583
589
  editDenied = { action: "deny", message: screened.reason };
584
590
  pass.deniedBy = "hook";
591
+ pass.deniedExtension = screened.extension;
585
592
  break;
586
593
  }
587
594
  const hr = screened.answer;
@@ -591,6 +598,7 @@ export async function runGateLanes(pass) {
591
598
  if (hr.action === "deny") {
592
599
  editDenied = { action: "deny", message: decisionText(hr) ?? `the approved edit for "${toolName}" was blocked by a PreToolUse hook` };
593
600
  pass.deniedBy = "hook";
601
+ pass.deniedExtension = screened.answeredBy;
594
602
  break;
595
603
  }
596
604
  if (hr.action === "ask") {
@@ -599,6 +607,7 @@ export async function runGateLanes(pass) {
599
607
  }
600
608
  const hookRead = readRejudge(pass.req, editArgs, hr);
601
609
  if (hookRead.kind === "rewritten") {
610
+ noteRewrite(pass.rewrites, pass.req, editArgs, hookRead.form, extensionAuthors(screened.rewrittenBy ?? []));
602
611
  editArgs = hookRead.form;
603
612
  rewrittenEdit = true;
604
613
  }
@@ -642,12 +651,14 @@ export async function runGateLanes(pass) {
642
651
  pass.deniedBy = "policy";
643
652
  break;
644
653
  }
654
+ noteRewrite(pass.rewrites, pass.req, editArgs, policyRead.form, POLICY_AUTHOR);
645
655
  editArgs = policyRead.form;
646
656
  rewrittenEdit = true;
647
657
  const second = screening !== undefined ? await screenRewrite(screening, pass.req, editArgs, `the rewritten edit for "${toolName}"`) : undefined;
648
658
  if (second?.kind === "refused") {
649
659
  editDenied = { action: "deny", message: second.reason };
650
660
  pass.deniedBy = "hook";
661
+ pass.deniedExtension = second.extension;
651
662
  break;
652
663
  }
653
664
  if (second?.kind === "stands") {
@@ -714,12 +725,13 @@ export async function runGateLanes(pass) {
714
725
  }
715
726
  const editRead = await checkTool(editDecision, editArgs, editOrg.org, undefined);
716
727
  if (editRead?.kind === "denied") {
717
- refuseByExtension(editRead.deny);
728
+ refuseByExtension(editRead.deny, editRead.by);
718
729
  editDenied = editRead.deny;
719
730
  break;
720
731
  }
721
732
  if (editRead?.kind === "approved") {
722
733
  carriedOwnAsk = editRead.outstanding ?? (editDecision.action === "ask" ? editDecision : undefined);
734
+ shownToApprover = { bytes: editArgs };
723
735
  editArgs = editRead.allow.updatedInput;
724
736
  editAnswer = editRead.allow;
725
737
  continue;
@@ -766,6 +778,7 @@ export async function runGateLanes(pass) {
766
778
  if (rr.updatedInput === undefined) {
767
779
  break;
768
780
  }
781
+ shownToApprover = { bytes: editArgs };
769
782
  editArgs = rr.updatedInput;
770
783
  editAnswer = rr;
771
784
  if (editAskDecision.action === "ask")
@@ -345,6 +345,24 @@ export declare const DENIED_BY_MAY_CARRY_CAUSE: {
345
345
  };
346
346
  /** Compile-time fence: `never` while every deny layer has a cause row. */
347
347
  export type CauseTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedBy, keyof typeof DENIED_BY_MAY_CARRY_CAUSE>>;
348
+ /** Which deny layers may name the extension whose handler ended the call ({@link GateDisposition}'s `extension`): the hook layer
349
+ * alone — an extension's `tool.check` answer or failure is a hook-layer refusal, and no other layer's verdict is an extension's.
350
+ * The mint reads it as the producer and the screen (invariant I12) as the archive: one table, two readers. Module-level only; not
351
+ * part of the package root. */
352
+ export declare const DENIED_BY_MAY_NAME_EXTENSION: {
353
+ readonly policy: false;
354
+ readonly hook: true;
355
+ readonly org: false;
356
+ readonly persisted_rule: false;
357
+ readonly classifier: false;
358
+ readonly compliance: false;
359
+ readonly write_protection: false;
360
+ readonly ask_resolution: false;
361
+ readonly read_boundary: false;
362
+ readonly mode: false;
363
+ };
364
+ /** Compile-time fence: `never` while every deny layer has an extension-naming row. */
365
+ export type ExtensionTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedBy, keyof typeof DENIED_BY_MAY_NAME_EXTENSION>>;
348
366
  /** The final disposition of a gate pass. `cause` is present exactly when the deny came out of an auto-mode
349
367
  * classifier round that did not RULE ({@link ClassifierDenyCause}); a ruling block and every non-classifier
350
368
  * deny carry none. Invariant I5 ({@link screenGateOutcome}): a cause stands only beside a layer word in
@@ -371,7 +389,15 @@ export type CauseTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedB
371
389
  * record is, with `positions` for a list member (the indices of those entries in the list the run received — a host maps them
372
390
  * onto the declaration it sent for this run). Present exactly when an allow member cleared a standing ask and nobody answered
373
391
  * it: absent on a call nothing asked about, a mode's release or acceptance, the read-only arm's, the classifier's or the
374
- * sandbox's allow, and a person's yes. Additive. Invariant I9 ({@link screenGateOutcome}) screens its shape. */
392
+ * sandbox's allow, and a person's yes. Additive. Invariant I9 ({@link screenGateOutcome}) screens its shape.
393
+ *
394
+ * `extension` — on the denied arm only: the registration name of the extension whose handler ended the call at the hook layer,
395
+ * by its `deny` answer (`tool.check`, `classic.PreToolUse`, `tool.call`) or by its failure (a throw, a budget overrun, an
396
+ * answer the station cannot take — the engine fails the call closed). Present exactly when `deniedBy` is `hook` and the
397
+ * refusing handler's registration is known; ABSENT beside every other layer word (an ancestor leg's screening reaches a
398
+ * descendant as a `policy` refusal, and a refusal an inherited installation's question settled is that question's), and beside
399
+ * a `hook` refusal that names no registration (the engine's own failed raise, a cancel). A display and audit fact: the call is
400
+ * refused whatever the name. Additive. Invariant I12 ({@link screenGateOutcome}) screens its shape. */
375
401
  export type GateDisposition = {
376
402
  kind: "allowed";
377
403
  classifier?: AutoModeClassifierRound;
@@ -385,6 +411,7 @@ export type GateDisposition = {
385
411
  mode?: ModeRefusal["mode"];
386
412
  askClass?: AskClass;
387
413
  classes?: readonly AskClass[];
414
+ extension?: string;
388
415
  };
389
416
  /**
390
417
  * A permission MODE released a surviving ask — the allowed disposition's account of the question it did not put
@@ -443,6 +470,8 @@ export interface ModeRefusal {
443
470
  * whole number when present, and `positions` — only on a list member (`request`, `deployment`) — a list of non-negative
444
471
  * whole numbers;
445
472
  * I10 `settlement.when` present ⇒ a finite number (epoch ms — the moment the wait ended is a value a reader can order);
473
+ * I12 `disposition.extension` present ⇒ the denied arm, a layer word {@link DENIED_BY_MAY_NAME_EXTENSION} admits (the hook layer),
474
+ * and a non-empty string (a registration's name);
446
475
  * I11 a winner's `decision` stated beside the record (the caller reads a durable row: `winnerDecision`) ⇒ a word a winner holds,
447
476
  * and its direction (allow: `allow` / `approve` / `edit`; refusal: `deny` / `reject`) is the direction of the record's
448
477
  * settlement ({@link SETTLEMENT_IS_REFUSAL}) and of its disposition (`allowed` / `denied`) — one decision, one direction.
@@ -514,7 +543,7 @@ export declare function isRetiredMember<S extends MemberSet>(set: S, word: unkno
514
543
  */
515
544
  export declare function releasePolicyDefects(g: unknown): string[];
516
545
  /** The members only the denied arm of a {@link GateDisposition} carries. */
517
- declare const DENY_ONLY_MEMBERS: readonly ["deniedBy", "cause", "mode", "askClass", "classes"];
546
+ declare const DENY_ONLY_MEMBERS: readonly ["deniedBy", "cause", "mode", "askClass", "classes", "extension"];
518
547
  type DenyOnlyMember = Exclude<keyof Extract<GateDisposition, {
519
548
  kind: "denied";
520
549
  }>, keyof Extract<GateDisposition, {
@@ -523,7 +552,7 @@ type DenyOnlyMember = Exclude<keyof Extract<GateDisposition, {
523
552
  /** Compile-time fence: `never` while the list is exactly the denied arm's own members. */
524
553
  export type DenyOnlyMembersAreListed = AssertAllKeysHandled<Exclude<DenyOnlyMember, (typeof DENY_ONLY_MEMBERS)[number]> | Exclude<(typeof DENY_ONLY_MEMBERS)[number], DenyOnlyMember>>;
525
554
  /**
526
- * The one invariant screen for a {@link GateOutcome} (I1–I11 above, plus the closed-set word each member carries). Two readings:
555
+ * The one invariant screen for a {@link GateOutcome} (I1–I12 above, plus the closed-set word each member carries). Two readings:
527
556
  * - `"archive"` (the default) — a record read back from where it was kept (a replay, a ledger, a durable row): its shape, with
528
557
  * every closed set read as its live members plus {@link RETIRED_MEMBERS}. A record lawful when minted is not a defect later.
529
558
  * - `"producer"` — a record THIS engine is composing or publishing now: the live sets alone, and the engine's release law
@@ -119,6 +119,18 @@ export const DENIED_BY_MAY_CARRY_CAUSE = {
119
119
  read_boundary: false,
120
120
  mode: false,
121
121
  };
122
+ export const DENIED_BY_MAY_NAME_EXTENSION = {
123
+ policy: false,
124
+ hook: true,
125
+ org: false,
126
+ persisted_rule: false,
127
+ classifier: false,
128
+ compliance: false,
129
+ write_protection: false,
130
+ ask_resolution: false,
131
+ read_boundary: false,
132
+ mode: false,
133
+ };
122
134
  const retired = (word, retiredIn) => Object.freeze({ word, retiredIn });
123
135
  export const RETIRED_MEMBERS = Object.freeze({
124
136
  askClass: Object.freeze([retired("write_protection_unresolved", "7.49.0"), retired("governance_unavailable", "7.51.0")]),
@@ -189,7 +201,7 @@ function clearanceDefects(v, settled, released) {
189
201
  }
190
202
  return out;
191
203
  }
192
- const DENY_ONLY_MEMBERS = Object.freeze(["deniedBy", "cause", "mode", "askClass", "classes"]);
204
+ const DENY_ONLY_MEMBERS = Object.freeze(["deniedBy", "cause", "mode", "askClass", "classes", "extension"]);
193
205
  function objectOf(v) {
194
206
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
195
207
  }
@@ -303,6 +315,12 @@ export function screenGateOutcome(g, opts) {
303
315
  }
304
316
  if (modeRefusal && (denied.askClass === undefined || denied.classes === undefined))
305
317
  defects.push("I8: a mode refusal carries askClass and classes");
318
+ if (denied.extension !== undefined) {
319
+ if (typeof denied.extension !== "string" || denied.extension === "")
320
+ defects.push(`I12: disposition.extension ${spelled(denied.extension)} is not a registration name (a non-empty string)`);
321
+ if (layer && !(isDeniedBy(denied.deniedBy) && DENIED_BY_MAY_NAME_EXTENSION[denied.deniedBy]))
322
+ defects.push(`I12: an extension cannot be named beside deniedBy "${String(denied.deniedBy)}"`);
323
+ }
306
324
  if (denied.askClass !== undefined && !member("askClass", denied.askClass))
307
325
  defects.push(outside("disposition.askClass", "askClass", denied.askClass));
308
326
  if (denied.classes !== undefined && !classList(denied.classes))
@@ -1,12 +1,28 @@
1
1
  import type { ExecutionEnv } from "../internal/harness-types.js";
2
- /** Private parent dir (under the repo root) that holds all managed worktrees, so {@link pruneWorktrees} and a
3
- * userland reaper can find orphans by a single known location. */
4
- export declare const WORKTREE_PARENT = ".sema-worktrees";
2
+ /** The managed parent (under the repository root) that holds every managed worktree — the reference implementation's
3
+ * `.claude/worktrees/` under this project's brand — so {@link pruneWorktrees} and a userland reaper find orphans by one known
4
+ * location. Every tree the engine mints lives at `<repoRoot>/.sema/worktrees/<slug>` (see {@link managedWorktreeDir}). */
5
+ export declare const WORKTREE_PARENT = ".sema/worktrees";
6
+ /** Why `name` is not a managed worktree name, or `undefined` when it is one. */
7
+ export declare function worktreeNameProblem(name: string): string | undefined;
8
+ /** THE managed location of the tree named `name` under `repoRoot`. */
9
+ export declare function managedWorktreeDir(repoRoot: string, name: string): string;
10
+ /** The checkout a managed worktree directory was minted under — `dir` minus its `/.sema/worktrees/<slug>` tail — or `undefined`
11
+ * when `dir` is not shaped as a managed tree. Literal, byte-exact segments (no case fold): this answer EXEMPTS, and a fold
12
+ * would widen an exemption. */
13
+ export declare function managedWorktreeBaseOf(dir: string): string | undefined;
14
+ /** The branch the path law gives the managed tree at `dir` (`sema/<slug>`), or `undefined` when `dir` is not a managed tree —
15
+ * what a recorded branch must equal before anything deletes it (a record cannot name some other branch for removal). */
16
+ export declare function managedWorktreeBranchOf(dir: string): string | undefined;
5
17
  export interface AddWorktreeOptions {
6
18
  /** The base repository root — where `git worktree add` runs (the base env's cwd is typically this). */
7
19
  repoRoot: string;
8
- /** Stable per-task identity, sanitized into the worktree dir name (for human-readable orphan diagnosis). */
20
+ /** Stable per-task identity: with no {@link name}, the tree's name is this (sanitized) plus a random suffix — a fresh name
21
+ * per mint, for the lanes that mint one tree per child. */
9
22
  sessionId: string;
23
+ /** The managed name ({@link worktreeNameProblem} grammar), used as given: the tree lands at `.sema/worktrees/<slug>` on the
24
+ * new branch `sema/<slug>`. A name whose directory or branch already exists is refused, never reused or reset. */
25
+ name?: string;
10
26
  /**
11
27
  * How to build a worktree-ROOTED {@link ExecutionEnv} for THIS env type — the only env-specific bit. Local:
12
28
  * `(dir) => new NodeExecutionEnv({ cwd: dir })`. A single-E2B deployment: an E2B env whose cwd is `dir`. The
@@ -17,16 +33,39 @@ export interface AddWorktreeOptions {
17
33
  commit?: string;
18
34
  }
19
35
  /**
20
- * design/97 CORE-6 — the env-agnostic git-WORKTREE isolation primitive. Creates a detached worktree under
21
- * {@link WORKTREE_PARENT} in `repoRoot` (via the BASE env's shell) and returns a worktree-ROOTED ExecutionEnv
22
- * (built by `rootEnvAt`) whose `destroy()` removes the worktree. A control-plane `executionEnvFactory` calls this
23
- * when its `ctx.isolation === "worktree"` and returns the result (with `destroy`); for a non-isolated task it
24
- * returns the SHARED base env (no `destroy`) so the Runner never tears the base down.
36
+ * Remove a managed worktree and — by the ONE branch rule — its branch: the branch is deleted only when its tip is still the
37
+ * commit the tree was minted at (it carries nothing the tree made); otherwise it is kept, so commits made in the tree stay
38
+ * reachable after the directory is gone. The branch half is best-effort (a branch left behind is a name, not an orphaned
39
+ * directory) and reported as `branchKept`.
40
+ *
41
+ * server [1796]②: the worktree removal itself used to be fire-and-forget — a transient failure (spawn EAGAIN/EMFILE under
42
+ * load) then left the directory AND its registration behind, which `git worktree prune` can never reclaim (prune only
43
+ * deregisters worktrees whose directory is gone). Check the result, retry once (the observed failures are transient),
44
+ * and report the outcome.
45
+ */
46
+ export declare function removeManagedWorktree(baseEnv: ExecutionEnv, repoRoot: string, worktreeDir: string, branch?: {
47
+ readonly name: string;
48
+ readonly baseSha: string;
49
+ }): Promise<{
50
+ ok: true;
51
+ branchDeleted?: string;
52
+ branchKept?: string;
53
+ } | {
54
+ ok: false;
55
+ detail: string;
56
+ }>;
57
+ /**
58
+ * design/97 CORE-6 — the env-agnostic git-WORKTREE isolation primitive, and the engine's ONE worktree mint. Creates a managed
59
+ * worktree at `<repoRoot>/.sema/worktrees/<slug>` on the new branch `sema/<slug>` (via the BASE env's shell, refusing when
60
+ * any level of that path is a symlink) and returns a worktree-ROOTED ExecutionEnv (built by `rootEnvAt`) whose `destroy()`
61
+ * removes the worktree (and its branch, by the branch rule of {@link removeManagedWorktree}). A control-plane
62
+ * `executionEnvFactory` calls this when its `ctx.isolation === "worktree"` and returns the result (with `destroy`); for a
63
+ * non-isolated task it returns the SHARED base env (no `destroy`) so the Runner never tears the base down.
25
64
  *
26
65
  * ISOLATE-ONLY: the runtime never merges — the orchestrator script reads each worktree's result and
27
66
  * decides verify/merge in userland. Caveats: `git worktree` isolates the git WORKING COPY, not
28
67
  * arbitrary shell access (bash can still reach the host — sandbox separately); UNCOMMITTED changes in the base
29
- * repo are absent in the child (detached HEAD); a worktree orphaned by a process crash is reaped by
68
+ * repo are absent in the child (the tree starts at the base commit); a worktree orphaned by a process crash is reaped by
30
69
  * {@link pruneWorktrees} (userland — there is no Runner hook for post-kill cleanup).
31
70
  */
32
71
  export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOptions): Promise<{
@@ -34,13 +73,16 @@ export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOpti
34
73
  destroy(): Promise<void>;
35
74
  };
36
75
  worktreeDir: string;
76
+ name: string;
77
+ branch: string;
78
+ baseSha?: string;
37
79
  }>;
38
80
  /** Reap orphaned worktrees (after a crash removed their dirs) — `git worktree prune` deregisters them. A userland
39
81
  * reaper calls this periodically against the base repo; core ships no post-kill Runner hook.
40
82
  *
41
83
  * HRD-PTL-11: the exec Result used to be discarded, so every caller had to ASSUME the prune landed — and
42
84
  * ExitWorktree's "already gone externally" leg told the model "stale git worktree metadata was pruned"
43
- * on a claim it could not have checked. Same fail-loud treatment {@link removeWorktree} already got
85
+ * on a claim it could not have checked. Same fail-loud treatment {@link removeManagedWorktree} already got
44
86
  * Report the outcome, let the caller decide what to say. Never throws (a throwing env
45
87
  * lands on the same `{ok:false}`), so a caller that ignores the value behaves exactly as before. */
46
88
  export declare function pruneWorktrees(baseEnv: ExecutionEnv, repoRoot: string): Promise<{
@@ -1,28 +1,107 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { thrownLabel, thrownText } from "./thrown-value.js";
3
- export const WORKTREE_PARENT = ".sema-worktrees";
3
+ export const WORKTREE_PARENT = ".sema/worktrees";
4
+ const WORKTREE_BRANCH_PREFIX = "sema";
5
+ const NAME_SEGMENT = /^[a-zA-Z0-9._-]+$/;
6
+ const NAME_MAX = 64;
7
+ export function worktreeNameProblem(name) {
8
+ if (name.length > NAME_MAX)
9
+ return `Invalid worktree name: must be ${NAME_MAX} characters or fewer (got ${name.length})`;
10
+ for (const segment of name.split("/")) {
11
+ if (segment === "." || segment === "..")
12
+ return `Invalid worktree name "${name}": must not contain "." or ".." path segments`;
13
+ if (segment.toLowerCase().replace(/\.+$/, "") === ".git")
14
+ return `Invalid worktree name "${name}": "${segment}" is a reserved git directory name`;
15
+ if (!NAME_SEGMENT.test(segment))
16
+ return `Invalid worktree name "${name}": each "/"-separated segment must be non-empty and contain only letters, digits, dots, underscores, and dashes`;
17
+ }
18
+ return undefined;
19
+ }
20
+ function slugOf(name) {
21
+ return name.replaceAll("/", "+");
22
+ }
23
+ export function managedWorktreeDir(repoRoot, name) {
24
+ return `${repoRoot}/${WORKTREE_PARENT}/${slugOf(name)}`;
25
+ }
26
+ export function managedWorktreeBaseOf(dir) {
27
+ const parts = dir.split("/");
28
+ if (parts.length < 4)
29
+ return undefined;
30
+ const [dot, parent, slug] = parts.slice(-3);
31
+ if (dot !== ".sema" || parent !== "worktrees" || slug === undefined || slug === "" || slug === "." || slug === "..")
32
+ return undefined;
33
+ const base = parts.slice(0, -3).join("/");
34
+ return base === "" ? "/" : base;
35
+ }
36
+ export function managedWorktreeBranchOf(dir) {
37
+ if (managedWorktreeBaseOf(dir) === undefined)
38
+ return undefined;
39
+ return `${WORKTREE_BRANCH_PREFIX}/${dir.slice(dir.lastIndexOf("/") + 1)}`;
40
+ }
4
41
  function shq(s) {
5
42
  return `'${s.replace(/'/g, "'\\''")}'`;
6
43
  }
7
- async function removeWorktree(baseEnv, repoRoot, worktreeDir) {
44
+ async function symlinkedLevel(env, repoRoot, worktreeDir) {
45
+ for (const level of [`${repoRoot}/.sema`, `${repoRoot}/${WORKTREE_PARENT}`, worktreeDir]) {
46
+ const info = await env.fileInfo(level);
47
+ if (!info.ok) {
48
+ if (info.error.code === "not_found")
49
+ continue;
50
+ return `Cannot create worktree: failed to read ${level} (${thrownText(info.error)}); a level of the managed path whose kind is unknown could be a symlink. Nothing was created.`;
51
+ }
52
+ if (info.value.kind === "symlink") {
53
+ return `Cannot create worktree: ${level} is a symlink. A symlink at .sema, .sema/worktrees or .sema/worktrees/<name> could redirect worktree creation outside the repository. Remove the symlink and retry.`;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+ export async function removeManagedWorktree(baseEnv, repoRoot, worktreeDir, branch) {
8
59
  let detail = "";
9
- for (let attempt = 0; attempt < 2; attempt++) {
60
+ let removed = false;
61
+ for (let attempt = 0; attempt < 2 && !removed; attempt++) {
10
62
  try {
11
63
  const r = await baseEnv.exec(`git worktree remove --force ${shq(worktreeDir)}`, { cwd: repoRoot });
12
64
  if (r.ok && r.value.exitCode === 0)
13
- return { ok: true };
14
- detail = r.ok ? r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}` : thrownText(r.error);
65
+ removed = true;
66
+ else
67
+ detail = r.ok ? r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}` : thrownText(r.error);
15
68
  }
16
69
  catch (err) {
17
70
  detail = thrownLabel(err);
18
71
  }
19
72
  }
20
- return { ok: false, detail };
73
+ if (!removed)
74
+ return { ok: false, detail };
75
+ if (branch === undefined || branch.name !== managedWorktreeBranchOf(worktreeDir))
76
+ return { ok: true };
77
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(branch.baseSha) || /^0+$/.test(branch.baseSha))
78
+ return { ok: true, branchKept: `${branch.name} (its base commit is not a usable witness)` };
79
+ try {
80
+ const del = await baseEnv.exec(`git update-ref --no-deref -d ${shq(`refs/heads/${branch.name}`)} ${shq(branch.baseSha)}`, { cwd: repoRoot });
81
+ if (del.ok && del.value.exitCode === 0)
82
+ return { ok: true, branchDeleted: branch.name };
83
+ const tip = await baseEnv.exec(`git rev-parse --verify --quiet ${shq(`refs/heads/${branch.name}`)}`, { cwd: repoRoot });
84
+ if (tip.ok && tip.value.exitCode !== 0)
85
+ return { ok: true };
86
+ if (tip.ok && tip.value.stdout.trim() !== branch.baseSha)
87
+ return { ok: true, branchKept: `${branch.name} (it carries commits made in the worktree)` };
88
+ return { ok: true, branchKept: `${branch.name} (it could not be deleted: ${del.ok ? (del.value.stderr || del.value.stdout).trim() : thrownText(del.error)})` };
89
+ }
90
+ catch (err) {
91
+ return { ok: true, branchKept: `${branch.name} (it could not be deleted: ${thrownLabel(err)})` };
92
+ }
21
93
  }
22
94
  export async function addWorktree(baseEnv, opts) {
23
- const safe = (opts.sessionId || "task").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
24
- const worktreeDir = `${opts.repoRoot}/${WORKTREE_PARENT}/${safe}-${randomUUID().slice(0, 8)}`;
25
- const add = await baseEnv.exec(`git worktree add --detach ${shq(worktreeDir)} ${shq(opts.commit ?? "HEAD")}`, {
95
+ const name = opts.name ?? `${(opts.sessionId || "task").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 50)}-${randomUUID().slice(0, 8)}`;
96
+ const nameProblem = worktreeNameProblem(name);
97
+ if (nameProblem !== undefined)
98
+ throw new Error(nameProblem);
99
+ const worktreeDir = managedWorktreeDir(opts.repoRoot, name);
100
+ const branch = `${WORKTREE_BRANCH_PREFIX}/${slugOf(name)}`;
101
+ const symlinked = await symlinkedLevel(baseEnv, opts.repoRoot, worktreeDir);
102
+ if (symlinked !== undefined)
103
+ throw new Error(symlinked);
104
+ const add = await baseEnv.exec(`git worktree add --no-track -b ${shq(branch)} ${shq(worktreeDir)} ${shq(opts.commit ?? "HEAD")}`, {
26
105
  cwd: opts.repoRoot,
27
106
  });
28
107
  if (!add.ok || add.value.exitCode !== 0) {
@@ -34,12 +113,17 @@ export async function addWorktree(baseEnv, opts) {
34
113
  .exec(`ex="$(git rev-parse --git-path info/exclude)" && mkdir -p "$(dirname "$ex")" && ` +
35
114
  `{ grep -qxF ${excludeLine} "$ex" 2>/dev/null || printf '%s\\n' ${excludeLine} >> "$ex"; }`, { cwd: opts.repoRoot })
36
115
  .catch(() => undefined);
116
+ const baseSha = await baseEnv
117
+ .exec("git rev-parse HEAD", { cwd: worktreeDir })
118
+ .then((r) => (r.ok && r.value.exitCode === 0 && r.value.stdout.trim() !== "" ? r.value.stdout.trim() : undefined))
119
+ .catch(() => undefined);
120
+ const branchRule = baseSha !== undefined ? { name: branch, baseSha } : undefined;
37
121
  let inner;
38
122
  try {
39
123
  inner = await opts.rootEnvAt(worktreeDir);
40
124
  }
41
125
  catch (err) {
42
- await removeWorktree(baseEnv, opts.repoRoot, worktreeDir);
126
+ await removeManagedWorktree(baseEnv, opts.repoRoot, worktreeDir, branchRule);
43
127
  throw err;
44
128
  }
45
129
  const innerDestroy = inner.destroy;
@@ -50,14 +134,14 @@ export async function addWorktree(baseEnv, opts) {
50
134
  await innerDestroy.call(inner);
51
135
  }
52
136
  finally {
53
- const removed = await removeWorktree(baseEnv, opts.repoRoot, worktreeDir);
137
+ const removed = await removeManagedWorktree(baseEnv, opts.repoRoot, worktreeDir, branchRule);
54
138
  if (!removed.ok) {
55
139
  throw new Error(`git worktree remove failed twice — ${worktreeDir} is now an orphan (dir + registration remain; ` +
56
140
  `\`git worktree prune\` cannot reclaim it while the dir exists — remove it manually): ${removed.detail}`);
57
141
  }
58
142
  }
59
143
  };
60
- return { env, worktreeDir };
144
+ return { env, worktreeDir, name, branch, ...(baseSha !== undefined ? { baseSha } : {}) };
61
145
  }
62
146
  export async function pruneWorktrees(baseEnv, repoRoot) {
63
147
  try {