@sema-agent/core 7.56.0 → 7.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/CHANGELOG.md +926 -0
  2. package/LICENSE +1 -1
  3. package/dist/agents/org-delivery-gate.js +3 -4
  4. package/dist/agents/peer-held-queue.d.ts +69 -49
  5. package/dist/agents/peer-held-queue.js +255 -106
  6. package/dist/agents/peer-session-drain.js +63 -43
  7. package/dist/agents/send-message-tool.js +3 -2
  8. package/dist/agents/subagent-steps.js +2 -4
  9. package/dist/agents/subagent.js +8 -8
  10. package/dist/brain/anthropic.js +16 -8
  11. package/dist/brain/open-responses.js +10 -8
  12. package/dist/brain/openai.js +11 -9
  13. package/dist/brain/provider-dialect.d.ts +3 -2
  14. package/dist/brain/provider-dialect.js +2 -2
  15. package/dist/brain/request-params.d.ts +6 -0
  16. package/dist/brain/request-params.js +14 -1
  17. package/dist/brain/route-adjudicator.js +2 -1
  18. package/dist/brain/stream-engine.d.ts +9 -0
  19. package/dist/brain/stream-engine.js +24 -10
  20. package/dist/brain/stream-shared.d.ts +5 -4
  21. package/dist/brain/stream-shared.js +4 -4
  22. package/dist/core/a2a.d.ts +2 -1
  23. package/dist/core/a2a.js +23 -10
  24. package/dist/core/allow-entry.d.ts +5 -11
  25. package/dist/core/allow-entry.js +19 -26
  26. package/dist/core/approval-object.d.ts +21 -5
  27. package/dist/core/approval-object.js +44 -17
  28. package/dist/core/ask-origin.d.ts +23 -4
  29. package/dist/core/ask-origin.js +5 -1
  30. package/dist/core/auto-compaction.d.ts +75 -6
  31. package/dist/core/auto-compaction.js +43 -27
  32. package/dist/core/auto-mode-directive.d.ts +29 -5
  33. package/dist/core/auto-mode-directive.js +38 -8
  34. package/dist/core/background-agent-store.d.ts +6 -2
  35. package/dist/core/background-agent-store.js +1 -1
  36. package/dist/core/checkpoint-requirements.d.ts +13 -1
  37. package/dist/core/checkpoint-requirements.js +4 -0
  38. package/dist/core/checkpoint-store.d.ts +44 -40
  39. package/dist/core/checkpoint-store.js +32 -14
  40. package/dist/core/cross-boundary-taint.js +4 -2
  41. package/dist/core/engine-notice.d.ts +4 -3
  42. package/dist/core/engine-notice.js +6 -0
  43. package/dist/core/file-history-store.d.ts +14 -8
  44. package/dist/core/file-history-store.js +14 -4
  45. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  46. package/dist/core/fs-write-gate-policy.js +7 -3
  47. package/dist/core/gate-fold.js +6 -3
  48. package/dist/core/gate-lanes.js +13 -5
  49. package/dist/core/git-worktree-env.d.ts +53 -11
  50. package/dist/core/git-worktree-env.js +96 -12
  51. package/dist/core/hooks.d.ts +6 -3
  52. package/dist/core/hooks.js +12 -5
  53. package/dist/core/human-input-projection.d.ts +1 -0
  54. package/dist/core/human-input-projection.js +3 -0
  55. package/dist/core/locked-config.d.ts +15 -1
  56. package/dist/core/locked-config.js +38 -2
  57. package/dist/core/mailbox-store.d.ts +62 -1
  58. package/dist/core/mailbox-store.js +59 -0
  59. package/dist/core/mcp-call-meta.d.ts +66 -0
  60. package/dist/core/mcp-call-meta.js +103 -0
  61. package/dist/core/mcp-connection-pool.d.ts +3 -1
  62. package/dist/core/mcp-connection-pool.js +3 -1
  63. package/dist/core/mcp-failure.d.ts +7 -1
  64. package/dist/core/mcp-failure.js +10 -0
  65. package/dist/core/mcp-name-judge.d.ts +46 -0
  66. package/dist/core/mcp-name-judge.js +61 -0
  67. package/dist/core/mcp-probe.d.ts +5 -1
  68. package/dist/core/mcp-probe.js +3 -6
  69. package/dist/core/mcp-server-link.d.ts +5 -2
  70. package/dist/core/mcp-server-spec.d.ts +46 -18
  71. package/dist/core/mcp-server-spec.js +1 -18
  72. package/dist/core/mcp.d.ts +6 -14
  73. package/dist/core/mcp.js +85 -65
  74. package/dist/core/memory-engine/consolidation-driver.js +4 -3
  75. package/dist/core/memory-engine/distiller.js +26 -17
  76. package/dist/core/memory-engine/layout.js +5 -2
  77. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  78. package/dist/core/memory-engine/scope-contract.js +80 -11
  79. package/dist/core/mode-policy.d.ts +8 -5
  80. package/dist/core/mode-policy.js +5 -4
  81. package/dist/core/mods/host.js +1 -1
  82. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  83. package/dist/core/mods/kernel/dispatch.js +10 -8
  84. package/dist/core/mods/kernel/events.d.ts +5 -1
  85. package/dist/core/mods/kernel/events.js +1 -1
  86. package/dist/core/mods/kernel/registration.d.ts +5 -1
  87. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  88. package/dist/core/mods/kernel/site-rules.js +10 -0
  89. package/dist/core/mods/package.d.ts +23 -0
  90. package/dist/core/mods/package.js +118 -0
  91. package/dist/core/mods/stations.d.ts +2 -2
  92. package/dist/core/mods/stations.js +1 -1
  93. package/dist/core/mods/tool-call.d.ts +5 -1
  94. package/dist/core/mods/tool-call.js +12 -3
  95. package/dist/core/park-selfcheck.js +2 -0
  96. package/dist/core/path-guard-rows.d.ts +20 -0
  97. package/dist/core/path-guard-rows.js +11 -0
  98. package/dist/core/peer-seat.d.ts +186 -0
  99. package/dist/core/peer-seat.js +307 -0
  100. package/dist/core/permission-rule-consent.d.ts +5 -3
  101. package/dist/core/permission-rule-consent.js +20 -15
  102. package/dist/core/permission-rule-model.d.ts +43 -2
  103. package/dist/core/permission-rule-model.js +52 -8
  104. package/dist/core/permission-rule-org.js +1 -1
  105. package/dist/core/present-plan-tool.d.ts +10 -1
  106. package/dist/core/present-plan-tool.js +46 -2
  107. package/dist/core/protocol-http-auth.d.ts +56 -31
  108. package/dist/core/protocol-http-auth.js +71 -42
  109. package/dist/core/protocol-naming.d.ts +20 -0
  110. package/dist/core/protocol-naming.js +20 -3
  111. package/dist/core/read-only-shell.d.ts +20 -5
  112. package/dist/core/read-only-shell.js +29 -14
  113. package/dist/core/redaction-marks.d.ts +16 -0
  114. package/dist/core/redaction-marks.js +16 -0
  115. package/dist/core/redaction-passes.js +8 -9
  116. package/dist/core/remote-env.d.ts +37 -1
  117. package/dist/core/remote-env.js +11 -0
  118. package/dist/core/resume-startup-cause.d.ts +24 -2
  119. package/dist/core/resume-startup-cause.js +20 -1
  120. package/dist/core/retention.d.ts +41 -15
  121. package/dist/core/retention.js +59 -12
  122. package/dist/core/rewrite-rejudge.d.ts +37 -0
  123. package/dist/core/rewrite-rejudge.js +40 -0
  124. package/dist/core/roles.js +50 -7
  125. package/dist/core/run-origin.d.ts +40 -0
  126. package/dist/core/run-origin.js +37 -0
  127. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  128. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  129. package/dist/core/runner/compact-session.d.ts +10 -0
  130. package/dist/core/runner/compact-session.js +202 -0
  131. package/dist/core/runner/compaction-call-options.d.ts +2 -2
  132. package/dist/core/runner/compaction-restate.d.ts +15 -6
  133. package/dist/core/runner/compaction-restate.js +28 -2
  134. package/dist/core/runner/compaction-seams.d.ts +21 -1
  135. package/dist/core/runner/compaction-seams.js +11 -8
  136. package/dist/core/runner/contracts.d.ts +36 -21
  137. package/dist/core/runner/derived-route-fallback.d.ts +13 -0
  138. package/dist/core/runner/derived-route-fallback.js +6 -0
  139. package/dist/core/runner/env-capability-census.d.ts +3 -2
  140. package/dist/core/runner/env-capability-census.js +9 -3
  141. package/dist/core/runner/gate-exit.d.ts +18 -4
  142. package/dist/core/runner/gate-exit.js +5 -1
  143. package/dist/core/runner/permission-rule-lanes.d.ts +7 -7
  144. package/dist/core/runner/permission-rule-lanes.js +17 -11
  145. package/dist/core/runner/prepare-acquire-reconcile.d.ts +3 -0
  146. package/dist/core/runner/prepare-acquire-reconcile.js +2 -1
  147. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  148. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  149. package/dist/core/runner/prepare-config-doors.d.ts +14 -5
  150. package/dist/core/runner/prepare-config-doors.js +16 -13
  151. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  152. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  153. package/dist/core/runner/prepare-gate-stations.js +1 -1
  154. package/dist/core/runner/prepare-hands-readface.d.ts +10 -4
  155. package/dist/core/runner/prepare-hands-readface.js +6 -1
  156. package/dist/core/runner/prepare-memory.d.ts +3 -0
  157. package/dist/core/runner/prepare-memory.js +19 -23
  158. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  159. package/dist/core/runner/prepare-park-ask.js +2 -2
  160. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  161. package/dist/core/runner/prepare-policy-chain.js +4 -6
  162. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  163. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  164. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  165. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  166. package/dist/core/runner/prepare-task.d.ts +4 -1
  167. package/dist/core/runner/prepare-task.js +46 -37
  168. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +13 -0
  169. package/dist/core/runner/prepare-tool-disclosure-mount.js +13 -7
  170. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  171. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  172. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  173. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  174. package/dist/core/runner/resume-admission.js +1 -1
  175. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  176. package/dist/core/runner/rewind-files.d.ts +2 -5
  177. package/dist/core/runner/rewind-files.js +9 -51
  178. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  179. package/dist/core/runner/run-harness-handlers.js +1 -8
  180. package/dist/core/runner/run-identity-wiring.js +1 -0
  181. package/dist/core/runner/run-leg.js +15 -22
  182. package/dist/core/runner/run-notification-lane.d.ts +2 -0
  183. package/dist/core/runner/run-notification-lane.js +5 -2
  184. package/dist/core/runner/run-recovery-lanes.js +3 -4
  185. package/dist/core/runner/run-settle-and-teardown.js +5 -11
  186. package/dist/core/runner/run-terminal-adoption.js +3 -4
  187. package/dist/core/runner/run-turn-boundary.js +3 -5
  188. package/dist/core/runner/runtask.d.ts +8 -1
  189. package/dist/core/runner/runtask.js +28 -34
  190. package/dist/core/runner/send-message-continuation.js +1 -1
  191. package/dist/core/runner/session-verb-doors.d.ts +28 -0
  192. package/dist/core/runner/session-verb-doors.js +48 -0
  193. package/dist/core/runner/session-write-ledger.d.ts +30 -0
  194. package/dist/core/runner/session-write-ledger.js +101 -0
  195. package/dist/core/runner/stream-settle-backstop.js +11 -14
  196. package/dist/core/runner/sub-agent-deny-lists.d.ts +25 -3
  197. package/dist/core/runner/sub-agent-deny-lists.js +21 -10
  198. package/dist/core/runner/teardown-bounded.d.ts +1 -0
  199. package/dist/core/runner/teardown-bounded.js +1 -0
  200. package/dist/core/runner/terminal-account.js +3 -3
  201. package/dist/core/runner/tool-end-body.js +1 -0
  202. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  203. package/dist/core/runner/tool-occurrence.js +2 -1
  204. package/dist/core/runner/write-protection-station.d.ts +8 -2
  205. package/dist/core/runner/write-protection-station.js +2 -0
  206. package/dist/core/runner-deps.d.ts +4 -4
  207. package/dist/core/secret-env.d.ts +4 -0
  208. package/dist/core/secret-env.js +3 -0
  209. package/dist/core/sensitive-path-policy.js +6 -7
  210. package/dist/core/session-log-transfer.d.ts +24 -0
  211. package/dist/core/session-log-transfer.js +166 -0
  212. package/dist/core/session-policy-store.d.ts +7 -2
  213. package/dist/core/session-policy-store.js +1 -1
  214. package/dist/core/session-store.d.ts +84 -19
  215. package/dist/core/session-store.js +162 -24
  216. package/dist/core/session.d.ts +92 -1
  217. package/dist/core/shell-read-silence.js +1 -0
  218. package/dist/core/shell-wrapper-projection.d.ts +1 -1
  219. package/dist/core/steer-replay.d.ts +4 -2
  220. package/dist/core/steer-replay.js +2 -1
  221. package/dist/core/store-contracts/background-agent-store-contract.js +1 -0
  222. package/dist/core/store-contracts/checkpoint-store-contract.js +19 -1
  223. package/dist/core/store-contracts/file-history-store-contract.js +9 -0
  224. package/dist/core/store-contracts/mailbox-store-contract.js +49 -1
  225. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  226. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  227. package/dist/core/store-contracts/session-store-contract.js +236 -2
  228. package/dist/core/task-event.d.ts +68 -8
  229. package/dist/core/task-registry-agent.d.ts +8 -4
  230. package/dist/core/task-registry-agent.js +14 -8
  231. package/dist/core/task-registry-shared.d.ts +36 -6
  232. package/dist/core/task-registry-shared.js +11 -0
  233. package/dist/core/task-registry.d.ts +1 -1
  234. package/dist/core/task-registry.js +1 -1
  235. package/dist/core/task-spec.d.ts +37 -0
  236. package/dist/core/task-stream.d.ts +2 -1
  237. package/dist/core/terminal-cause.d.ts +1 -1
  238. package/dist/core/tool-catalog-entries.d.ts +6 -0
  239. package/dist/core/tool-catalog-entries.js +2 -0
  240. package/dist/core/tool-name-aliases.d.ts +32 -2
  241. package/dist/core/tool-name-aliases.js +23 -0
  242. package/dist/core/tool-name-readings.d.ts +4 -0
  243. package/dist/core/tool-name-readings.js +1 -0
  244. package/dist/core/tool-policy.d.ts +10 -6
  245. package/dist/core/tool-policy.js +4 -7
  246. package/dist/core/tool-result-store.d.ts +17 -10
  247. package/dist/core/tool-result-store.js +3 -1
  248. package/dist/core/trace.d.ts +4 -1
  249. package/dist/core/trace.js +2 -1
  250. package/dist/core/types.d.ts +1 -1
  251. package/dist/core/untrusted-egress.d.ts +18 -0
  252. package/dist/core/untrusted-egress.js +82 -12
  253. package/dist/core/wiring-manifest.d.ts +12 -3
  254. package/dist/core/wiring-manifest.js +4 -3
  255. package/dist/core/workspace-snapshot.d.ts +44 -0
  256. package/dist/core/workspace-snapshot.js +34 -0
  257. package/dist/core/write-protect.d.ts +43 -3
  258. package/dist/core/write-protect.js +43 -16
  259. package/dist/engine/execution-env/node-execution-env.js +15 -11
  260. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  261. package/dist/engine/harness/agent-harness.d.ts +12 -5
  262. package/dist/engine/harness/agent-harness.js +13 -2
  263. package/dist/engine/harness/types.d.ts +48 -7
  264. package/dist/engine/harness/types.js +5 -1
  265. package/dist/engine/llm/types.d.ts +12 -3
  266. package/dist/engine/llm/types.js +1 -1
  267. package/dist/engine/loop/agent-loop.d.ts +1 -4
  268. package/dist/engine/loop/agent-loop.js +26 -4
  269. package/dist/engine/session/import-validate.js +3 -0
  270. package/dist/engine/session/memory-repo.d.ts +17 -9
  271. package/dist/engine/session/memory-repo.js +44 -34
  272. package/dist/engine/session/repo-utils.d.ts +22 -4
  273. package/dist/engine/session/repo-utils.js +49 -1
  274. package/dist/engine/session/storage-base.d.ts +10 -1
  275. package/dist/engine/session/storage-base.js +7 -1
  276. package/dist/index.d.ts +23 -11
  277. package/dist/index.js +15 -6
  278. package/dist/internal/harness-types.d.ts +1 -1
  279. package/dist/internal/harness.d.ts +4 -3
  280. package/dist/internal/harness.js +3 -2
  281. package/dist/stores/file/checkpoint-store.d.ts +0 -4
  282. package/dist/stores/file/checkpoint-store.js +0 -1
  283. package/dist/stores/file/file-history-store.js +12 -4
  284. package/dist/stores/file/index.d.ts +4 -1
  285. package/dist/stores/file/index.js +4 -1
  286. package/dist/stores/file/mailbox-store.d.ts +2 -1
  287. package/dist/stores/file/mailbox-store.js +26 -1
  288. package/dist/stores/file/session-store.d.ts +15 -8
  289. package/dist/stores/file/session-store.js +28 -13
  290. package/dist/tools/fs/bash-readonly-classifier.d.ts +15 -19
  291. package/dist/tools/fs/bash-readonly-classifier.js +5 -10
  292. package/dist/tools/fs/fs-bash.js +10 -3
  293. package/dist/tools/fs/fs-write.d.ts +6 -3
  294. package/dist/tools/fs/fs-write.js +8 -7
  295. package/dist/tools/fs/index.d.ts +3 -0
  296. package/dist/tools/fs/index.js +1 -1
  297. package/dist/tools/fs/pattern-kill-guard.d.ts +3 -2
  298. package/dist/tools/fs/pattern-kill-guard.js +68 -36
  299. package/dist/tools/fs/safety.js +40 -8
  300. package/dist/tools/fs/search.js +6 -24
  301. package/dist/tools/fs/shell-read-check.d.ts +18 -1
  302. package/dist/tools/fs/shell-read-check.js +66 -16
  303. package/dist/tools/fs/shell-read-establish.js +2 -1
  304. package/dist/tools/fs/shell-read-identity.d.ts +12 -9
  305. package/dist/tools/fs/shell-read-identity.js +10 -5
  306. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  307. package/dist/tools/web.js +9 -7
  308. package/dist/tools/worktree.d.ts +42 -15
  309. package/dist/tools/worktree.js +60 -32
  310. package/package.json +4 -2
  311. package/test/export-surface.snapshot.json +141 -3
  312. package/wire-changes/core-stores-sql@7.57.0.json +29 -0
  313. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  314. package/wire-changes/core@7.57.0.json +1487 -0
  315. package/wire-changes/core@7.58.0.json +2188 -0
  316. package/wire-changes/mods-kernel@7.57.0.json +29 -0
  317. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  318. package/wire-changes/primitives@7.57.0.json +245 -0
  319. package/wire-changes/primitives@7.58.0.json +29 -0
