@stigmer/runner 3.15.3-dev.20260914121148 → 3.16.0

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