@@ -60,6 +60,24 @@ export declare function redactHostLeaks(s: string, report?: RedactionReport): Eg
60
60
  * - cycles and shared members stay shared on the snapshot.
61
61
  */
62
62
  export declare function egressValue<T extends EgressTier, V>(tier: T, value: V): V;
63
+ /**
64
+ * Tier `tier`'s pass over an engine ACCOUNT value — a notice's detail, a trace frame: data the engine shaped, carrying words that may have
65
+ * come from a host, a store or a remote. Returned as a new value, never the one handed in. The rules, one each:
66
+ * - a string, at any depth, goes through {@link egressText};
67
+ * - a member NAME of plain data is the engine's own closed word and is kept as written (a detail's `key` or `tokenCount` is not a
68
+ * credential name, and reading it as one would blank the engine's own facts);
69
+ * - plain data is an array or an object whose prototype is `Object.prototype` or `null`, and is not a proxy (whose traps answer what
70
+ * they choose, a fresh value at every read included); its own enumerable members are read once, a function member is code and is
71
+ * not carried;
72
+ * - any other object (an error, a class instance, a `Map`, a `Date`, a proxy) came from elsewhere and leaves as
73
+ * {@link egressValue} reads it — there, and only there, a credential-named member's string is the marker whole, and there, and
74
+ * only there, a member bound applies (one per such value);
75
+ * - no member bound applies to plain data: the account is the engine's own, and its size is the engine's to answer for;
76
+ * - one walk: an object reached twice — through the data and through a value from elsewhere included — is read once and answers one
77
+ * snapshot (cycles and shared members stay shared); past {@link VALUE_DEPTH_MAX} the marker stands in.
78
+ * Every pass it runs is a fixed point, so an account value minted twice reads the same.
79
+ */
80
+ export declare function egressAccount<T extends EgressTier, V>(tier: T, value: V): V;
63
81
  /** The `same-principal` tier's pass + size-bound (NO injection fence): workflow outputs/results/errors riding back to
64
82
  * the launching model/script, run rows behind scope-gated observe. Paths/URLs survive (the assertion pattern depends on
65
83
  * them); secrets never do. */
@@ -1,5 +1,7 @@
1
+ import { types } from "node:util";
1
2
  import { delimitUntrusted, inlineUntrusted, neutralizeForFence } from "./untrusted-text.js";
2
3
  import { egressPasses, runRedactionPasses } from "./redaction-passes.js";
4
+ import { REDACTION_MARK, REDACTION_MARKS, redactionMarkerSpans } from "./redaction-marks.js";
3
5
  import { CREDENTIAL_VOCABULARY, egressPassGroups, isSensitiveRecordKey, URI_SCHEME_SOURCE } from "./credential-vocabulary.js";
4
6
  import { isErrorLike, readMember, thrownText } from "./thrown-value.js";
5
7
  import { sliceHeadSafe } from "./surrogate-safe-slice.js";
@@ -9,20 +11,20 @@ const BARE_USERNAME_MAX_LEN = 20;
9
11
  function redactUserinfo(scheme, userinfoWithAt) {
10
12
  const userinfo = userinfoWithAt.slice(0, -1);
11
13
  if (CREDENTIAL_VOCABULARY.policy.urlUserinfo === "whole" || userinfo.includes("@"))
12
- return `${scheme}[redacted-credentials]@`;
14
+ return `${scheme}${REDACTION_MARKS.credentials}@`;
13
15
  const colonIdx = userinfo.indexOf(":");
14
16
  if (colonIdx === -1) {
15
- return userinfo.length >= BARE_USERNAME_MAX_LEN ? `${scheme}[redacted-credentials]@` : `${scheme}${userinfo}@`;
17
+ return userinfo.length >= BARE_USERNAME_MAX_LEN ? `${scheme}${REDACTION_MARKS.credentials}@` : `${scheme}${userinfo}@`;
16
18
  }
17
- return `${scheme}${userinfo.slice(0, colonIdx)}:[redacted-credentials]@`;
19
+ return `${scheme}${userinfo.slice(0, colonIdx)}:${REDACTION_MARKS.credentials}@`;
18
20
  }
19
21
  const SECRET_TIER_PASSES = egressPasses(egressPassGroups(CREDENTIAL_VOCABULARY), {
20
22
  "url-credentials": (_m, scheme, userinfo) => redactUserinfo(scheme, userinfo),
21
23
  });
22
24
  const HOST_LEAK_PASSES = [
23
25
  ...SECRET_TIER_PASSES,
24
- { kind: "url", confidence: "medium", marker: "[redacted-url]", source: "untrusted-egress", re: URL_OF_ANY_PROTOCOL, replace: "[redacted-url]" },
25
- { kind: "fs-path", confidence: "low", marker: "[redacted-path]", source: "untrusted-egress", re: /(?:\/[A-Za-z0-9_.-]+){2,}/g, replace: "[redacted-path]" },
26
+ { kind: "url", confidence: "medium", marker: REDACTION_MARKS.url, source: "untrusted-egress", re: URL_OF_ANY_PROTOCOL, replace: REDACTION_MARKS.url },
27
+ { kind: "fs-path", confidence: "low", marker: REDACTION_MARKS.path, source: "untrusted-egress", re: /(?:\/[A-Za-z0-9_.-]+){2,}/g, replace: REDACTION_MARKS.path },
26
28
  ];
27
29
  const TIER_PASSES = { "same-principal": SECRET_TIER_PASSES, human: HOST_LEAK_PASSES };
28
30
  export function egressText(tier, text, report) {
@@ -42,9 +44,10 @@ export function redactHostLeaks(s, report) {
42
44
  }
43
45
  const VALUE_DEPTH_MAX = 32;
44
46
  const VALUE_MEMBERS_MAX = 2_000;
45
- const WHOLE = "[redacted]";
46
47
  export function egressValue(tier, value) {
47
- const snapshots = new Map();
48
+ return foreignValue(tier, value, new Map());
49
+ }
50
+ function foreignValue(tier, value, snapshots) {
48
51
  let budget = VALUE_MEMBERS_MAX;
49
52
  const ownKeys = (o, all) => {
50
53
  try {
@@ -75,7 +78,7 @@ export function egressValue(tier, value) {
75
78
  };
76
79
  const member = (read, depth, name) => {
77
80
  const out = pass(read, depth + 1, name);
78
- return typeof out === "string" && isSensitiveRecordKey(name) ? WHOLE : out;
81
+ return typeof out === "string" && isSensitiveRecordKey(name) ? REDACTION_MARK : out;
79
82
  };
80
83
  const fill = (o, depth, keys, snapshot) => {
81
84
  snapshots.set(o, snapshot);
@@ -113,7 +116,7 @@ export function egressValue(tier, value) {
113
116
  if (known !== undefined)
114
117
  return known;
115
118
  if (depth >= VALUE_DEPTH_MAX)
116
- return WHOLE;
119
+ return REDACTION_MARK;
117
120
  if (isErrorLike(v))
118
121
  return errorSnapshot(v, depth);
119
122
  const toJSON = readMember(v, "toJSON");
@@ -123,7 +126,7 @@ export function egressValue(tier, value) {
123
126
  reading = toJSON.call(v, key);
124
127
  }
125
128
  catch {
126
- return WHOLE;
129
+ return REDACTION_MARK;
127
130
  }
128
131
  if (reading !== v) {
129
132
  const out = pass(reading, depth + 1, key);
@@ -143,9 +146,76 @@ export function egressValue(tier, value) {
143
146
  }
144
147
  return pass(value, 0, "");
145
148
  }
146
- const REDACTION_MARKER_RE = /\[redacted(?:-[a-z]+)?\]/g;
149
+ export function egressAccount(tier, value) {
150
+ const snapshots = new Map();
151
+ const plainShape = (o) => {
152
+ try {
153
+ if (types.isProxy(o))
154
+ return undefined;
155
+ if (Array.isArray(o))
156
+ return "array";
157
+ const proto = Object.getPrototypeOf(o);
158
+ return proto === Object.prototype || proto === null ? "record" : undefined;
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ };
164
+ function pass(v, depth) {
165
+ if (typeof v === "string")
166
+ return egressText(tier, v);
167
+ if (typeof v === "function")
168
+ return undefined;
169
+ if (typeof v !== "object" || v === null)
170
+ return v;
171
+ const known = snapshots.get(v);
172
+ if (known !== undefined)
173
+ return known;
174
+ if (depth >= VALUE_DEPTH_MAX)
175
+ return REDACTION_MARK;
176
+ const shape = plainShape(v);
177
+ if (shape === undefined)
178
+ return foreignValue(tier, v, snapshots);
179
+ let keys;
180
+ try {
181
+ keys = Object.keys(v);
182
+ }
183
+ catch {
184
+ return foreignValue(tier, v, snapshots);
185
+ }
186
+ const snapshot = shape === "array" ? [] : prototypeIsNull(v) ? Object.create(null) : {};
187
+ snapshots.set(v, snapshot);
188
+ for (const key of keys) {
189
+ let read;
190
+ let isData = false;
191
+ try {
192
+ const d = Reflect.getOwnPropertyDescriptor(v, key);
193
+ if (d === undefined)
194
+ continue;
195
+ isData = "value" in d;
196
+ read = isData ? pass(d.value, depth + 1) : foreignValue(tier, d.get?.call(v), snapshots);
197
+ if (read === undefined && !(isData && d.value === undefined))
198
+ continue;
199
+ }
200
+ catch {
201
+ continue;
202
+ }
203
+ Object.defineProperty(snapshot, key, { value: read, enumerable: true, writable: true, configurable: true });
204
+ }
205
+ return snapshot;
206
+ }
207
+ const prototypeIsNull = (o) => {
208
+ try {
209
+ return Object.getPrototypeOf(o) === null;
210
+ }
211
+ catch {
212
+ return false;
213
+ }
214
+ };
215
+ return pass(value, 0);
216
+ }
147
217
  function countRedactionMarkers(s) {
148
- return (s.match(REDACTION_MARKER_RE) ?? []).length;
218
+ return redactionMarkerSpans(s).length;
149
219
  }
150
220
  function safeEllipsisTruncate(s, max) {
151
221
  if (max < 1)
@@ -27,6 +27,7 @@ import type { ModAdmissionRecord } from "./mods/kernel/index.js";
27
27
  import type { McpDelivered, McpFailureKind, McpServerLiveness } from "./mcp-failure.js";
28
28
  import type { WriteProtectionTargetView } from "./write-protect.js";
29
29
  import type { OnAsk } from "./tool-policy.js";
30
+ import { type RunOrigin } from "./run-origin.js";
30
31
  export type { StoreDurability };
31
32
  /** The manifest-face projection of {@link StoreDurability}: `"declared_durable"` (the name says it —
32
33
  * a DECLARATION relayed, not a verification) vs `"process_local"` (declared so, or fail-closed
@@ -184,9 +185,13 @@ export declare function deriveLspSeam(mounted: boolean, diagnosticsLive: boolean
184
185
  */
185
186
  export interface WiringManifest {
186
187
  schemaVersion: 1;
187
- /** Present on EFFECTIVE (per-leg) manifests only; the static half has no leg. */
188
+ /** Present on EFFECTIVE (per-leg) manifests only; the static half has no leg. `runOrigin`: the word of the input that
189
+ * opened this leg, when its host said so (the objective's `TaskSpec.runOrigin`, or the newest input a wake hands over; read
190
+ * once at the config doors), and on a leg a decision resumed, the checkpoint row's — absent when the host said nothing, and
191
+ * on a delegated child (a child is its parent's model's work). */
188
192
  leg?: {
189
193
  kind: WiringLegKind;
194
+ runOrigin?: RunOrigin;
190
195
  };
191
196
  /** Effective half only — the leg's team role ({@link import("../agents/team-role.js").teamRoleOf}):
192
197
  * `lead` for a top-level leg, `teammate` for a named delegation, `none` for an unnamed one. Leg-local
@@ -358,9 +363,11 @@ export interface WiringManifest {
358
363
  tools?: import("./tool-roster.js").ToolRoster;
359
364
  /**
360
365
  * EFFECTIVE half only: the leg's mods admission — one record per registration of the two seats, in run order: a
361
- * mounted one with the patterns it actually hung (`events`), the ones it declared observe-only (`observe`) and the
366
+ * mounted one with the patterns it actually hung (`events`), the ones among them it only watches (`observe`: every
367
+ * handler it hung on the pattern is a watcher — a registration that only watches has `observe` equal to `events`) and the
362
368
  * judges skipped while it was judged (`skipped`), or a refused one with who refused it and why (`refusedBy`,
363
- * `reason`). PRESENT IFF the leg has a registration — a deployment that wires none reports nothing here and its
369
+ * `reason`); either carries the registration's `provenance` label as the host gave it (absent when none was given — no
370
+ * default is minted). PRESENT IFF the leg has a registration — a deployment that wires none reports nothing here and its
364
371
  * manifest (and {@link configFingerprint}) is byte-for-byte what it was. Absence reads as "this leg carries no
365
372
  * registration", NOT as "no extension judges this leg's calls": a delegated child can still be screened by an
366
373
  * ancestor's chain through the gate's constraint fold. EXCLUDED from {@link configFingerprint}: the task seat is a
@@ -526,6 +533,8 @@ export interface WiringFacts {
526
533
  half: "static" | "effective";
527
534
  /** Required on the effective half; must be absent on the static half. */
528
535
  leg?: WiringLegKind;
536
+ /** Effective half only, reported inside `leg` — see {@link WiringManifest.leg}. */
537
+ runOrigin?: RunOrigin;
529
538
  /** Effective half only — see {@link WiringManifest.teamRole}. */
530
539
  teamRole?: import("../agents/team-role.js").TeamRole;
531
540
  /** Effective half only — see {@link WiringManifest.peerPresence}; copied, never aliased. */
@@ -6,6 +6,7 @@ import { resolveCheckpointStore } from "./checkpoint-store.js";
6
6
  import { isLiveQuestionFace } from "./ask-question.js";
7
7
  import { AUTO_MODE_DENY_SOURCES, isAutoModeDenySource } from "./runtime-caps.js";
8
8
  import { describeRejectedValue } from "./tool-search-setting.js";
9
+ import { RUN_ORIGINS } from "./run-origin.js";
9
10
  export const APPROVAL_REACH = Object.freeze(["none"]);
10
11
  const APPROVAL_REACH_SET = new Set(APPROVAL_REACH);
11
12
  export function isApprovalReach(v) {
@@ -161,8 +162,8 @@ function readSessionRulesFact(fact) {
161
162
  return { childrenReadLive: fact };
162
163
  }
163
164
  export function deriveWiringManifest(facts) {
164
- if (facts.half === "static" && facts.leg !== undefined) {
165
- throw new Error("a static wiring manifest has no leg — leg identity is an effective-half fact");
165
+ if (facts.half === "static" && (facts.leg !== undefined || facts.runOrigin !== undefined)) {
166
+ throw new Error("a static wiring manifest has no leg — leg identity (its kind and its run origin) is an effective-half fact");
166
167
  }
167
168
  if (facts.half === "effective" && facts.leg === undefined) {
168
169
  throw new Error("an effective wiring manifest requires its leg kind");
@@ -179,7 +180,7 @@ export function deriveWiringManifest(facts) {
179
180
  : "absent";
180
181
  const manifest = {
181
182
  schemaVersion: 1,
182
- ...(facts.leg !== undefined ? { leg: { kind: facts.leg } } : {}),
183
+ ...(facts.leg !== undefined ? { leg: { kind: facts.leg, ...(facts.runOrigin !== undefined ? { runOrigin: readWordFact(facts.runOrigin, RUN_ORIGINS, "run origin") } : {}) } } : {}),
183
184
  ask: {
184
185
  form: facts.askForm,
185
186
  ...(facts.askProvenance !== undefined ? { provenance: facts.askProvenance } : {}),
@@ -0,0 +1,44 @@
1
+ /**
2
+ * WHERE A LEG STANDS, as one value: the ONE projection of it ({@link workspaceSnapshotOf}) and the ONE seat
3
+ * that announces it on the `workspace_changed` frame ({@link createWorkspaceFrameSeat}).
4
+ *
5
+ * The seat sends the leg-start snapshot when the leg binds its sink, and afterwards a frame only when the snapshot's digest
6
+ * differs from the last frame it sent — the digest is the snapshot's canonical JSON, so every member the projection carries
7
+ * takes part in the comparison with no second list to keep in step. The fixed members (root, project, remote) are leg
8
+ * facts handed in at prepare; the two live ones are read off the leg's own seats at each observation (the tracked cwd, the
9
+ * active EnterWorktree switch), never copied.
10
+ */
11
+ import type { ActiveWorktreeSession } from "../internal/harness-types.js";
12
+ import type { SessionProject } from "./memory-engine/scope-contract.js";
13
+ import type { TaskEvent, TaskEventIdentity } from "./task-event.js";
14
+ /** The frame's value — derived from the `workspace_changed` arm of the event union (one source; never a hand-copied shape). */
15
+ export type WorkspaceSnapshot = Omit<Extract<TaskEvent, {
16
+ type: "workspace_changed";
17
+ }>, "type" | keyof TaskEventIdentity>;
18
+ /** What a leg's snapshot is projected from. */
19
+ export interface WorkspaceFacts {
20
+ /** The leg's task root as its root receiving point settled it (`resolveTaskRootCanonical`). */
21
+ readonly root: string;
22
+ /** The leg's tracked logical cwd — present only where a real shell is mounted; absent ⇒ the cwd is `root`. */
23
+ readonly cwdRef?: {
24
+ readonly current: string;
25
+ };
26
+ /** The leg's EnterWorktree seat — present only where the worktree tools are mounted. */
27
+ readonly worktreeSessionRef?: {
28
+ readonly current?: ActiveWorktreeSession;
29
+ };
30
+ /** The leg's project verdict (`resolveSessionProject`); absent ⇒ the leg has no project identity. */
31
+ readonly project?: SessionProject;
32
+ /** The leg's one remoteness reading (the restore phase's, the same value `ResolvedWorkspace.remote` carries). */
33
+ readonly remote: boolean;
34
+ }
35
+ /** The ONE mint of the `workspace_changed` value. */
36
+ export declare function workspaceSnapshotOf(facts: WorkspaceFacts): WorkspaceSnapshot;
37
+ /** The leg's frame seat (held on `Prepared`): the run binds its sink once, and observes after every tool that may have moved the leg. */
38
+ export interface WorkspaceFrameSeat {
39
+ /** Bind this leg's frame sink and send the leg-start snapshot through it. The first binding wins; a later one is ignored. */
40
+ subscribe(push: (snapshot: WorkspaceSnapshot) => void): void;
41
+ /** Re-project, and send iff the snapshot differs from the last one sent. Nothing is sent before the sink is bound. */
42
+ observe(): void;
43
+ }
44
+ export declare function createWorkspaceFrameSeat(facts: WorkspaceFacts): WorkspaceFrameSeat;
@@ -0,0 +1,34 @@
1
+ import { canonicalJsonStringify } from "./canonical-json.js";
2
+ export function workspaceSnapshotOf(facts) {
3
+ const active = facts.worktreeSessionRef?.current;
4
+ return {
5
+ cwd: facts.cwdRef?.current ?? facts.root,
6
+ root: facts.root,
7
+ ...(active !== undefined ? { entered: { dir: active.worktreeDir, ...(active.entered === true ? { byPath: true } : {}) } } : {}),
8
+ ...(facts.project !== undefined ? { project: { id: facts.project.id, source: facts.project.source } } : {}),
9
+ remote: facts.remote,
10
+ };
11
+ }
12
+ export function createWorkspaceFrameSeat(facts) {
13
+ let push;
14
+ let lastSent;
15
+ const send = () => {
16
+ if (push === undefined)
17
+ return;
18
+ const snapshot = workspaceSnapshotOf(facts);
19
+ const digest = canonicalJsonStringify(snapshot);
20
+ if (digest === lastSent)
21
+ return;
22
+ lastSent = digest;
23
+ push(snapshot);
24
+ };
25
+ return {
26
+ subscribe(sink) {
27
+ if (push !== undefined)
28
+ return;
29
+ push = sink;
30
+ send();
31
+ },
32
+ observe: send,
33
+ };
34
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ExecutionEnv } from "../internal/harness-types.js";
2
2
  import type { ObservedFilesystem } from "../tools/fs/shell-read-environment.js";
3
3
  import type { PermissionResult } from "./tool-policy.js";
4
+ import { type GuardHitVia } from "./path-guard-rows.js";
4
5
  import { type ToolCallLike } from "./tool-registry.js";
5
6
  /**
6
7
  * How one table row matches the judged path:
@@ -106,7 +107,7 @@ export type WriteProtectionVerdict = {
106
107
  } | {
107
108
  readonly kind: "hit";
108
109
  readonly hit: WriteProtectedHit;
109
- readonly via: "spelling" | "chain" | "target";
110
+ readonly via: GuardHitVia;
110
111
  } | {
111
112
  readonly kind: "unresolvable";
112
113
  readonly cause: string;
@@ -206,6 +207,27 @@ export interface WriteProtectionCompileOptions {
206
207
  * cannot answer path questions), and its consumer announces once per leg rather than once per write.
207
208
  */
208
209
  readonly onViewAbsent?: (absence: WriteProtectionViewAbsence) => void;
210
+ /**
211
+ * The leg's CURRENT write location when it is a managed worktree — read once per judgment; `undefined` while the leg writes
212
+ * a directory that is not one. Each entry is one spelling of that tree: its `root` (`<base>/.sema/worktrees/<slug>`) and the
213
+ * `base` checkout it was minted under; `kind: "canonical"` is the tree's canonical identity, `kind: "spelled"` the spelling
214
+ * the leg's cwd and spellings carry it under (the task root as given, which may reach it through an alias).
215
+ *
216
+ * THE CURRENT-TREE READING (the reference implementation's `.claude/worktrees` exemption, narrowed to the one tree this leg
217
+ * writes): every view of a target that lies inside the tree is judged as the SAME relative path in `base` — only the managed
218
+ * prefix is removed, so the base checkout's own ancestry is judged as ever, a tree's own `.sema/settings.json` or `.git` is
219
+ * judged as the base checkout's, and an ordinary file of the tree meets no `.sema` row. A view outside the tree (a sibling
220
+ * tree, any other path) is judged as it stands. Narrow by construction, because this reading exempts: containment is
221
+ * byte-exact (no case fold), the canonical view is compared with the canonical identity alone, and a remainder that carries a
222
+ * `.` or `..` segment is judged as it stands (where it lands is not decided here).
223
+ */
224
+ readonly checkoutOf?: () => ReadonlyArray<ManagedCheckoutView> | undefined;
225
+ }
226
+ /** One spelling of the leg's current managed tree ({@link WriteProtectionCompileOptions.checkoutOf}). */
227
+ export interface ManagedCheckoutView {
228
+ readonly root: string;
229
+ readonly base: string;
230
+ readonly kind: "canonical" | "spelled";
209
231
  }
210
232
  /**
211
233
  * Compile the write-protection judge for a deployment configuration. Returns `undefined` when the
@@ -223,6 +245,12 @@ export declare function compileWriteProtection(entries?: readonly WriteProtected
223
245
  * ask carries that table's class) or a deployment's guarded write row (`ToolPolicy.writeGuardRows`: the target is not
224
246
  * placed). */
225
247
  export type WriteTargetCoverage = "protected" | "guarded";
248
+ /** One file of the engine's own the table does not demote: its declared spelling and the canonical key the run admitted it
249
+ * under (the session plan file, `TaskSpec.planFile`, as the advertised-writable seat holds it). ENGINE-INTERNAL. */
250
+ export interface ExemptFile {
251
+ readonly spelled: string;
252
+ readonly key: string;
253
+ }
226
254
  /** The leg's write judgment, compiled once ({@link compileLegWriteJudgment}). ENGINE-INTERNAL (not re-exported from
227
255
  * `src/index.ts`). */
228
256
  export interface LegWriteJudgment {
@@ -236,6 +264,7 @@ export interface LegWriteJudgment {
236
264
  readonly fs: ObservedFilesystem;
237
265
  readonly signal?: AbortSignal;
238
266
  readonly canonical?: true;
267
+ readonly spellingOnly?: true;
239
268
  }) => Promise<WriteTargetCoverage | undefined>) | undefined;
240
269
  }
241
270
  /**
@@ -246,6 +275,7 @@ export interface LegWriteJudgment {
246
275
  */
247
276
  export declare function compileLegWriteJudgment(entries: readonly WriteProtectedEntry[], opts: Omit<WriteProtectionCompileOptions, "dataRoot"> & {
248
277
  readonly exemptRoots: readonly string[];
278
+ readonly exemptFiles?: readonly ExemptFile[];
249
279
  readonly guardRows?: import("./tool-policy.js").ToolPolicy["writeGuardRows"];
250
280
  }): LegWriteJudgment;
251
281
  /**
@@ -254,8 +284,11 @@ export declare function compileLegWriteJudgment(entries: readonly WriteProtected
254
284
  * · `hit` ⇒ `ask` (`safety`; no `requiresRealApproval` — one explicit look, clearable by an approver, a
255
285
  * blanket `onAsk:"allow"`, the classifier or a matching persisted rule). The matched row NAME goes on the
256
286
  * message (table names are deployment-validated vocabulary); the model-authored target path deliberately
257
- * does not — `message` is the classifier's `askMessage`, and the approval card already shows the args. The
258
- * spelling form's sentence is the historical one byte for byte; the target form says the target RESOLVED.
287
+ * does not — `message` is the classifier's `askMessage`, and the approval card already shows the args. ONE
288
+ * sentence for every view: the row first, then — when the reading that met it is not the spelling — the one reach
289
+ * clause every guard's sentence uses ({@link guardHitReachClause}); a hit through the real target and a hit through a
290
+ * hop of the link chain are one fact to the classifier and the approver, so they read one sentence. The spelling
291
+ * view's sentence is the historical one byte for byte.
259
292
  * · `unresolvable` ⇒ `deny` (`safety`; reason word `target_unresolved` on the sentence): where the write lands could not be
260
293
  * determined, so this table cannot say it is not a protected path — refused in every permission mode (a refusal, not a
261
294
  * question a mode releases), the reference's write check form ("where it leads on disk could not be determined").
@@ -270,6 +303,13 @@ export declare function writeProtectionTightenDecision(toolName: string, verdict
270
303
  * it took no part.
271
304
  */
272
305
  export declare function writeProtectionMandated(verdict: WriteProtectionVerdict): boolean;
306
+ /**
307
+ * WHICH of the two table classes a verdict's hit is — the one reading of `via` as the class fact, beside the mandate predicate:
308
+ * `spelling` ⇒ the path as written names the row (`write_protection`); `target` / `chain` ⇒ the row is met only where the path
309
+ * resolves on disk (`write_protection_on_disk`) — the judge reads the spelling first and answers there on a hit, so a resolved
310
+ * reading is the answer only for a spelling that names no row. `undefined` for a verdict that is not a hit.
311
+ */
312
+ export declare function writeProtectionReachOf(verdict: WriteProtectionVerdict): "spelling" | "on_disk" | undefined;
273
313
  /**
274
314
  * The ENGINE-FILLED gate input (`ToolGateInput.writeProtectionCheck`). Returns `null` SYNCHRONOUSLY when the
275
315
  * call is not this layer's business — not a covered write, or no resolvable target string — and otherwise
@@ -1,5 +1,5 @@
1
- import { anchorSpelling, canonicalizeTarget, isAbsoluteForFamily, isWinFormPath, writeTargetPath, isUncPath, pathFamilyOf } from "../tools/fs/safety.js";
2
- import { judgePathRows } from "./path-guard-rows.js";
1
+ import { anchorSpelling, canonicalizeTarget, isAbsoluteForFamily, isWinFormPath, normalizeAbsPathLexically, writeTargetPath, isUncPath, pathFamilyOf } from "../tools/fs/safety.js";
2
+ import { checkoutReadingOf, guardHitReachClause, guardHitVia, judgePathRows } from "./path-guard-rows.js";
3
3
  import { protectivePathTargetOf } from "./tool-registry.js";
4
4
  import { pathTargetBaseOf } from "./effective-path-target.js";
5
5
  import { canonicalDataRootKeys, dataRootSpellings, relativeUnderRoot } from "./sensitive-path-policy.js";
@@ -207,6 +207,22 @@ export function spelledExemptionOf(dataRootPaths) {
207
207
  return (spelling) => relativeUnderDataRoot(spelling, roots);
208
208
  }
209
209
  export const WRITE_PROTECTION_TARGET_VIEWS = Object.freeze(["spelling-only", "target"]);
210
+ function judgedInCheckout(path, checkout, kind) {
211
+ const reading = checkoutReadingOf(kind);
212
+ for (const c of checkout ?? []) {
213
+ if (reading === "canonical-only" && c.kind !== "canonical")
214
+ continue;
215
+ const rel = relativeUnderRoot(path, c.root);
216
+ if (rel === null)
217
+ continue;
218
+ if (rel.split("/").some((s) => s === "." || s === ".."))
219
+ return path;
220
+ if (rel === "")
221
+ return c.base;
222
+ return c.base.endsWith("/") ? `${c.base}${rel}` : `${c.base}/${rel}`;
223
+ }
224
+ return path;
225
+ }
210
226
  export function compileWriteProtection(entries, opts) {
211
227
  const rows = resolveWriteProtectedTable(entries);
212
228
  if (rows.length === 0)
@@ -223,6 +239,10 @@ export function compileLegWriteJudgment(entries, opts) {
223
239
  judgeWriteTarget: rows.length === 0 && guardRows === undefined
224
240
  ? undefined
225
241
  : async (target, judgeOpts) => {
242
+ if (judgeOpts.spellingOnly === true) {
243
+ const spelled = await compiled.judgment(target, {}, undefined);
244
+ return spelled !== undefined && spelled.unreadable === undefined && TABLE_ROWS.has(spelled.row) ? "protected" : undefined;
245
+ }
226
246
  const hit = await compiled.judgment(target, { ...(judgeOpts.signal !== undefined ? { signal: judgeOpts.signal } : {}), ...(judgeOpts.canonical === true ? { canonical: true } : {}) }, judgeOpts.fs, guardRows);
227
247
  return hit === undefined ? undefined : hit.unreadable === undefined && TABLE_ROWS.has(hit.row) ? "protected" : "guarded";
228
248
  },
@@ -234,6 +254,8 @@ function heldRows(cause) {
234
254
  }
235
255
  function compileWriteJudgment(rows, origin, opts) {
236
256
  const dataRootPaths = opts.exemptRoots;
257
+ const exemptFileKeys = (opts.exemptFiles ?? []).map((f) => f.key);
258
+ const exemptFileSpellings = new Set((opts.exemptFiles ?? []).flatMap((f) => [normalizeAbsPathLexically(f.spelled), normalizeAbsPathLexically(f.key)]));
237
259
  const spelledRemainder = spelledExemptionOf(dataRootPaths);
238
260
  const readingMemo = new Map();
239
261
  const readingsOf = (spelling) => {
@@ -275,9 +297,10 @@ function compileWriteJudgment(rows, origin, opts) {
275
297
  return readingsOf(view.path).some((segs) => roots.some((root) => atConfigRoot(segs, root.map(foldWriteProtectSegment), tail))) ? REACHED : NOT_REACHED;
276
298
  }, { below: opts?.agentConfigDir ?? "" }));
277
299
  const tableAt = (canonicalRoots) => (configTails.length === 0 ? tableRows : [...tableRows, ...configRowsAt(canonicalRoots)]);
278
- const spelledView = (spelled, kind) => {
279
- const remainder = spelledRemainder(spelled);
280
- return { path: spelled, kind, ...(remainder !== null ? { exemptRemainder: remainder } : {}) };
300
+ const spelledView = (spelled, kind, checkout) => {
301
+ const judgedPath = judgedInCheckout(spelled, checkout, kind);
302
+ const remainder = spelledRemainder(judgedPath);
303
+ return { path: judgedPath, kind, ...(remainder !== null ? { exemptRemainder: remainder } : {}) };
281
304
  };
282
305
  const anchoredSpelling = (path, cwd) => {
283
306
  const base = typeof cwd === "string" && cwd.length > 0 ? cwd : undefined;
@@ -307,9 +330,11 @@ function compileWriteJudgment(rows, origin, opts) {
307
330
  })();
308
331
  const givenKey = ctx.canonical === true && env !== undefined;
309
332
  const base = ctx.base ?? ctx.cwd ?? rootPath;
310
- const lexical = givenKey ? undefined : spelledView(anchoredSpelling(path, ctx.base ?? ctx.cwd), "lexical");
333
+ const checkout = opts.checkoutOf?.();
334
+ const lexical = givenKey ? undefined : spelledView(anchoredSpelling(path, ctx.base ?? ctx.cwd), "lexical", checkout);
311
335
  const bySpelling = lexical === undefined ? undefined : judgePathRows([...tableAt([]), ...extra], { views: [lexical] }, "tighten");
312
- if (bySpelling !== undefined && bySpelling.unreadable === undefined && TABLE_ROWS.has(bySpelling.row))
336
+ const namesExemptFile = lexical !== undefined && env !== undefined && exemptFileSpellings.has(normalizeAbsPathLexically(lexical.path));
337
+ if (bySpelling !== undefined && bySpelling.unreadable === undefined && TABLE_ROWS.has(bySpelling.row) && !namesExemptFile)
313
338
  return bySpelling;
314
339
  if (env === undefined)
315
340
  return bySpelling;
@@ -338,11 +363,13 @@ function compileWriteJudgment(rows, origin, opts) {
338
363
  const canonicalRoots = canonKey === undefined || configTails.length === 0 || opts?.agentConfigDir === undefined ? [] : (await canonicalDataRootKeys(env, [opts.agentConfigDir], ctx.signal, rootLookupFailed)).map(agentConfigDirSegments);
339
364
  const table = [...tableAt(canonicalRoots), ...extra];
340
365
  const aliased = canonAliased ? { aliasResolved: true } : {};
341
- const views = [...(lexical !== undefined ? [{ ...lexical, ...aliased }] : []), ...(canonKey !== undefined ? [{ path: canonKey, kind: "canonical", ...aliased }] : [])];
366
+ const views = [...(lexical !== undefined ? [{ ...lexical, ...aliased }] : []), ...(canonKey !== undefined ? [{ path: judgedInCheckout(canonKey, checkout, "canonical"), kind: "canonical", ...aliased }] : [])];
342
367
  const identity = {};
343
368
  const identityRemainder = () => (identity.asked ??= (async () => {
344
369
  if (canonKey === undefined)
345
370
  return undefined;
371
+ if (exemptFileKeys.includes(canonKey))
372
+ return "";
346
373
  for (const rootKey of await canonicalDataRootKeys(env, dataRootPaths, ctx.signal, rootLookupFailed)) {
347
374
  const relative = relativeUnderRoot(canonKey, rootKey);
348
375
  if (relative !== null)
@@ -377,7 +404,7 @@ function compileWriteJudgment(rows, origin, opts) {
377
404
  targetUnread ??= chain.value.cause;
378
405
  }
379
406
  for (const hop of chainHopsOrNone(chain.value))
380
- views.push(spelledView(hop, "hop"));
407
+ views.push(spelledView(hop, "hop", checkout));
381
408
  }
382
409
  return judged();
383
410
  };
@@ -385,7 +412,7 @@ function compileWriteJudgment(rows, origin, opts) {
385
412
  rows,
386
413
  targetView: opts?.env === undefined ? "spelling-only" : "target",
387
414
  matchPath(path, cwd) {
388
- const hit = judgePathRows(tableAt([]), { views: [spelledView(anchoredSpelling(path, cwd), "lexical")] }, "tighten");
415
+ const hit = judgePathRows(tableAt([]), { views: [spelledView(anchoredSpelling(path, cwd), "lexical", opts.checkoutOf?.())] }, "tighten");
389
416
  return hit === undefined ? null : { name: hit.row.name, kind: hit.row.kind };
390
417
  },
391
418
  async judge(path, ctx = {}) {
@@ -417,7 +444,7 @@ function atConfigRoot(segs, root, tail) {
417
444
  return segs.length >= root.length + tail.length && root.every((a, i) => segs[i] === a) && tail.every((t, i) => segs[root.length + i] === t);
418
445
  }
419
446
  function verdictOf(hit) {
420
- return { kind: "hit", hit: { name: hit.row.name, kind: hit.row.kind }, via: hit.viewKind === "canonical" ? "target" : hit.viewKind === "hop" ? "chain" : "spelling" };
447
+ return { kind: "hit", hit: { name: hit.row.name, kind: hit.row.kind }, via: guardHitVia(hit.viewKind) };
421
448
  }
422
449
  export function writeProtectionTightenDecision(toolName, verdict) {
423
450
  if (verdict.kind === "clear")
@@ -429,19 +456,19 @@ export function writeProtectionTightenDecision(toolName, verdict) {
429
456
  decisionReason: "safety",
430
457
  };
431
458
  }
459
+ const reach = guardHitReachClause(verdict.via);
432
460
  return {
433
461
  action: "ask",
434
- message: verdict.via === "target"
435
- ? `tool "${toolName}" writes to a write-protected path — its real target resolves onto table entry "${verdict.hit.name}" — explicit approval required`
436
- : verdict.via === "chain"
437
- ? `tool "${toolName}" writes to a write-protected path — its symlink chain passes through table entry "${verdict.hit.name}" — explicit approval required`
438
- : `tool "${toolName}" writes to a write-protected path (table entry "${verdict.hit.name}") — explicit approval required`,
462
+ message: `tool "${toolName}" writes to a write-protected path (table entry "${verdict.hit.name}")${reach !== undefined ? ` — ${reach}` : ""} — explicit approval required`,
439
463
  decisionReason: "safety",
440
464
  };
441
465
  }
442
466
  export function writeProtectionMandated(verdict) {
443
467
  return verdict.kind === "hit";
444
468
  }
469
+ export function writeProtectionReachOf(verdict) {
470
+ return verdict.kind !== "hit" ? undefined : verdict.via === "spelling" ? "spelling" : "on_disk";
471
+ }
445
472
  export function createWriteProtectionCheck(entries, opts) {
446
473
  const matcher = compileWriteProtection(entries, opts);
447
474
  return matcher === undefined ? undefined : writeProtectionMountOver(matcher, opts?.rootPath);