@adhdev/daemon-core 0.9.82-rc.4 → 0.9.82-rc.400

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 (418) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +11 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +67 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +123 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +7 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +15 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +60 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +2 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +116 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +267 -2
  56. package/dist/commands/upgrade-helper.d.ts +41 -1
  57. package/dist/config/chat-history.d.ts +9 -0
  58. package/dist/config/config.d.ts +5 -0
  59. package/dist/config/mesh-config.d.ts +77 -1
  60. package/dist/config/mesh-json-config.d.ts +299 -0
  61. package/dist/daemon/dev-server.d.ts +0 -2
  62. package/dist/detection/ide-detector.d.ts +13 -0
  63. package/dist/detection/win32-ide-version.d.ts +37 -0
  64. package/dist/git/change-impact-config.d.ts +159 -0
  65. package/dist/git/git-commands.d.ts +12 -1
  66. package/dist/git/git-diff.d.ts +6 -0
  67. package/dist/git/git-executor.d.ts +11 -0
  68. package/dist/git/git-status.d.ts +28 -0
  69. package/dist/git/git-types.d.ts +5 -43
  70. package/dist/git/git-worktree.d.ts +22 -0
  71. package/dist/git/index.d.ts +2 -0
  72. package/dist/index.d.ts +57 -13
  73. package/dist/index.js +48373 -18578
  74. package/dist/index.js.map +1 -1
  75. package/dist/index.mjs +47576 -17923
  76. package/dist/index.mjs.map +1 -1
  77. package/dist/installer.d.ts +1 -4
  78. package/dist/ipc/local-ipc-server.d.ts +91 -0
  79. package/dist/launch.d.ts +1 -1
  80. package/dist/logging/async-batch-writer.d.ts +10 -0
  81. package/dist/logging/log-redactor.d.ts +24 -0
  82. package/dist/logging/log-tail-reader.d.ts +81 -0
  83. package/dist/logging/logger.d.ts +1 -1
  84. package/dist/mesh/contracts.d.ts +164 -0
  85. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  86. package/dist/mesh/coordinator-registry.d.ts +59 -0
  87. package/dist/mesh/mesh-active-work.d.ts +174 -0
  88. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  89. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  90. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  91. package/dist/mesh/mesh-event-forwarding.d.ts +19 -0
  92. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  93. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  94. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  95. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  96. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  97. package/dist/mesh/mesh-events.d.ts +6 -37
  98. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  99. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  100. package/dist/mesh/mesh-init.d.ts +86 -0
  101. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  102. package/dist/mesh/mesh-ledger.d.ts +77 -1
  103. package/dist/mesh/mesh-missions.d.ts +164 -0
  104. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  105. package/dist/mesh/mesh-queue-assignment.d.ts +95 -0
  106. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  107. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  108. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  109. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  110. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  111. package/dist/mesh/mesh-routing.d.ts +70 -0
  112. package/dist/mesh/mesh-runtime-store.d.ts +447 -0
  113. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  114. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  115. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  116. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  117. package/dist/mesh/mesh-work-queue.d.ts +250 -6
  118. package/dist/mesh/preview-freshness.d.ts +18 -0
  119. package/dist/mesh/refine-config.d.ts +216 -0
  120. package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
  121. package/dist/providers/acp-provider-instance.d.ts +5 -0
  122. package/dist/providers/approval-utils.d.ts +20 -0
  123. package/dist/providers/chat-message-normalization.d.ts +13 -0
  124. package/dist/providers/cli-provider-instance.d.ts +157 -3
  125. package/dist/providers/contracts.d.ts +139 -6
  126. package/dist/providers/external-sources.d.ts +71 -0
  127. package/dist/providers/manual-attendance.d.ts +63 -0
  128. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  129. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  130. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  131. package/dist/providers/native-history/constants.d.ts +12 -0
  132. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  133. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  134. package/dist/providers/native-history/index.d.ts +13 -0
  135. package/dist/providers/provider-instance-manager.d.ts +14 -0
  136. package/dist/providers/provider-instance.d.ts +23 -1
  137. package/dist/providers/provider-loader.d.ts +26 -4
  138. package/dist/providers/provider-trust.d.ts +31 -0
  139. package/dist/providers/read-chat-contract.d.ts +29 -0
  140. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  141. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  142. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  143. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  144. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  145. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  146. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  147. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  148. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  149. package/dist/providers/sdk/v1/index.d.ts +30 -0
  150. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  151. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  152. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  153. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  154. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  155. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  156. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  157. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  158. package/dist/providers/spec/adapter.d.ts +91 -0
  159. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  160. package/dist/providers/spec/evaluator.d.ts +45 -0
  161. package/dist/providers/spec/fsm-driver.d.ts +407 -0
  162. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  163. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  164. package/dist/providers/spec/fsm-types.d.ts +174 -0
  165. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  166. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  167. package/dist/providers/spec/route.d.ts +4 -0
  168. package/dist/providers/spec/types.d.ts +222 -0
  169. package/dist/providers/status-monitor.d.ts +7 -7
  170. package/dist/providers/transcript-v2.d.ts +176 -0
  171. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  172. package/dist/providers/working-dir.d.ts +17 -0
  173. package/dist/repo-mesh-types.d.ts +536 -1
  174. package/dist/runtime-defaults.d.ts +2 -0
  175. package/dist/sessions/registry.d.ts +6 -0
  176. package/dist/shared-types-extra.d.ts +2 -4
  177. package/dist/shared-types.d.ts +59 -2
  178. package/dist/status/normalize.d.ts +1 -1
  179. package/dist/status/normalize.js +1 -0
  180. package/dist/status/normalize.js.map +1 -1
  181. package/dist/status/normalize.mjs +1 -0
  182. package/dist/status/normalize.mjs.map +1 -1
  183. package/dist/status/reporter.d.ts +2 -0
  184. package/dist/status/snapshot.d.ts +26 -0
  185. package/dist/system/hash.d.ts +8 -0
  186. package/dist/system/load-better-sqlite3.d.ts +21 -0
  187. package/dist/types.d.ts +5 -0
  188. package/package.json +7 -3
  189. package/src/agent-stream/poller.ts +2 -3
  190. package/src/agent-stream/provider-adapter.ts +1 -1
  191. package/src/boot/daemon-lifecycle.ts +66 -12
  192. package/src/boot/process-hardening.ts +89 -0
  193. package/src/build-info.ts +73 -0
  194. package/src/chat/source-machine.ts +534 -0
  195. package/src/chat/source-resolver.ts +0 -0
  196. package/src/chat/subscription-updates.ts +20 -1
  197. package/src/cli-adapter-types.d.ts +1 -0
  198. package/src/cli-adapter-types.ts +68 -2
  199. package/src/cli-adapters/cli-script-runner.ts +421 -0
  200. package/src/cli-adapters/cli-state-engine.ts +1221 -0
  201. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  202. package/src/cli-adapters/provider-cli-adapter.ts +888 -1144
  203. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  204. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  205. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  206. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  207. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  208. package/src/cli-adapters/pty-transport.ts +2 -1
  209. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  210. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  211. package/src/cli-adapters/resolve-executable.ts +90 -0
  212. package/src/cli-adapters/session-host-transport.ts +2 -1
  213. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  214. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  215. package/src/cli-adapters/terminal-screen.ts +16 -81
  216. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  217. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  218. package/src/commands/chat-commands-read.ts +2327 -0
  219. package/src/commands/chat-commands-scope.ts +54 -0
  220. package/src/commands/chat-commands-shared.ts +114 -0
  221. package/src/commands/chat-commands-write.ts +880 -0
  222. package/src/commands/chat-commands.ts +19 -1841
  223. package/src/commands/cli-manager.ts +513 -26
  224. package/src/commands/handler.ts +841 -2
  225. package/src/commands/high-family/index.ts +28 -0
  226. package/src/commands/high-family/mesh-coordinator-launch.ts +673 -0
  227. package/src/commands/high-family/mesh-events.ts +80 -0
  228. package/src/commands/high-family/mesh-status.ts +678 -0
  229. package/src/commands/high-family/types.ts +76 -0
  230. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  231. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  232. package/src/commands/low-family/diagnostics.ts +57 -0
  233. package/src/commands/low-family/index.ts +37 -0
  234. package/src/commands/low-family/mesh-ledger.ts +62 -0
  235. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  236. package/src/commands/low-family/notification.ts +116 -0
  237. package/src/commands/low-family/refine-config.ts +106 -0
  238. package/src/commands/low-family/session-host.ts +274 -0
  239. package/src/commands/low-family/spec-providerdev.ts +217 -0
  240. package/src/commands/low-family/status-meta.ts +112 -0
  241. package/src/commands/low-family/types.ts +39 -0
  242. package/src/commands/med-family/cli-agent.ts +238 -0
  243. package/src/commands/med-family/fast-forward.ts +230 -0
  244. package/src/commands/med-family/ide.ts +163 -0
  245. package/src/commands/med-family/index.ts +37 -0
  246. package/src/commands/med-family/mesh-crud.ts +865 -0
  247. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  248. package/src/commands/med-family/mesh-queue.ts +131 -0
  249. package/src/commands/med-family/mesh-restart.ts +92 -0
  250. package/src/commands/med-family/types.ts +120 -0
  251. package/src/commands/mesh-coordinator.ts +334 -124
  252. package/src/commands/router.ts +2636 -2310
  253. package/src/commands/stream-commands.ts +8 -0
  254. package/src/commands/upgrade-helper.ts +310 -45
  255. package/src/config/chat-history.ts +483 -24
  256. package/src/config/config.ts +12 -0
  257. package/src/config/mesh-config.ts +353 -22
  258. package/src/config/mesh-json-config.ts +617 -0
  259. package/src/config/recent-activity.ts +8 -2
  260. package/src/daemon/dev-auto-implement.ts +3 -2
  261. package/src/daemon/dev-cli-debug.ts +10 -1
  262. package/src/daemon/dev-server.ts +0 -541
  263. package/src/detection/cli-detector.ts +28 -9
  264. package/src/detection/ide-detector.ts +55 -16
  265. package/src/detection/win32-ide-version.ts +106 -0
  266. package/src/git/change-impact-config.ts +354 -0
  267. package/src/git/git-commands.ts +56 -15
  268. package/src/git/git-diff.ts +81 -11
  269. package/src/git/git-executor.ts +12 -0
  270. package/src/git/git-status.ts +670 -48
  271. package/src/git/git-summary.ts +3 -0
  272. package/src/git/git-types.ts +17 -54
  273. package/src/git/git-worktree.ts +76 -1
  274. package/src/git/index.ts +16 -0
  275. package/src/index.ts +179 -12
  276. package/src/installer.d.ts +1 -1
  277. package/src/installer.ts +8 -6
  278. package/src/ipc/local-ipc-server.ts +278 -0
  279. package/src/launch.d.ts +1 -1
  280. package/src/launch.ts +37 -28
  281. package/src/logging/async-batch-writer.ts +55 -0
  282. package/src/logging/command-log.ts +7 -5
  283. package/src/logging/log-redactor.ts +100 -0
  284. package/src/logging/log-tail-reader.ts +341 -0
  285. package/src/logging/logger.ts +14 -7
  286. package/src/mesh/contracts.ts +338 -0
  287. package/src/mesh/coordinator-prompt.ts +381 -33
  288. package/src/mesh/coordinator-registry.ts +121 -0
  289. package/src/mesh/mesh-active-work.ts +645 -0
  290. package/src/mesh/mesh-coordinator-config.ts +97 -0
  291. package/src/mesh/mesh-delivery-policy.ts +315 -0
  292. package/src/mesh/mesh-event-classify.ts +51 -0
  293. package/src/mesh/mesh-event-forwarding.ts +1762 -0
  294. package/src/mesh/mesh-event-trace.ts +67 -0
  295. package/src/mesh/mesh-events-coordinator.ts +31 -0
  296. package/src/mesh/mesh-events-pending.ts +590 -0
  297. package/src/mesh/mesh-events-stale.ts +389 -0
  298. package/src/mesh/mesh-events-utils.ts +443 -0
  299. package/src/mesh/mesh-events.ts +32 -897
  300. package/src/mesh/mesh-fast-forward.ts +839 -0
  301. package/src/mesh/mesh-host-ownership.ts +73 -0
  302. package/src/mesh/mesh-init.ts +260 -0
  303. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  304. package/src/mesh/mesh-ledger.ts +596 -102
  305. package/src/mesh/mesh-missions.ts +322 -0
  306. package/src/mesh/mesh-node-identity.ts +1887 -0
  307. package/src/mesh/mesh-queue-assignment.ts +1726 -0
  308. package/src/mesh/mesh-reconcile-loop.ts +1550 -0
  309. package/src/mesh/mesh-refine-batch.ts +205 -0
  310. package/src/mesh/mesh-refine-gates.ts +1660 -0
  311. package/src/mesh/mesh-refine-status.ts +231 -0
  312. package/src/mesh/mesh-review-inbox.ts +307 -0
  313. package/src/mesh/mesh-routing.ts +291 -0
  314. package/src/mesh/mesh-runtime-store.ts +1817 -0
  315. package/src/mesh/mesh-scheduling-runtime.ts +201 -0
  316. package/src/mesh/mesh-task-stats.ts +161 -0
  317. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  318. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  319. package/src/mesh/mesh-work-queue.ts +1178 -162
  320. package/src/mesh/preview-freshness.ts +118 -0
  321. package/src/mesh/refine-config.ts +423 -0
  322. package/src/mesh/worktree-bootstrap-config.ts +369 -0
  323. package/src/providers/acp-provider-instance.ts +43 -10
  324. package/src/providers/approval-utils.d.ts +5 -0
  325. package/src/providers/approval-utils.ts +57 -5
  326. package/src/providers/chat-message-normalization.ts +48 -6
  327. package/src/providers/cli-provider-instance.ts +1580 -103
  328. package/src/providers/contracts.d.ts +55 -0
  329. package/src/providers/contracts.ts +150 -6
  330. package/src/providers/extension-provider-instance.ts +12 -7
  331. package/src/providers/external-sources.ts +218 -0
  332. package/src/providers/ide-provider-instance.ts +35 -12
  333. package/src/providers/manual-attendance.ts +85 -0
  334. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  335. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  336. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  337. package/src/providers/native-history/constants.ts +19 -0
  338. package/src/providers/native-history/dispatcher.ts +339 -0
  339. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  340. package/src/providers/native-history/index.ts +30 -0
  341. package/src/providers/provider-instance-manager.ts +30 -0
  342. package/src/providers/provider-instance.ts +19 -1
  343. package/src/providers/provider-loader.ts +668 -50
  344. package/src/providers/provider-schema.ts +87 -14
  345. package/src/providers/provider-trust.ts +114 -0
  346. package/src/providers/read-chat-contract.ts +76 -16
  347. package/src/providers/sdk/README.md +49 -0
  348. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  349. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  350. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  351. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  352. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  353. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  354. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  355. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  356. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  357. package/src/providers/sdk/v1/index.ts +152 -0
  358. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  359. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  360. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  361. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  362. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  363. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  364. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  365. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  366. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  367. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  368. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  369. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  370. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  375. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  376. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  377. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  378. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  379. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  380. package/src/providers/sdk/v1/validators/index.ts +19 -0
  381. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  382. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  383. package/src/providers/spec/adapter.ts +235 -0
  384. package/src/providers/spec/cli-adapter.ts +1056 -0
  385. package/src/providers/spec/evaluator.ts +407 -0
  386. package/src/providers/spec/fsm-driver.ts +1304 -0
  387. package/src/providers/spec/fsm-evaluator.ts +272 -0
  388. package/src/providers/spec/fsm-loader.ts +120 -0
  389. package/src/providers/spec/fsm-types.ts +273 -0
  390. package/src/providers/spec/native-history-executor.ts +1128 -0
  391. package/src/providers/spec/pre-launch-trust.ts +104 -0
  392. package/src/providers/spec/route.ts +51 -0
  393. package/src/providers/spec/types.ts +262 -0
  394. package/src/providers/status-monitor.d.ts +7 -7
  395. package/src/providers/status-monitor.ts +37 -22
  396. package/src/providers/transcript-v2.ts +567 -0
  397. package/src/providers/types/interactive-prompt.ts +536 -0
  398. package/src/providers/version-archive.ts +64 -24
  399. package/src/providers/working-dir.ts +23 -0
  400. package/src/repo-mesh-types.ts +755 -2
  401. package/src/runtime-defaults.ts +39 -0
  402. package/src/sessions/registry.ts +6 -0
  403. package/src/shared-types-extra.ts +2 -4
  404. package/src/shared-types.d.ts +8 -0
  405. package/src/shared-types.ts +64 -1
  406. package/src/status/builders.ts +26 -6
  407. package/src/status/normalize.ts +2 -0
  408. package/src/status/reporter.ts +19 -1
  409. package/src/status/snapshot.ts +95 -26
  410. package/src/system/hash.ts +23 -0
  411. package/src/system/host-memory.ts +29 -12
  412. package/src/system/load-better-sqlite3.ts +68 -0
  413. package/src/types.ts +5 -0
  414. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  415. package/dist/mesh/mesh-sync.d.ts +0 -53
  416. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  417. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  418. package/src/mesh/mesh-sync.ts +0 -111
@@ -13,19 +13,25 @@ import { createRequire } from 'node:module';
13
13
  import { normalizeInputEnvelope, type ProviderModule, flattenContent, type InputEnvelope, type InputPart } from './contracts.js';
14
14
  import { assertProviderSupportsDeclaredInput, getEffectiveMessageInputSupport } from './provider-input-support.js';
15
15
  import type { ProviderInstance, ProviderState, ProviderEvent, InstanceContext, ProviderErrorReason, HotChatSessionState, SessionModalState } from './provider-instance.js';
16
+ import { normalizeInteractivePrompt, normalizeInteractivePromptResponse, type InteractivePrompt } from './types/interactive-prompt.js';
16
17
  import { ProviderCliAdapter } from '../cli-adapters/provider-cli-adapter.js';
18
+ import { shortHash } from '../system/hash.js';
17
19
  import type { CliProviderModule } from '../cli-adapters/provider-cli-adapter.js';
20
+ import { createCliAdapter } from './spec/route.js';
18
21
  import type { PtyRuntimeMetadata, PtyTransportFactory } from '../cli-adapters/pty-transport.js';
19
22
  import { StatusMonitor } from './status-monitor.js';
20
23
  import { ChatHistoryWriter, isNativeSourceCanonicalHistory, materializeProviderNativeHistory, readChatHistory, readProviderChatHistory } from '../config/chat-history.js';
21
24
  import { LOG } from '../logging/logger.js';
25
+ import { traceMeshEventStage, traceMeshEventDrop } from '../mesh/mesh-event-trace.js';
22
26
  import type { ChatMessage } from '../types.js';
23
27
  import { buildPersistedProviderEffectMessage, normalizeProviderEffects } from './control-effects.js';
24
- import { formatAutoApprovalMessage, pickApprovalButton } from './approval-utils.js';
28
+ import { formatAutoApprovalMessage, pickApprovalButton, hasNegativeApprovalOption, looksLikeActiveApprovalPromptText } from './approval-utils.js';
25
29
  import { getCliScriptCommand, parseCliScriptResult } from './cli-script-results.js';
26
30
  import { mergeProviderPatchState, resolveProviderStateSurface } from './provider-patch-state.js';
27
31
  import { normalizeProviderSessionId } from './provider-session-id.js';
28
32
  import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
33
+ import { workingDirBasename } from './working-dir.js';
34
+ import { ManualAttendanceTracker } from './manual-attendance.js';
29
35
 
30
36
  type PersistableCliHistoryMessage = {
31
37
  role: string;
@@ -35,16 +41,108 @@ type PersistableCliHistoryMessage = {
35
41
  receivedAt?: number;
36
42
  };
37
43
 
44
+ // Status snapshots only ever surface the newest messages: the cloud 'live'
45
+ // profile drops chat messages entirely (loaded lazily via read_chat on
46
+ // subscribe) and the 'full' profile caps activeChat.messages to the last 60
47
+ // (see status/normalize.ts). Unread/completion markers walk only the tail.
48
+ // So getState()'s saved-history hydration — which runs once per resume/manual
49
+ // CLI session on every status report — must read only a bounded tail, not the
50
+ // entire transcript. A full MAX_SAFE_INTEGER read here makes the initial
51
+ // status report O(transcript) × N(sessions), which is the real cold first-
52
+ // connection bottleneck on chat-heavy machines. The window comfortably exceeds
53
+ // the 60-message snapshot cap so dedup/collapse at the boundary stays stable.
54
+ const STATUS_HYDRATION_TAIL_LIMIT = 200;
55
+
38
56
  type CompletedDebouncePending = {
39
57
  chatTitle: string;
40
58
  duration: number;
41
59
  timestamp: number;
42
60
  firstObservedAt: number;
61
+ previousStatus: string;
43
62
  loggedBlockReason?: string;
63
+ loggedTranscriptProbe?: boolean;
64
+ transcriptProbeHistory?: ExternalTranscriptProbe[];
65
+ };
66
+
67
+ function isIdleStatus(value: unknown): boolean {
68
+ const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
69
+ return !status || status === 'idle' || status === 'ready';
70
+ }
71
+
72
+
73
+ function getMessageTime(message: unknown): number {
74
+ if (!message || typeof message !== 'object') return 0;
75
+ const record = message as { receivedAt?: unknown; timestamp?: unknown };
76
+ const value = Number(record.receivedAt ?? record.timestamp ?? 0);
77
+ return Number.isFinite(value) ? value : 0;
78
+ }
79
+
80
+ type CompletedFinalizationBlock = {
81
+ reason: string;
82
+ terminal?: boolean;
83
+ allowTimeout?: boolean;
84
+ // (SETTLE-VALLEY) When set, suppress the CANON-C decoupled-immediate emit for this
85
+ // missing_final_assistant block and HOLD (retry up to COMPLETED_FINALIZATION_MAX_WAIT_MS)
86
+ // until the native transcript's final assistant turn arrives (block clears → genuine emit)
87
+ // or the worker resumes (resume guard cancels). Set only for the inter-approval idle valley
88
+ // of a native-history mesh worker, where an immediate weak emit would freeze a truncated
89
+ // preamble summary (evidenceLevel=insufficient) into the append-only ledger before the
90
+ // worker's next approval turn resumes. Independent of valley length.
91
+ holdForTranscript?: boolean;
92
+ };
93
+
94
+ type CompletionFinalAssistantEvidence = {
95
+ present: boolean;
96
+ messages: unknown[];
97
+ source: 'parsed' | 'external-native' | 'unavailable';
98
+ };
99
+
100
+ type ExternalTranscriptProbe = {
101
+ readAt: number;
102
+ msgCount: number;
103
+ lastRole: string | null;
104
+ lastKind: string | null;
105
+ contentLen: number;
106
+ sourcePath: string | null;
107
+ sourceMtimeMs: number | null;
108
+ mtimeAgeMs: number | null;
44
109
  };
45
110
 
46
111
  const COMPLETED_FINALIZATION_RETRY_MS = 1000;
47
112
  const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
113
+ // (FALSEIDLE-BGCHILD-a) Minimum generating→idle settle window for native-history mesh worker
114
+ // sessions. Native-history providers (e.g. claude-cli) normally flush the completion with
115
+ // flushDelay=0 — the transcript is authoritative, so there is no reason to wait. But a worker
116
+ // turn that spawns a BACKGROUND child (e.g. `npm test &`, a backgrounded Bash tool) can paint
117
+ // a burst of child output, fall quiet, and have the screen parser read a PRIOR/intermediate
118
+ // standard assistant as if the turn were done — firing a false idle while the agent is in fact
119
+ // still generating (e.g. mid-commit). With flushDelay=0 there is no window for the resume guard
120
+ // in flushCompletedDebounceIfFinalized (latestVisibleStatus !== 'idle' → cancel) to observe the
121
+ // agent picking the turn back up. A short non-zero settle window restores that resume guard for
122
+ // mesh workers without delaying genuinely-finished turns beyond this bound. Scoped to mesh
123
+ // worker sessions so interactive native-history sessions keep the immediate flush.
124
+ // 4000ms (was 1500): live measurement showed the completion event can fire 1.6–3s
125
+ // BEFORE the worker's final-assistant turn lands in the transcript on a natural
126
+ // generating→idle completion (no approval modal), freezing a prior intermediate
127
+ // bubble as finalSummary (evidenceLevel=insufficient). The 68a3c324 waiting_approval
128
+ // hold only covers the approval-resolved valley; widening this settle window to 4000ms
129
+ // covers that race AND the ~3s waiting_approval valley within the settle bound.
130
+ const NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4000;
131
+ // TASKBUBBLE-DUP: window during which an identical user-input ack (same trimmed
132
+ // content on the same instance) is treated as a redelivery of one dispatch and
133
+ // suppressed from the chat transcript. Matches the coordinator-side
134
+ // DUPLICATE_DISPATCH_WINDOW_MS (mesh-tools) so the daemon's bubble-level guard
135
+ // covers the same retry horizon as the MCP-level dispatch dedup.
136
+ const USER_INPUT_ACK_DEDUP_WINDOW_MS = 60_000;
137
+
138
+ /** Events that signal a dispatched mesh task has reached a terminal state.
139
+ * Detach the mesh assignment after emitting one of these so the worker's
140
+ * next unrelated turn doesn't impersonate another completion. */
141
+ const TERMINAL_MESH_EVENTS = new Set([
142
+ 'agent:generating_completed',
143
+ 'agent:stopped',
144
+ 'agent:ready',
145
+ ]);
48
146
 
49
147
  const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
50
148
  'image/png': '.png',
@@ -120,7 +218,7 @@ function hasNonEmptyCliModalButtons(activeModal: unknown): boolean {
120
218
  }
121
219
 
122
220
  function isCliGeneratingLikeStatus(status: unknown): boolean {
123
- return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
221
+ return status === 'generating' || status === 'streaming' || status === 'no_progress' || status === 'long_generating' || status === 'starting';
124
222
  }
125
223
 
126
224
  export function buildCliStructuredInputPrompt(
@@ -300,24 +398,114 @@ export class CliProviderInstance implements ProviderInstance {
300
398
  readonly type: string;
301
399
  readonly category = 'cli' as const;
302
400
 
401
+ /**
402
+ * Quiet period an approval modal's signature must be stable before
403
+ * auto-approve sends the approve key. Guards against firing on a prompt
404
+ * that is still streaming into the PTY (the "resolves too fast" symptom):
405
+ * while the modal text/buttons are still changing, every frame yields a
406
+ * new signature and the settle clock restarts. Once the prompt finishes
407
+ * rendering the signature holds and the key is sent after this window.
408
+ * Bounded + small so genuine approvals stay timely. The FSM is already
409
+ * authoritative over the `waiting_approval` state; this only delays the
410
+ * keystroke until the modal *content* has settled.
411
+ */
412
+ private static readonly AUTO_APPROVE_SETTLE_MS = 600;
413
+
414
+ /**
415
+ * Busy-side hysteresis for the settle gate. A momentary `generating` flip
416
+ * while the SAME approval modal's button block is still on screen (its
417
+ * question line scrolled out of the captured frame, only the buttons + a
418
+ * residual `esc to interrupt` spinner remain) briefly reports
419
+ * status!=waiting_approval. Without hysteresis that flip wipes the settle
420
+ * clock, and the modal→generating→modal flap restarts the 600ms window
421
+ * every time so auto-approve never fires. We keep the in-progress settle
422
+ * gate warm across an inactive blip up to this bound; only once the modal
423
+ * has genuinely stayed gone this long (a real resolution → idle) is the
424
+ * gate cleared. Bounded so a genuinely new, later approval still re-settles
425
+ * from scratch rather than firing on a stale timestamp.
426
+ */
427
+ private static readonly AUTO_APPROVE_GATE_HYSTERESIS_MS = 1500;
428
+
429
+ /**
430
+ * STATUS-MISMATCH: upper bound on how long the auto-approve→`generating` SURFACE
431
+ * mask may hide a worker's `waiting_approval` (status + activeModal) before we give
432
+ * up and surface the real prompt. The mask exists because auto-approve is expected
433
+ * to resolve the modal momentarily; but if it STALLS without ever calling
434
+ * resolveModal — the modal signature never settles for AUTO_APPROVE_SETTLE_MS (a
435
+ * perpetually-flapping/streaming prompt), no concrete modal is ever captured, or the
436
+ * modal is a picker/non-affirmative we never auto-pick — the mask would persist
437
+ * forever and read_chat / mesh_status / the dashboard would NEVER see the pending
438
+ * approval (the coordinator cannot mesh_approve what it cannot see). Once an episode
439
+ * exceeds this bound we stop masking. Generously larger than
440
+ * AUTO_APPROVE_SETTLE_MS (600) + AUTO_APPROVE_GATE_HYSTERESIS_MS (1500) so a
441
+ * legitimately slow-settling / blip-flapping prompt is never unmasked early; a
442
+ * genuine never-resolving stall surfaces within this window. The settle gate keeps
443
+ * running underneath, so a prompt that finally stabilises still auto-approves, and
444
+ * mesh_approve (raw FSM, unmasked) works throughout.
445
+ */
446
+ private static readonly AUTO_APPROVE_MASK_STALL_MS = 4500;
447
+
303
448
  private adapter: ProviderCliAdapter;
304
449
  private context: InstanceContext | null = null;
305
450
  private events: ProviderEvent[] = [];
306
451
  private lastStatus: string = 'starting';
452
+ // Idempotency guard for the queue-claim agent:ready event. agent:ready is the
453
+ // sole signal the mesh coordinator's tryAssignQueueTask waits on to hand a
454
+ // queued task to this worker. It is emitted in two places: the boot-time
455
+ // starting→idle one-shot, and the readySeen re-arm below. This flag makes the
456
+ // event fire AT MOST ONCE per session so a worker is never claimed twice and a
457
+ // queued task is never double-dispatched/double-injected. Whichever path fires
458
+ // first sets it; the other becomes a no-op.
459
+ private agentReadyEmitted = false;
307
460
  private generatingStartedAt: number = 0;
308
461
  private settings: Record<string, any> = {};
309
462
  private monitor: StatusMonitor;
310
463
  private generatingDebounceTimer: NodeJS.Timeout | null = null;
311
464
  private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
312
- private lastApprovalEventAt = 0;
465
+ private lastApprovalEventFingerprint = '';
313
466
  private autoApproveBusy = false;
314
467
  private autoApproveBusyTimer: NodeJS.Timeout | null = null;
468
+ private lastAutoApprovalSignature = '';
469
+ // Settle gate: the approval modal's signature + the wall-clock when this
470
+ // exact signature was first observed. Auto-approve only fires once the
471
+ // SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
472
+ // still streaming into the PTY (its buttons/message changing frame to
473
+ // frame) keeps resetting the timer and is never approved half-rendered.
474
+ private pendingAutoApprovalSignature = '';
475
+ private pendingAutoApprovalSince = 0;
476
+ private autoApproveSettleTimer: NodeJS.Timeout | null = null;
477
+ // Wall-clock when auto-approve first observed status!=waiting_approval while
478
+ // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS so a
479
+ // brief generating flip does not immediately wipe the settle clock.
480
+ private autoApproveInactiveSince = 0;
481
+ // STATUS-MISMATCH: wall-clock when the CURRENT auto-approve episode (waiting_approval
482
+ // + shouldAutoApprove) first began wanting to mask. Unlike pendingAutoApprovalSince it
483
+ // is NOT reset when the modal signature changes (a still-streaming/flapping prompt) and
484
+ // survives the same hysteresis blips the settle gate does, so it measures the TRUE age
485
+ // of an unresolved auto-approve. Once it exceeds AUTO_APPROVE_MASK_STALL_MS the surface
486
+ // mask is dropped so the real waiting_approval surfaces. Cleared when the episode ends
487
+ // (modal genuinely gone, manual attendance takes over, or auto-approve fires).
488
+ private autoApproveMaskSince = 0;
489
+ // Provider-common manual-attendance signal: while a human is actively driving
490
+ // this session from the dashboard, auto-approve holds so they can take manual
491
+ // control. Background mesh workers are never attended → delegated auto-approve
492
+ // is unaffected.
493
+ private readonly manualAttendance = new ManualAttendanceTracker();
315
494
  private controlValues: Record<string, string | number | boolean> = {};
316
495
  private summaryMetadata: unknown = undefined;
317
496
  private appliedEffectKeys = new Set<string>();
318
497
  private historyWriter: ChatHistoryWriter;
319
498
  private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
320
499
  private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
500
+ private lastAcknowledgedUserInputAt = 0;
501
+ // TASKBUBBLE-DUP: per-content last-ack timestamps so the same dispatched
502
+ // prompt acked twice in quick succession (the worker buffers the first
503
+ // send during bootstrap/busy, then a redelivery — dispatch-confirm-timeout
504
+ // requeue or a reconcile re-dispatch — fires a SECOND send_chat before the
505
+ // outbound queue drains) collapses to ONE user bubble. Keyed on the trimmed
506
+ // content; an entry older than USER_INPUT_ACK_DEDUP_WINDOW_MS is treated as
507
+ // a fresh, intentional resend and is NOT suppressed.
508
+ private recentUserInputAcks = new Map<string, number>();
321
509
  private lastNativeSourceCanonicalCheckAt = 0;
322
510
  private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
323
511
  private cachedSqliteDb: {
@@ -330,6 +518,7 @@ export class CliProviderInstance implements ProviderInstance {
330
518
  private suppressIdleHistoryReplay = false;
331
519
  private errorMessage: string | undefined = undefined;
332
520
  private errorReason: ProviderErrorReason | undefined = undefined;
521
+ private activeInteractivePrompt: InteractivePrompt | null = null;
333
522
 
334
523
  private presentationMode: 'terminal' | 'chat';
335
524
  private providerSessionId?: string;
@@ -370,7 +559,10 @@ export class CliProviderInstance implements ProviderInstance {
370
559
  this.providerSessionId = options?.providerSessionId;
371
560
  this.launchMode = options?.launchMode || 'new';
372
561
  this.onProviderSessionResolved = options?.onProviderSessionResolved;
373
- this.adapter = new ProviderCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory);
562
+ this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
563
+ if (this.providerSessionId) {
564
+ this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
565
+ }
374
566
  this.monitor = new StatusMonitor();
375
567
  this.historyWriter = new ChatHistoryWriter();
376
568
  }
@@ -389,8 +581,8 @@ export class CliProviderInstance implements ProviderInstance {
389
581
  this.adapter.updateRuntimeSettings?.(this.settings);
390
582
  this.monitor.updateConfig({
391
583
  approvalAlert: this.settings.approvalAlert !== false,
392
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
393
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
584
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
585
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
394
586
  });
395
587
 
396
588
  // Server connection
@@ -412,7 +604,7 @@ export class CliProviderInstance implements ProviderInstance {
412
604
  await this.adapter.spawn();
413
605
  await this.enforceFreshSessionLaunchIfNeeded();
414
606
  this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
415
- if (this.providerSessionId) {
607
+ if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
416
608
  this.restorePersistedHistoryFromCurrentSession();
417
609
  }
418
610
  if (this.providerSessionId && this.launchMode === 'resume') {
@@ -486,14 +678,38 @@ export class CliProviderInstance implements ProviderInstance {
486
678
  }
487
679
 
488
680
  getState(): ProviderState {
681
+ // TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
682
+ // parseSession) are currently invoked by CliScriptRunner.invoke() via direct
683
+ // function calls — the scripts run in the daemon process with full Node.js
684
+ // access and no resource limits.
685
+ //
686
+ // When Phase 5 lands, CliScriptRunner should route these calls through a
687
+ // SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
688
+ // that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
689
+ // a 32 MB memory cap. The execution path to change is:
690
+ // CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
691
+ //
692
+ // This getState() call-site is NOT where the change goes — the wiring belongs
693
+ // in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
694
+ // parseSession), with provider-loader.ts updated to store script source strings
695
+ // alongside the loaded function references for extended-legacy providers.
489
696
  const adapterStatus = this.adapter.getStatus();
697
+ if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
698
+ this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
699
+ }
490
700
  let parsedStatus: any = null;
491
701
  let parseErrorMessage: string | undefined;
492
702
  if (typeof this.adapter.getScriptParsedStatus === 'function') {
493
703
  try {
494
704
  parsedStatus = this.adapter.getScriptParsedStatus() || null;
495
- this.errorMessage = undefined;
496
- this.errorReason = undefined;
705
+ const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
706
+ ? parsedStatus.errorMessage.trim()
707
+ : undefined;
708
+ const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
709
+ ? parsedStatus.errorReason.trim() as ProviderErrorReason
710
+ : undefined;
711
+ this.errorMessage = parsedErrorMessage;
712
+ this.errorReason = parsedErrorReason;
497
713
  } catch (error: any) {
498
714
  parseErrorMessage = error?.message || String(error);
499
715
  this.errorMessage = parseErrorMessage;
@@ -503,22 +719,59 @@ export class CliProviderInstance implements ProviderInstance {
503
719
  this.errorMessage = undefined;
504
720
  this.errorReason = undefined;
505
721
  }
506
- const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
507
- const visibleStatus = parseErrorMessage
508
- ? 'error'
509
- : (autoApproveActive ? 'generating' : adapterStatus.status);
510
- const parsedProviderSessionId = normalizeProviderSessionId(
722
+ const adapterProviderSessionId = normalizeProviderSessionId(
511
723
  this.provider,
512
- typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
724
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
513
725
  );
514
- if (parsedProviderSessionId) {
515
- this.promoteProviderSessionId(parsedProviderSessionId);
726
+ const nowMs = Date.now();
727
+ // STATUS-MISMATCH: maybeAutoApproveStatus still runs for its side effects (settle gate,
728
+ // resolveModal fire), but the SURFACE mask is dropped once the episode has stalled past
729
+ // AUTO_APPROVE_MASK_STALL_MS — otherwise a never-settling auto-approve hides the worker's
730
+ // waiting_approval + modal from read_chat/mesh_status/dashboard forever.
731
+ const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, nowMs)
732
+ && !this.autoApproveMaskStalled(nowMs);
733
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
734
+ let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
735
+ ? 'error'
736
+ : (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
737
+ // getState() must agree with the status the FSM-driven detectStatusTransition()
738
+ // already committed to lastStatus. The adapter's own status is authoritative; we do
739
+ // not second-guess it with native-transcript shape. Only reconcile a generating-like
740
+ // read down to idle when our own lastStatus has already flipped idle (avoids a
741
+ // perpetual dashboard spinner during the brief window before the next getStatus()).
742
+ if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
743
+ visibleStatus = 'idle';
516
744
  }
517
745
  const runtime = this.adapter.getRuntimeMetadata();
518
746
  this.maybeAppendRuntimeRecoveryMessage(runtime);
519
747
  let parsedMessages = Array.isArray(parsedStatus?.messages)
520
748
  ? parsedStatus.messages
521
749
  : [];
750
+ const parsedProviderSessionId = normalizeProviderSessionId(
751
+ this.provider,
752
+ typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
753
+ );
754
+ const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
755
+ parsedMessages,
756
+ parsedStatus,
757
+ adapterStatus,
758
+ parsedProviderSessionId,
759
+ );
760
+ if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
761
+ this.promoteProviderSessionId(adapterProviderSessionId);
762
+ }
763
+ if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
764
+ this.promoteProviderSessionId(parsedProviderSessionId);
765
+ }
766
+ if (suppressFreshLaunchStartupReplay) {
767
+ parsedMessages = [];
768
+ }
769
+ // Adapter runtime metadata is transport-owned and is not guaranteed to
770
+ // identify this conversation. Spec adapters historically exposed the
771
+ // provider spec id (for example "codex-cli") as runtimeId, which made
772
+ // concurrent sessions share one activeChat identity until their native
773
+ // provider session ids were discovered.
774
+ const activeChatId = this.providerSessionId || this.instanceId;
522
775
  const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
523
776
  ? Math.max(0, Number(parsedStatus.historyMessageCount))
524
777
  : null;
@@ -528,9 +781,20 @@ export class CliProviderInstance implements ProviderInstance {
528
781
  : [];
529
782
  }
530
783
  const mergedMessages = this.mergeConversationMessages(parsedMessages);
531
- const canonicalBackedHistory = this.syncCanonicalSavedHistoryIfNeeded();
784
+ const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
785
+ ? this.syncCanonicalSavedHistoryIfNeeded()
786
+ : false;
787
+ const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
788
+ ? this.lastPersistedHistoryMessages.map((message) => ({
789
+ role: message.role,
790
+ content: message.content,
791
+ kind: message.kind,
792
+ senderName: message.senderName,
793
+ receivedAt: message.receivedAt,
794
+ }))
795
+ : mergedMessages;
532
796
 
533
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
797
+ const dirName = workingDirBasename(this.workingDir);
534
798
  const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
535
799
  ? parsedStatus.status.trim()
536
800
  : undefined;
@@ -542,7 +806,7 @@ export class CliProviderInstance implements ProviderInstance {
542
806
  && adapterStatus.status === 'idle'
543
807
  && parsedStatus?.status === 'idle';
544
808
  let messagesToSave = parsedMessages;
545
- if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'long_generating')) {
809
+ if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'no_progress' || parsedChatStatus === 'long_generating')) {
546
810
  const lastIdx = messagesToSave.length - 1;
547
811
  if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === 'assistant') {
548
812
  messagesToSave = messagesToSave.slice(0, lastIdx);
@@ -572,33 +836,48 @@ export class CliProviderInstance implements ProviderInstance {
572
836
  }
573
837
  }
574
838
 
575
- this.applyProviderResponse(parsedStatus, { phase: 'immediate' });
839
+ this.applyProviderResponse(
840
+ suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
841
+ ? { ...parsedStatus, providerSessionId: undefined }
842
+ : parsedStatus,
843
+ { phase: 'immediate' },
844
+ );
576
845
  const surface = resolveProviderStateSurface({
577
846
  summaryMetadata: this.summaryMetadata as any,
578
847
  controlValues: this.controlValues,
579
848
  });
580
849
  const activeChatStatus = parseErrorMessage
581
850
  ? 'error'
582
- : autoApproveActive && parsedStatus?.status === 'waiting_approval'
851
+ : (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
583
852
  ? 'generating'
584
853
  : (adapterStatus.status !== 'idle'
585
854
  ? visibleStatus
586
855
  : (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
587
856
 
857
+ // If an AskUserQuestion prompt is awaiting user input, overlay status as
858
+ // waiting_choice. This is distinct from waiting_approval (tool-use consent)
859
+ // — the engine's isWaitingForResponse state is unchanged, so completion
860
+ // tracking continues normally once the user responds.
861
+ const hasInteractivePrompt = !!this.activeInteractivePrompt;
862
+ const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
863
+ const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
864
+
588
865
  return {
589
866
  type: this.type,
590
867
  name: this.provider.name,
591
868
  category: 'cli',
592
- status: visibleStatus,
869
+ status: finalStatus,
593
870
  mode: this.presentationMode,
594
871
  activeChat: {
595
- id: `${this.type}_${this.workingDir}`,
872
+ id: activeChatId,
596
873
  title: parsedStatus?.title || dirName,
597
- status: activeChatStatus,
598
- messages: mergedMessages,
599
- activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
874
+ status: finalChatStatus,
875
+ messages: statusMessages,
876
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
877
+ activeInteractivePrompt: this.activeInteractivePrompt,
600
878
  inputContent: '',
601
879
  },
880
+ activeInteractivePrompt: this.activeInteractivePrompt,
602
881
  workspace: this.workingDir,
603
882
  instanceId: this.instanceId,
604
883
  providerSessionId: this.providerSessionId,
@@ -638,8 +917,12 @@ export class CliProviderInstance implements ProviderInstance {
638
917
 
639
918
  getHotChatSessionState(): HotChatSessionState {
640
919
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
641
- const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
642
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
920
+ const nowMs = Date.now();
921
+ // STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
922
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
923
+ && !this.autoApproveMaskStalled(nowMs);
924
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
925
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
643
926
  const runtime = this.adapter.getRuntimeMetadata();
644
927
  return {
645
928
  id: this.instanceId,
@@ -651,36 +934,198 @@ export class CliProviderInstance implements ProviderInstance {
651
934
  };
652
935
  }
653
936
 
654
- getSessionModalState(): SessionModalState {
655
- const adapterStatus = this.adapter.getStatus({ allowParse: false });
656
- const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
657
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
658
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
937
+ getSessionModalState(sessionId?: string): SessionModalState {
938
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
939
+ const nowMs = Date.now();
940
+ // STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
941
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
942
+ && !this.autoApproveMaskStalled(nowMs);
943
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
944
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
945
+ const dirName = workingDirBasename(this.workingDir);
659
946
  return {
660
- id: this.instanceId,
947
+ // Honor the caller-supplied sessionId — InstanceMgr rejects the
948
+ // projection when projected.id !== requested sessionId, and
949
+ // this.instanceId is the manager's internal key, not the public
950
+ // sessionId the dashboard subscribes by.
951
+ id: sessionId ?? this.instanceId,
661
952
  status: visibleStatus,
662
953
  title: dirName,
663
- activeModal: autoApproveActive ? null : adapterStatus.activeModal,
954
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
664
955
  };
665
956
  }
666
957
 
667
958
  updateSettings(newSettings: Record<string, any>): void {
668
- this.settings = { ...newSettings };
959
+ // Merge semantics: a key omitted from newSettings preserves its existing
960
+ // value, a key present in newSettings (even as false) overrides it.
961
+ //
962
+ // This is required because updateSettings has two callers with opposite
963
+ // intent:
964
+ // 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
965
+ // → getSettings → updateInstanceSettings) sends the COMPLETE settings
966
+ // object, so an explicit autoApprove:false must win.
967
+ // 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
968
+ // buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
969
+ // meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
970
+ // re-dispatch. It carries no autoApprove, so a full replacement would
971
+ // wipe the launch-time autoApprove:true the worker was started with,
972
+ // silently dropping every later approval to a manual gate until the
973
+ // machine-page toggle re-injected the full settings.
974
+ //
975
+ // A plain merge satisfies both: undefined keys fall through to the existing
976
+ // value (preserving launch-stamp settings like autoApprove + the mesh routing
977
+ // keys), explicit keys override. This subsumes the previous mesh-key preserve
978
+ // list, which only protected the routing keys and not autoApprove.
979
+ this.settings = { ...this.settings, ...newSettings };
669
980
  this.adapter.updateRuntimeSettings?.(this.settings);
670
981
  this.monitor.updateConfig({
671
982
  approvalAlert: this.settings.approvalAlert !== false,
672
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
673
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
983
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
984
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
674
985
  });
675
986
  }
676
987
 
988
+ /**
989
+ * Stamp a direct-dispatch mesh assignment on this instance.
990
+ * setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
991
+ * route generating_completed back to the originating coordinator. Without
992
+ * this stamp, mesh_send_task --direct targets a plain CLI session whose
993
+ * completion events silently drop because the forwarder has nothing to
994
+ * match against.
995
+ */
996
+ attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string; coordinatorSessionId?: string }): void {
997
+ if (!assignment?.meshId) return;
998
+ this.settings = {
999
+ ...this.settings,
1000
+ meshNodeFor: assignment.meshId,
1001
+ // WTCLAIM (A): track the bound node id under BOTH the active marker
1002
+ // (meshNodeId, cleared on detach) and a sticky marker (meshLastNodeId,
1003
+ // preserved across detach). The sticky marker lets a detached but still
1004
+ // coordinator-owned session be re-picked ONLY for the SAME node it served
1005
+ // — never auto-adopted for a sibling node (e.g. a cloned worktree) that
1006
+ // shares this daemon. See isMeshOwnedDelegateSession's post-detach gate.
1007
+ ...(assignment.nodeId ? { meshNodeId: assignment.nodeId, meshLastNodeId: assignment.nodeId } : {}),
1008
+ ...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
1009
+ ...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
1010
+ // Session-level routing anchor: the originating coordinator session, so this
1011
+ // worker's completion events route back to the exact session that dispatched it.
1012
+ ...(assignment.coordinatorSessionId ? { meshCoordinatorSessionId: assignment.coordinatorSessionId } : {}),
1013
+ };
1014
+ this.adapter.updateRuntimeSettings?.(this.settings);
1015
+ }
1016
+
1017
+ /**
1018
+ * Clear a previously-attached mesh assignment after the task reaches a
1019
+ * terminal state. Leaving meshNodeFor pinned would route this session's
1020
+ * subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
1021
+ * coordinator as if they were task completions.
1022
+ *
1023
+ * MESHID-DROP-ON-DETACH (Fix C): a coordinator-LAUNCHED worker session
1024
+ * (launchedByCoordinator) holds its mesh membership (meshNodeFor / meshNodeId /
1025
+ * meshCoordinatorDaemonId) at the SESSION level — set once at launch
1026
+ * (mesh_launch_session / queue auto-launch), independent of any single task.
1027
+ * The original detach wiped meshNodeFor + meshNodeId together with the
1028
+ * task-level meshActiveTaskId, so the FIRST task completion stripped the
1029
+ * membership and EVERY subsequent completion forwarded with meshId absent —
1030
+ * resolveWorkerDelegateRouting fell to mesh_unresolved and the coordinator
1031
+ * rejected the forward "meshId required". For a launched member we therefore
1032
+ * clear ONLY the task-level marker (meshActiveTaskId) and preserve the
1033
+ * session-level membership so its next task's completion still resolves.
1034
+ * A task-less ad-hoc turn on a preserved-membership session is NOT misrouted:
1035
+ * its completion carries no taskId and the session holds no active assignment,
1036
+ * so the forwarder's WARMUPGAP guard skips the dispatch-row flip (it only
1037
+ * injects a benign task-less notification). A NON-launched session (a plain CLI
1038
+ * session adopted by mesh_send_task --direct, launchedByCoordinator falsy)
1039
+ * keeps the original full clear so an ad-hoc session is never left pinned.
1040
+ */
1041
+ detachMeshAssignment(): void {
1042
+ if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
1043
+ // Session-level member: keep membership, drop only the task-level marker.
1044
+ if (this.settings.launchedByCoordinator === true) {
1045
+ if (!this.settings.meshActiveTaskId) return;
1046
+ const { meshActiveTaskId, ...rest } = this.settings;
1047
+ void meshActiveTaskId;
1048
+ this.settings = rest;
1049
+ this.adapter.updateRuntimeSettings?.(this.settings);
1050
+ return;
1051
+ }
1052
+ const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
1053
+ void meshNodeFor; void meshActiveTaskId;
1054
+ // WTCLAIM (A): clear the active binding but PRESERVE the last bound node id
1055
+ // (meshLastNodeId) so a later sessionless dispatch can re-adopt this idle
1056
+ // session ONLY for the node it last served. Carry the id being cleared, or
1057
+ // keep an already-present sticky marker if meshNodeId was absent.
1058
+ const lastNodeId = (typeof meshNodeId === 'string' && meshNodeId.trim())
1059
+ ? meshNodeId.trim()
1060
+ : (typeof rest.meshLastNodeId === 'string' && rest.meshLastNodeId.trim() ? rest.meshLastNodeId.trim() : undefined);
1061
+ this.settings = lastNodeId ? { ...rest, meshLastNodeId: lastNodeId } : rest;
1062
+ this.adapter.updateRuntimeSettings?.(this.settings);
1063
+ }
1064
+
1065
+ /**
1066
+ * The resolved modal-park status of this session, or null when it is not
1067
+ * parked on a modal awaiting a human answer. Mirrors the overlay logic in
1068
+ * getState(): an active AskUserQuestion interactive prompt resolves to
1069
+ * waiting_choice; otherwise the adapter's waiting_approval (tool consent)
1070
+ * counts — UNLESS auto-approve will dismiss it, in which case the session is
1071
+ * effectively generating and is NOT modal-parked. This is the single signal
1072
+ * the mesh force-inject guard consults, and the same status string the
1073
+ * reconcile loop reads off get_status_metadata. Lowercase literals only —
1074
+ * the SessionStatus enum is forked across modules and waiting_choice is
1075
+ * absent from some of them.
1076
+ */
1077
+ resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
1078
+ if (this.activeInteractivePrompt) return 'waiting_choice';
1079
+ let adapterStatus: { status?: string };
1080
+ try {
1081
+ adapterStatus = this.adapter.getStatus({ allowParse: false });
1082
+ } catch {
1083
+ return null;
1084
+ }
1085
+ // A session whose auto-approve is held by manual attendance IS parked on a
1086
+ // modal awaiting the human — autoApproveEffectivelyActive folds that in, so
1087
+ // the mesh force-inject guard correctly treats it as modal-parked. STATUS-MISMATCH:
1088
+ // a STALLED auto-approve (never resolving) is likewise effectively parked — treat it
1089
+ // as modal-parked so its events are held/surfaced rather than masked behind generating.
1090
+ if (adapterStatus.status === 'waiting_approval'
1091
+ && (!this.autoApproveEffectivelyActive(adapterStatus.status) || this.autoApproveMaskStalled())) {
1092
+ return 'waiting_approval';
1093
+ }
1094
+ return null;
1095
+ }
1096
+
1097
+ /** True when this session is parked on a modal awaiting a human answer. */
1098
+ isModalParked(): boolean {
1099
+ return this.resolveModalParkStatus() !== null;
1100
+ }
1101
+
677
1102
  onEvent(event: string, data?: any): void {
678
1103
  if (event === 'send_message') {
679
1104
  const input = normalizeInputEnvelope(data);
680
1105
  assertProviderSupportsDeclaredInput(this.provider, input);
681
1106
  const promptText = buildCliStructuredInputPrompt(input);
682
1107
  if (promptText) {
683
- void this.adapter.sendMessage(promptText).catch((e: any) => {
1108
+ // force:true bypasses the busy/generating send guard so terminal mesh
1109
+ // events (completion/failure/bootstrap) land in a coordinator session that
1110
+ // is itself parked in `generating` while awaiting that very event.
1111
+ // Without it the message is queued and only flushed on the coordinator's
1112
+ // own idle transition — which never happens until it receives the message.
1113
+ const force = data?.force === true;
1114
+ // Modal guard: a force-inject still writes raw keystrokes into the PTY,
1115
+ // bypassing the busy send-guard. If the coordinator is parked on a
1116
+ // harness modal (claude-cli AskUserQuestion → waiting_choice, or a
1117
+ // tool-consent waiting_approval), those keystrokes are consumed by the
1118
+ // modal's key handler and silently select a choice the user never made
1119
+ // (data corruption). Hold the force-inject in that narrow window —
1120
+ // the event stays queued and the reconcile loop redelivers it on the
1121
+ // next tick once the modal is resolved. We ONLY hold for the two modal
1122
+ // states; generating is still force-injected (that is the deadlock the
1123
+ // force path exists to break — see mesh-events-coordinator).
1124
+ if (force && this.isModalParked()) {
1125
+ LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
1126
+ return;
1127
+ }
1128
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
684
1129
  LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
685
1130
  });
686
1131
  }
@@ -690,14 +1135,101 @@ export class CliProviderInstance implements ProviderInstance {
690
1135
  void this.adapter.resolveAction(data).catch((e: any) => {
691
1136
  LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
692
1137
  });
1138
+ } else if (event === 'interactive_prompt' && data) {
1139
+ const prompt = normalizeInteractivePrompt(data);
1140
+ if (prompt) {
1141
+ this.activeInteractivePrompt = prompt;
1142
+ this.events.push({
1143
+ event: 'interactive_prompt',
1144
+ timestamp: Date.now(),
1145
+ promptId: prompt.promptId,
1146
+ });
1147
+ }
1148
+ } else if (event === 'interactive_prompt_response' && data) {
1149
+ try {
1150
+ const response = normalizeInteractivePromptResponse(data);
1151
+ if (this.activeInteractivePrompt?.promptId === response.promptId) {
1152
+ this.activeInteractivePrompt = null;
1153
+ }
1154
+ if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
1155
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
1156
+ return;
1157
+ }
1158
+ void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
1159
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
1160
+ });
1161
+ } catch (e: any) {
1162
+ LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
1163
+ }
693
1164
  } else if (event === 'provider_state_patch' && data && typeof data === 'object') {
694
1165
  this.applyProviderResponse(data, { phase: 'immediate' });
695
1166
  }
696
1167
  }
697
1168
 
1169
+ recordAcknowledgedUserInput(input: InputEnvelope | string): void {
1170
+ const content = typeof input === 'string'
1171
+ ? input.trim()
1172
+ : buildCliStructuredInputPrompt(input).trim();
1173
+ if (!content) return;
1174
+
1175
+ const receivedAt = Date.now();
1176
+
1177
+ // TASKBUBBLE-DUP: collapse a redelivered dispatch to one bubble. A single
1178
+ // mesh_send_task can reach this instance as TWO send_chat calls when the
1179
+ // first injection is buffered during bootstrap/busy and a retry (dispatch-
1180
+ // confirm-timeout requeue, or a reconcile re-dispatch) fires before the
1181
+ // outbound queue drains. The previous dedupKey hashed receivedAt, so the
1182
+ // two acks produced different keys and BOTH bubbled. Suppress an identical
1183
+ // content ack seen within USER_INPUT_ACK_DEDUP_WINDOW_MS; a later resend of
1184
+ // the same text (beyond the window) is a genuine new turn and still shows.
1185
+ const ackContentKey = shortHash(`${this.instanceId}:${content}`, 24);
1186
+ const lastAckAt = this.recentUserInputAcks.get(ackContentKey);
1187
+ if (lastAckAt !== undefined && receivedAt - lastAckAt <= USER_INPUT_ACK_DEDUP_WINDOW_MS) {
1188
+ // Refresh the timestamp so a steady stream of redeliveries keeps
1189
+ // collapsing, and prune stale entries to bound the map size.
1190
+ this.recentUserInputAcks.set(ackContentKey, receivedAt);
1191
+ this.pruneRecentUserInputAcks(receivedAt);
1192
+ return;
1193
+ }
1194
+ this.recentUserInputAcks.set(ackContentKey, receivedAt);
1195
+ this.pruneRecentUserInputAcks(receivedAt);
1196
+
1197
+ this.lastAcknowledgedUserInputAt = receivedAt;
1198
+ // The runtimeMessages dedupKey stays per-call unique (includes receivedAt)
1199
+ // so a genuine resend of the same text after the window appends a fresh
1200
+ // bubble; redelivery within the window is already suppressed above.
1201
+ const dedupKey = `user_input_ack:${shortHash(`${this.instanceId}:${content}:${receivedAt}`, 24)}`;
1202
+ this.appendRuntimeMessage(buildChatMessage({
1203
+ role: 'user',
1204
+ senderName: 'User',
1205
+ kind: 'standard',
1206
+ content,
1207
+ receivedAt,
1208
+ timestamp: receivedAt,
1209
+ source: 'runtime_input_ack',
1210
+ meta: {
1211
+ runtimeInputAck: true,
1212
+ provider: this.type,
1213
+ workspace: this.workingDir,
1214
+ },
1215
+ } as ChatMessage), dedupKey);
1216
+ }
1217
+
1218
+ /** Drop user-input ack entries older than the dedup window so the map can't grow unbounded. */
1219
+ private pruneRecentUserInputAcks(now: number): void {
1220
+ if (this.recentUserInputAcks.size <= 1) return;
1221
+ for (const [key, at] of this.recentUserInputAcks) {
1222
+ if (now - at > USER_INPUT_ACK_DEDUP_WINDOW_MS) this.recentUserInputAcks.delete(key);
1223
+ }
1224
+ }
1225
+
698
1226
  dispose(): void {
699
1227
  this.adapter.shutdown();
700
1228
  this.monitor.reset();
1229
+ // Cancel any armed auto-approve timers so a pending settle re-check
1230
+ // can't fire resolveModal/detectStatusTransition against a dead adapter.
1231
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1232
+ if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
701
1233
  this.appliedEffectKeys.clear();
702
1234
  try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
703
1235
  this.cachedSqliteDb = null;
@@ -706,6 +1238,7 @@ export class CliProviderInstance implements ProviderInstance {
706
1238
 
707
1239
  private completedDebounceTimer: NodeJS.Timeout | null = null;
708
1240
  private completedDebouncePending: CompletedDebouncePending | null = null;
1241
+ private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
709
1242
 
710
1243
  private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
711
1244
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
@@ -740,7 +1273,180 @@ export class CliProviderInstance implements ProviderInstance {
740
1273
  const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
741
1274
  const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
742
1275
  const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
743
- return role === 'assistant' && !!content;
1276
+ if (role !== 'assistant' || !content) return false;
1277
+ // Guard: if the last assistant message looks like an active approval/input prompt,
1278
+ // it is not a real completion — the session is still awaiting user input.
1279
+ if (looksLikeActiveApprovalPromptText(content)) return false;
1280
+ return true;
1281
+ }
1282
+
1283
+ private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
1284
+ const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1285
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1286
+ const readAt = Date.now();
1287
+ const mtimeMs = Number(sourceMtimeMs) || 0;
1288
+ return {
1289
+ readAt,
1290
+ msgCount: messages.length,
1291
+ lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
1292
+ lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
1293
+ contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
1294
+ sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
1295
+ sourceMtimeMs: mtimeMs || null,
1296
+ mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
1297
+ };
1298
+ }
1299
+
1300
+ private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
1301
+ const probe = this.lastExternalCompletionProbe;
1302
+ if (!probe) return null;
1303
+ const history = pending.transcriptProbeHistory || [];
1304
+ const last = history[history.length - 1];
1305
+ if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
1306
+ history.push(probe);
1307
+ pending.transcriptProbeHistory = history.slice(-5);
1308
+ }
1309
+ return probe;
1310
+ }
1311
+
1312
+ private readExternalCompletionMessages(): unknown[] | null {
1313
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1314
+ if (!adapterOwnsMessagesElsewhere) return null;
1315
+ if (!this.providerSessionId) return null;
1316
+ if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
1317
+
1318
+ if (this.lastExternalCompletionProbe?.sourcePath) {
1319
+ try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
1320
+ }
1321
+ const restoredHistory = readProviderChatHistory(this.type, {
1322
+ canonicalHistory: this.provider.nativeHistory,
1323
+ historySessionId: this.providerSessionId,
1324
+ workspace: this.workingDir,
1325
+ offset: 0,
1326
+ limit: Number.MAX_SAFE_INTEGER,
1327
+ historyBehavior: this.provider.historyBehavior,
1328
+ scripts: this.provider.scripts as any,
1329
+ sessionStartedAtMs: this.startedAt,
1330
+ forceRefresh: true,
1331
+ });
1332
+ if (restoredHistory.source !== 'provider-native') {
1333
+ this.lastExternalCompletionProbe = null;
1334
+ return null;
1335
+ }
1336
+ this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
1337
+ restoredHistory.messages,
1338
+ restoredHistory.sourcePath,
1339
+ restoredHistory.sourceMtimeMs,
1340
+ );
1341
+ return restoredHistory.messages;
1342
+ }
1343
+
1344
+ private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
1345
+ if (this.completionHasFinalAssistantMessage(parsedMessages)) {
1346
+ return {
1347
+ present: true,
1348
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1349
+ source: 'parsed',
1350
+ };
1351
+ }
1352
+
1353
+ const externalMessages = this.readExternalCompletionMessages();
1354
+ if (externalMessages) {
1355
+ return {
1356
+ present: this.completionHasFinalAssistantMessage(externalMessages),
1357
+ messages: externalMessages,
1358
+ source: 'external-native',
1359
+ };
1360
+ }
1361
+
1362
+ return {
1363
+ present: false,
1364
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1365
+ source: 'unavailable',
1366
+ };
1367
+ }
1368
+
1369
+ private completionFinalSummary(parsedMessages: unknown): string | undefined {
1370
+ // For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
1371
+ // screen parse is NOT the source of truth for the final summary — the terminal
1372
+ // wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
1373
+ // prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
1374
+ // the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
1375
+ // to the parsed screen only when the transcript is unavailable. This is the real cause
1376
+ // of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
1377
+ // any short, fast-completing task where screen parse wins the race).
1378
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1379
+ const parsedSummary = extractFinalSummaryFromMessages(
1380
+ (this.completionHasFinalAssistantMessage(parsedMessages)
1381
+ ? (Array.isArray(parsedMessages) ? parsedMessages : [])
1382
+ : []) as any,
1383
+ );
1384
+ if (adapterOwnsMessagesElsewhere) {
1385
+ const externalMessages = this.readExternalCompletionMessages();
1386
+ const externalSummary = externalMessages
1387
+ ? extractFinalSummaryFromMessages(externalMessages as any)
1388
+ : '';
1389
+ // The transcript is authoritative for native-source providers. Use it unless it is
1390
+ // empty (not yet written) — only then fall back to whatever the screen parsed.
1391
+ if (externalSummary) return externalSummary;
1392
+ return parsedSummary || undefined;
1393
+ }
1394
+ return parsedSummary || undefined;
1395
+ }
1396
+
1397
+ private buildCompletedFinalizationDiagnostic(args: {
1398
+ blockReason: string;
1399
+ latestStatus?: any;
1400
+ latestVisibleStatus: string;
1401
+ waitedMs: number;
1402
+ pending: CompletedDebouncePending;
1403
+ emittedAfterFinalizationTimeout: boolean;
1404
+ }): Record<string, unknown> {
1405
+ let parsed: any = null;
1406
+ let parseError: string | undefined;
1407
+ try {
1408
+ parsed = this.adapter.getScriptParsedStatus();
1409
+ } catch (error: any) {
1410
+ parseError = error?.message || String(error);
1411
+ }
1412
+
1413
+ const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
1414
+ if (evidence.source === 'external-native') {
1415
+ this.recordPendingTranscriptProbe(args.pending);
1416
+ }
1417
+ const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
1418
+ .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1419
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1420
+ const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
1421
+ const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
1422
+ const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
1423
+
1424
+ return {
1425
+ providerType: this.type,
1426
+ sessionId: this.instanceId,
1427
+ providerSessionId: this.providerSessionId || null,
1428
+ workspace: this.workingDir,
1429
+ blockReason: args.blockReason,
1430
+ emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
1431
+ waitedMs: args.waitedMs,
1432
+ maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
1433
+ adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
1434
+ latestVisibleStatus: args.latestVisibleStatus,
1435
+ parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
1436
+ parseError: parseError || undefined,
1437
+ finalAssistantPresent: evidence.present,
1438
+ finalAssistantEvidenceSource: evidence.source,
1439
+ visibleMessageCount: visibleMessages.length,
1440
+ lastVisibleRole,
1441
+ lastVisibleKind,
1442
+ lastVisibleContentLength,
1443
+ pendingStartedAt: this.generatingStartedAt || null,
1444
+ pendingFirstObservedAt: args.pending.firstObservedAt,
1445
+ pendingTimestamp: args.pending.timestamp,
1446
+ pendingDurationSec: args.pending.duration,
1447
+ previousBlockReason: args.pending.loggedBlockReason || null,
1448
+ transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
1449
+ };
744
1450
  }
745
1451
 
746
1452
  private hasAdapterPendingResponse(): boolean {
@@ -765,41 +1471,188 @@ export class CliProviderInstance implements ProviderInstance {
765
1471
  if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
766
1472
  if (adapterRawStatus !== 'idle') return false;
767
1473
  if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
768
- return !this.hasAdapterPendingResponse();
1474
+ if (this.hasAdapterPendingResponse()) return false;
1475
+ // Do not suppress when the adapter's raw response buffer is still non-empty.
1476
+ // This catches the case where isWaitingForResponse has already flipped to false
1477
+ // (so getPartialResponse() returns '') but the provider's native parser still
1478
+ // reports generating because it's parsing buffered content. Suppressing the
1479
+ // finalization block here would emit a false completion event while the provider
1480
+ // session is still actively processing its response stream.
1481
+ const adapterAny = this.adapter as any;
1482
+ if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
1483
+ return true;
769
1484
  }
770
1485
 
771
- private getCompletedFinalizationBlockReason(latestVisibleStatus: string): string | null {
772
- if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}`;
1486
+ private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1487
+ if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
773
1488
 
774
1489
  const adapterAny = this.adapter as any;
775
- if (adapterAny?.isWaitingForResponse === true) return 'adapter_waiting_for_response';
776
- if (adapterAny?.currentTurnScope) return 'adapter_turn_scope_active';
1490
+ const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
1491
+ if (!approvalResolvedIdle) {
1492
+ if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
1493
+ if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
1494
+ if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
1495
+ }
777
1496
 
778
1497
  const partial = typeof this.adapter.getPartialResponse === 'function'
779
1498
  ? this.adapter.getPartialResponse()
780
1499
  : '';
781
- if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
1500
+ if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
782
1501
 
783
1502
  let parsed: any;
784
1503
  try {
785
1504
  parsed = this.adapter.getScriptParsedStatus();
786
1505
  } catch (error: any) {
787
- return `parse_error:${error?.message || String(error)}`;
1506
+ return { reason: `parse_error:${error?.message || String(error)}` };
788
1507
  }
789
1508
 
790
1509
  const parsedStatus = typeof parsed?.status === 'string' ? parsed.status : 'unknown';
791
- if (parsedStatus !== 'idle') return `parsed_status:${parsedStatus}`;
792
- if (parsed?.activeModal || parsed?.modal) return 'parsed_modal_active';
793
- if (!this.completionHasFinalAssistantMessage(parsed?.messages)) return 'missing_final_assistant';
1510
+ if (parsedStatus !== 'idle') {
1511
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1512
+ if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
1513
+ return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
1514
+ }
1515
+ if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
1516
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1517
+ const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
1518
+ const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1519
+ LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
1520
+ if (!finalAssistantEvidence.present) {
1521
+ if (adapterOwnsMessagesElsewhere) {
1522
+ if (finalAssistantEvidence.source === 'external-native') {
1523
+ const probe = this.recordPendingTranscriptProbe(pending);
1524
+ if (probe && !pending.loggedTranscriptProbe) {
1525
+ LOG.info('CLI', `[${this.type}] external transcript probe: msgCount=${probe.msgCount} lastRole=${probe.lastRole || 'none'} lastKind=${probe.lastKind || 'none'} contentLen=${probe.contentLen} sourceMtime=${probe.sourceMtimeMs ?? 'unknown'} mtimeAge=${probe.mtimeAgeMs ?? 'unknown'}ms`);
1526
+ pending.loggedTranscriptProbe = true;
1527
+ }
1528
+ LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
1529
+ if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
1530
+ return null;
1531
+ }
1532
+ if (this.type === 'antigravity-cli') {
1533
+ return null;
1534
+ }
1535
+ // (SETTLE-VALLEY) The inter-approval idle valley: a native-history mesh worker
1536
+ // that resolved an approval and fell briefly idle (waiting_approval→idle) BEFORE
1537
+ // the next approval turn resumes. The live valley (~3s) is mostly covered by the
1538
+ // 4000ms NATIVE_HISTORY_MESH_IDLE_SETTLE_MS settle window, but a longer valley can
1539
+ // still let the flush run while the transcript's final assistant turn is not yet
1540
+ // written (source still the screen parse → finalAssistantPresent=false,
1541
+ // workerResult.source='default'). CANON-C would emit immediately here, freezing a
1542
+ // truncated preamble summary as evidenceLevel=insufficient. Instead HOLD: this
1543
+ // waiting_approval hold complements the settle window. Retry until the transcript finalizes
1544
+ // (block clears → genuine emit) or the worker resumes (resume guard cancels),
1545
+ // bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS. Scoped to the approval-resolved
1546
+ // idle so a genuinely-finished background-child turn keeps the CANON-C immediate
1547
+ // emit (its transcript trails by a write, not by a whole resume).
1548
+ if (allowMissingAssistantTimeout && pending.previousStatus === 'waiting_approval') {
1549
+ return { reason: 'missing_final_assistant', terminal: false, holdForTranscript: true };
1550
+ }
1551
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1552
+ }
1553
+ if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
1554
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1555
+ }
1556
+ } else {
1557
+ LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
1558
+ return {
1559
+ reason: 'missing_final_assistant',
1560
+ terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
1561
+ allowTimeout: allowMissingAssistantTimeout,
1562
+ };
1563
+ }
1564
+ }
1565
+
1566
+ // (FALSEIDLE-a) Structural approval-resolution gate. Runs BEFORE the brittle
1567
+ // screen-text heuristic below so it also catches modals whose text does not match
1568
+ // looksLikeActiveApprovalPromptText (e.g. claude-cli's cd / "untrusted hooks" prompt).
1569
+ const approvalResolutionBlock = this.approvalResolutionFinalizationBlock(pending);
1570
+ if (approvalResolutionBlock) return approvalResolutionBlock;
1571
+
1572
+ // Guard: if the screen still shows an approval/choice prompt as the last visible text,
1573
+ // the turn is not complete even if the parsed status says idle and there is an assistant
1574
+ // message. This catches the case where waiting_approval→idle transitions occur before
1575
+ // the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
1576
+ try {
1577
+ const screenText = typeof (this.adapter as any).getScreenText === 'function'
1578
+ ? String((this.adapter as any).getScreenText() || '')
1579
+ : '';
1580
+ if (screenText) {
1581
+ const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
1582
+ if (looksLikeActiveApprovalPromptText(tailLines)) {
1583
+ return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
1584
+ }
1585
+ }
1586
+ } catch { /* defensive: screen text read is best-effort */ }
794
1587
 
795
1588
  return null;
796
1589
  }
797
1590
 
1591
+ // (FALSEIDLE-a) Positive, structural proof that the latest approval entry was resolved
1592
+ // through ADHDev. resolveModal() — driven by auto-approve, dashboard/mesh_approve, and
1593
+ // dev-cli-debug alike — advances the engine's lastResolvedEntrySeq to the current
1594
+ // approvalEntrySeq. So `lastResolvedEntrySeq >= approvalEntrySeq` (with a real entry,
1595
+ // approvalEntrySeq > 0) means the modal we last saw was actually answered. Absence of this
1596
+ // evidence after a waiting_approval→idle transition means the idle is suspect: the spec's
1597
+ // text-based approval→idle rule false-tripped while the modal is still unresolved.
1598
+ // Fails OPEN (returns true) when the seq fields are unavailable, so the gate can never wedge
1599
+ // a session on a provider/adapter that does not surface the counters.
1600
+ private hasApprovalResolutionEvidence(): boolean {
1601
+ try {
1602
+ const status = this.adapter.getStatus({ allowParse: false }) as any;
1603
+ const entrySeq = typeof status?.approvalEntrySeq === 'number' ? status.approvalEntrySeq : 0;
1604
+ if (entrySeq <= 0) return true;
1605
+ const resolvedSeq = typeof status?.lastResolvedEntrySeq === 'number' ? status.lastResolvedEntrySeq : undefined;
1606
+ if (resolvedSeq === undefined) return true;
1607
+ return resolvedSeq >= entrySeq;
1608
+ } catch {
1609
+ return true;
1610
+ }
1611
+ }
1612
+
1613
+ // (FALSEIDLE-a) Hold a completion that is the anomalous DIRECT waiting_approval→idle
1614
+ // transition with no positive resolution evidence. A genuinely resolved approval routes
1615
+ // through resolveModal → setStatus('generating'), so its completion's previousStatus is
1616
+ // 'generating' (not 'waiting_approval') and this gate never fires for it. Scoped to
1617
+ // delegated mesh/coordinator sessions — whose only modal-resolution path is auto-approve /
1618
+ // mesh_approve (both advance lastResolvedEntrySeq) — so an interactive local session, where
1619
+ // a human may answer the PTY prompt directly and leave no resolveModal record, is untouched.
1620
+ // Non-terminal: the hold is bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS (30s), giving a
1621
+ // settling auto-approve time to fire and advance the seq, and guaranteeing no permanent wedge
1622
+ // if resolution ever happens via a path that does not record evidence.
1623
+ private approvalResolutionFinalizationBlock(pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1624
+ if (pending.previousStatus !== 'waiting_approval') return null;
1625
+ const meshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1626
+ if (!meshContext) return null;
1627
+ if (this.hasApprovalResolutionEvidence()) return null;
1628
+ return { reason: 'approval_resolution_unconfirmed', terminal: false };
1629
+ }
1630
+
798
1631
  private scheduleCompletedDebounceFlush(delayMs: number): void {
799
1632
  if (this.completedDebounceTimer) clearTimeout(this.completedDebounceTimer);
800
1633
  this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
801
1634
  }
802
1635
 
1636
+ // EVTTRACE (observation-only): is this a mesh worker session whose completion
1637
+ // events must route to a coordinator? Used purely to gate trace logging so a
1638
+ // non-mesh CLI session's completions don't add EvtTrace noise. No decision logic.
1639
+ private isMeshWorkerSession(): boolean {
1640
+ return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId
1641
+ || this.settings.meshNodeId || this.settings.launchedByCoordinator);
1642
+ }
1643
+
1644
+ // EVTTRACE correlation context for this session's completion lifecycle. taskId is
1645
+ // the primary grep anchor; instanceId is the session fallback.
1646
+ private meshTraceCtx(event = 'agent:generating_completed'): Record<string, unknown> {
1647
+ return {
1648
+ taskId: this.settings.meshActiveTaskId,
1649
+ sessionId: this.instanceId,
1650
+ nodeId: this.settings.meshNodeId,
1651
+ meshId: this.settings.meshNodeFor,
1652
+ event,
1653
+ };
1654
+ }
1655
+
803
1656
  private flushCompletedDebounceIfFinalized(): void {
804
1657
  const pending = this.completedDebouncePending;
805
1658
  if (!pending) {
@@ -809,7 +1662,8 @@ export class CliProviderInstance implements ProviderInstance {
809
1662
 
810
1663
  const latestStatus = this.adapter.getStatus({ allowParse: false });
811
1664
  const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
812
- const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
1665
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
1666
+ LOG.debug('CLI', `[${this.type}] flush attempt: adapterStatus=${latestStatus.status} latestVisible=${latestVisibleStatus} generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse} hasPartial=${!!this.adapter.getPartialResponse?.()}`);
813
1667
  if (latestVisibleStatus !== 'idle') {
814
1668
  LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
815
1669
  this.completedDebouncePending = null;
@@ -817,84 +1671,410 @@ export class CliProviderInstance implements ProviderInstance {
817
1671
  return;
818
1672
  }
819
1673
 
820
- const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
821
- if (blockReason) {
1674
+ const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
1675
+ if (block) {
1676
+ const blockReason = block.reason;
822
1677
  const waitedMs = Date.now() - pending.firstObservedAt;
823
- if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
1678
+ // CANON-C (completion-gate decouple): a block carrying `allowTimeout` is the
1679
+ // transcript-evidence gate — the worker FSM has ALREADY reached idle and the only
1680
+ // thing missing is the append-only transcript's final assistant turn (a native-source
1681
+ // race: claude-cli owns its history externally and the file write trails the idle
1682
+ // transition). `allowTimeout` is set ONLY on the missing_final_assistant block, and
1683
+ // ONLY for mesh worker sessions (meshNodeFor / meshActiveTaskId / launchedByCoordinator).
1684
+ // The coordinator's sole path to learn this session is idle is agent:generating_completed,
1685
+ // so holding it up to COMPLETED_FINALIZATION_MAX_WAIT_MS (30s) leaves the coordinator
1686
+ // false-generating while the worker is done. Decouple the idle NOTIFICATION from the
1687
+ // transcript evidence: emit the completion immediately, marked weak
1688
+ // (completionDiagnostic.blockReason=missing_final_assistant, finalAssistantPresent=false).
1689
+ // The finalSummary is enriched on a SEPARATE path — the mesh reconcile loop reads the
1690
+ // transcript once written and re-emits a GENUINE completion (CANON-B weak→genuine
1691
+ // upgrade; buildPendingEventFingerprint keeps weak and genuine distinct so the enriched
1692
+ // one still surfaces, and isFalseIdleCompletion keeps the direct dispatch active until
1693
+ // then). All OTHER blocks (genuinely-busy adapter/partial/parsed states, transient
1694
+ // parse_error) keep the existing terminal-hold / 30s-retry behavior unchanged.
1695
+ //
1696
+ // (SETTLE-VALLEY) Exception: a `holdForTranscript` block is the inter-approval idle
1697
+ // valley of a native-history mesh worker (waiting_approval→idle that will resume into
1698
+ // the next approval). It deliberately does NOT carry allowTimeout, so it falls into the
1699
+ // hold-and-retry path below (terminal:false) rather than the CANON-C immediate emit —
1700
+ // the retry loop re-runs the resume guard each cycle, so when the worker resumes the
1701
+ // pending completion is cancelled, and when the transcript's final assistant arrives the
1702
+ // block clears for a GENUINE emit. This blocks the truncated weak (insufficient) summary
1703
+ // from ever being emitted during the valley, without depending on the valley's length.
1704
+ const isTranscriptEvidenceGate = block.allowTimeout === true;
1705
+ LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} allowTimeout=${isTranscriptEvidenceGate} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
1706
+ if (!isTranscriptEvidenceGate && (block.terminal || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS)) {
824
1707
  if (pending.loggedBlockReason !== blockReason) {
825
1708
  LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
1709
+ // EVTTRACE: completion held by the finalization gate (CANON-C). Observation
1710
+ // only — does not change the hold decision above.
1711
+ if (this.isMeshWorkerSession()) {
1712
+ traceMeshEventDrop('completion_gate_hold', this.meshTraceCtx(), `${blockReason} waited=${waitedMs}ms`);
1713
+ }
826
1714
  pending.loggedBlockReason = blockReason;
827
1715
  }
828
1716
  this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
829
1717
  return;
830
1718
  }
831
- LOG.warn('CLI', `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1719
+ const emittedAfterFinalizationTimeout = waitedMs >= COMPLETED_FINALIZATION_MAX_WAIT_MS;
1720
+ const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
1721
+ blockReason,
1722
+ latestStatus,
1723
+ latestVisibleStatus,
1724
+ waitedMs,
1725
+ pending,
1726
+ emittedAfterFinalizationTimeout,
1727
+ });
1728
+ // Surface the CANON-C immediate-emit path distinctly so a delegated worker's idle
1729
+ // notification (transcript still pending) is not mistaken for a 30s-timeout fallback.
1730
+ (completionDiagnostic as Record<string, unknown>).decoupledImmediateEmit = isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout;
1731
+ LOG.warn('CLI', `[${this.type}] emitting completed event (${isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'CANON-C decoupled-immediate, transcript pending' : `after ${waitedMs}ms`}) without finalized assistant turn (${blockReason})`);
1732
+ // EVTTRACE: completion fired (forced past the finalization timeout / CANON-C decoupled-immediate).
1733
+ if (this.isMeshWorkerSession()) {
1734
+ traceMeshEventStage('fired', this.meshTraceCtx(), `forced after ${waitedMs}ms (${blockReason})`);
1735
+ }
1736
+ this.pushEvent({
1737
+ event: 'agent:generating_completed',
1738
+ chatTitle: pending.chatTitle,
1739
+ duration: pending.duration,
1740
+ timestamp: pending.timestamp,
1741
+ // When finalization is forced past the timeout on a `parsed_status:` block
1742
+ // (the parser never confirmed a final assistant turn) we previously rode an
1743
+ // empty `finalSummary` unconditionally. That empty value propagates to the
1744
+ // mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
1745
+ // delegated session's inbox preview blank — or, for a LOCAL worktree session,
1746
+ // stuck on the dispatched user task. If the parser DID surface assistant text,
1747
+ // prefer it; only fall back to '' when no assistant summary can be derived.
1748
+ finalSummary: blockReason.startsWith('parsed_status:')
1749
+ ? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages) ?? '')
1750
+ : this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
1751
+ completionDiagnostic,
1752
+ });
832
1753
  this.completedDebouncePending = null;
833
1754
  this.completedDebounceTimer = null;
834
1755
  this.generatingStartedAt = 0;
1756
+ this.lastApprovalEventFingerprint = '';
835
1757
  return;
836
1758
  }
837
1759
 
838
1760
  LOG.info('CLI', `[${this.type}] completed in ${pending.duration}s`);
1761
+ // EVTTRACE: completion fired (transcript finalized cleanly).
1762
+ if (this.isMeshWorkerSession()) {
1763
+ traceMeshEventStage('fired', this.meshTraceCtx(), `duration=${pending.duration}s`);
1764
+ }
839
1765
  this.pushEvent({
840
1766
  event: 'agent:generating_completed',
841
1767
  chatTitle: pending.chatTitle,
842
1768
  duration: pending.duration,
843
1769
  timestamp: pending.timestamp,
844
- finalSummary: extractFinalSummaryFromMessages(this.adapter?.getScriptParsedStatus()?.messages),
1770
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
845
1771
  });
846
1772
  this.completedDebouncePending = null;
847
1773
  this.completedDebounceTimer = null;
848
1774
  this.generatingStartedAt = 0;
1775
+ this.lastApprovalEventFingerprint = '';
849
1776
  }
850
1777
 
851
1778
  private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
1779
+ // Manual-attendance suppression (provider-common): when a human is
1780
+ // actively driving this session from the dashboard, hold auto-approve so
1781
+ // the modal stays visible and they can pick a button / use the controlbar
1782
+ // themselves. Return false (NOT auto-approving) so getState keeps the
1783
+ // modal surfaced. Clear any in-progress settle gate — a genuine fire
1784
+ // after the window lapses must re-settle from scratch — and arm a
1785
+ // re-check for the lapse moment, because the PTY may have gone silent and
1786
+ // would otherwise never re-drive this decision. Background mesh workers
1787
+ // are never attended, so their delegated auto-approve is untouched.
1788
+ if (adapterStatus?.status === 'waiting_approval'
1789
+ && this.shouldAutoApprove()
1790
+ && this.manualAttendance.isAttended(now)) {
1791
+ this.lastAutoApprovalSignature = '';
1792
+ this.pendingAutoApprovalSignature = '';
1793
+ this.pendingAutoApprovalSince = 0;
1794
+ this.autoApproveInactiveSince = 0;
1795
+ // Manual attendance takes over — the modal stays surfaced (maybeAutoApproveStatus
1796
+ // returns false), so end the mask episode.
1797
+ this.autoApproveMaskSince = 0;
1798
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1799
+ this.autoApproveSettleTimer = setTimeout(() => {
1800
+ this.autoApproveSettleTimer = null;
1801
+ this.recheckAutoApproveSettled();
1802
+ }, this.manualAttendance.remainingMs(now) + 20);
1803
+ return false;
1804
+ }
852
1805
  const autoApproveActive = adapterStatus?.status === 'waiting_approval' && this.shouldAutoApprove();
853
1806
  // Guard re-entry: onStatusChange/getState can observe the same modal multiple
854
1807
  // times while the PTY absorbs the approval key. Without this flag, repeated
855
1808
  // snapshots would write stray keys into the input once the modal dismisses.
856
- if (autoApproveActive && !this.autoApproveBusy) {
857
- this.autoApproveBusy = true;
858
- if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
859
- this.autoApproveBusyTimer = setTimeout(() => {
860
- this.autoApproveBusy = false;
861
- this.autoApproveBusyTimer = null;
862
- }, 2000);
863
- const modal = adapterStatus.activeModal;
864
- const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(modal?.buttons, this.provider);
865
- this.recordAutoApproval(modal?.message, buttonLabel, now);
866
- setTimeout(() => {
867
- this.adapter.resolveModal(buttonIndex);
868
- }, 0);
1809
+ // However, Claude Code can present a second approval immediately after the
1810
+ // first. Resolve a changed modal signature even while the previous write is
1811
+ // still inside the short busy window.
1812
+ if (!autoApproveActive) {
1813
+ this.lastAutoApprovalSignature = '';
1814
+ // Hysteresis: if a settle gate is mid-progress, a momentary
1815
+ // status!=waiting_approval blip (a generating flip while the same
1816
+ // modal's button block is still on screen) must NOT wipe the settle
1817
+ // clock otherwise the modal→generating→modal flap restarts the
1818
+ // 600ms window every time and auto-approve never fires. Keep the
1819
+ // gate warm for AUTO_APPROVE_GATE_HYSTERESIS_MS; re-arm a timer so
1820
+ // that if the modal does NOT come back the gate is cleared on the
1821
+ // re-check (a genuine resolution → idle frees the gate normally).
1822
+ if (this.pendingAutoApprovalSince) {
1823
+ if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
1824
+ const goneForMs = now - this.autoApproveInactiveSince;
1825
+ if (goneForMs < CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS) {
1826
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1827
+ this.autoApproveSettleTimer = setTimeout(() => {
1828
+ this.autoApproveSettleTimer = null;
1829
+ this.recheckAutoApproveSettled();
1830
+ }, CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS - goneForMs + 20);
1831
+ return autoApproveActive;
1832
+ }
1833
+ }
1834
+ // Clear the settle gate so the next approval starts its own quiet
1835
+ // window from scratch (a stale timestamp would let it fire instantly).
1836
+ this.pendingAutoApprovalSignature = '';
1837
+ this.pendingAutoApprovalSince = 0;
1838
+ this.autoApproveInactiveSince = 0;
1839
+ // Modal has genuinely been gone past the hysteresis window → the episode ended;
1840
+ // end the mask episode too (a later approval starts a fresh stall clock).
1841
+ this.autoApproveMaskSince = 0;
1842
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1843
+ return autoApproveActive;
1844
+ }
1845
+ // Active approval observed — reset the inactivity tracker so a later
1846
+ // blip starts its hysteresis window fresh.
1847
+ this.autoApproveInactiveSince = 0;
1848
+ // STATUS-MISMATCH: start (or keep) the mask-stall clock for this episode. Set ONLY
1849
+ // when zero so it survives modal-signature changes and hysteresis blips — it measures
1850
+ // the true age of the unresolved auto-approve, not the per-signature settle window.
1851
+ if (!this.autoApproveMaskSince) this.autoApproveMaskSince = now;
1852
+ const modal = adapterStatus.activeModal;
1853
+ // (fix) Do not auto-approve when no concrete modal/buttons are present.
1854
+ // Claude TUI flaps between paints; without this guard adapterStatus
1855
+ // could report status=waiting_approval with activeModal=null (or with
1856
+ // an empty buttons array briefly) and we'd still call
1857
+ // resolveModal(-1) — which used to type "1" into the prompt
1858
+ // repeatedly. Skip until a real modal is captured.
1859
+ const buttons = Array.isArray(modal?.buttons)
1860
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
1861
+ : [];
1862
+ if (!modal || buttons.length === 0) {
1863
+ return autoApproveActive;
1864
+ }
1865
+ // Picker/confirm exclusion (provider-common). A /model or /mode picker is
1866
+ // surfaced with status=waiting_approval so the dashboard shows it, but it
1867
+ // has no "correct" answer to auto-pick — blindly selecting the first
1868
+ // option silently switches the model (the "always Opus, before I even
1869
+ // choose" bug). Two independent gates, BOTH must pass to fire:
1870
+ //
1871
+ // (1) modal_kind — the spec/FSM tells us this is an 'approval' modal,
1872
+ // not a 'picker'/'confirm'. A modal whose kind is unknown (legacy
1873
+ // adapter, or a spec that predates modal_kind) reads as 'approval'
1874
+ // so genuine approvals keep auto-approving; only an explicit
1875
+ // 'picker'/'confirm' is excluded here.
1876
+ // (2) structural anchor — a real approval offers an affirmative AND a
1877
+ // decline option (pickApprovalButton finds a positive that isn't a
1878
+ // decline, and hasNegativeApprovalOption confirms a No/Cancel/Deny
1879
+ // is present). A model picker ("1. Default 2. Opus 3. Sonnet")
1880
+ // has no decline, so even an un-migrated picker is caught here.
1881
+ //
1882
+ // Mirrors the SDK v1 detect-status approval heuristic (detect-status.ts).
1883
+ const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
1884
+ if (modalKind !== 'approval') {
1885
+ // Picker/confirm — leave it for the user; keep the modal surfaced.
1886
+ return autoApproveActive;
869
1887
  }
1888
+ const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
1889
+ if (buttonIndex < 0 || !hasNegativeApprovalOption(buttons)) {
1890
+ // No affirmative matched, or no decline option present (→ not a real
1891
+ // consent prompt, e.g. a picker that slipped past the kind gate).
1892
+ // Surface the modal so the user decides; never pick blindly.
1893
+ return autoApproveActive;
1894
+ }
1895
+ // Modal *identity* signature — the question/button set only, NO volatile
1896
+ // counters. This is what the settle gate tracks: the FSM bumps
1897
+ // approvalEntrySeq on every fresh waiting_approval entry, and a
1898
+ // modal→generating→modal flap (the question line scrolled out of the
1899
+ // captured frame while the button block stays) re-enters and bumps it
1900
+ // again. Folding that seq into the settle signature made the 600ms
1901
+ // settle clock restart on every flap, so the modal never stayed stable
1902
+ // long enough to fire — the gate was never satisfied. Identity excludes
1903
+ // the seq so button/seq flap of the SAME modal keeps one settle clock.
1904
+ const modalSignature = [
1905
+ typeof modal?.message === 'string' ? modal.message.trim() : '',
1906
+ buttons.join('|'),
1907
+ buttonIndex,
1908
+ ].join('::');
1909
+ // Busy-window re-entry guard still needs the seq: two DISTINCT
1910
+ // back-to-back approvals can carry identical message/buttons (common
1911
+ // with claude-cli). Without the seq their busy signatures collide and
1912
+ // the 5s busy-window guard below would swallow the second auto-approve,
1913
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
1914
+ // waiting_approval entry, so a new approval always yields a new busy
1915
+ // signature and fires through.
1916
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1917
+ ? adapterStatus.approvalEntrySeq
1918
+ : 0;
1919
+ const busySignature = `${approvalEntrySeq}::${modalSignature}`;
1920
+ // Already fired for this exact modal entry and still inside the busy
1921
+ // window — nothing to do (re-entry guard for repeated snapshots of one
1922
+ // modal).
1923
+ if (this.autoApproveBusy && busySignature === this.lastAutoApprovalSignature) {
1924
+ return autoApproveActive;
1925
+ }
1926
+
1927
+ // Settle gate: only fire once this modal identity has been stable for
1928
+ // AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
1929
+ // message/buttons each frame → new identity → clock restarts, so we
1930
+ // never approve a half-rendered prompt (the "resolves too fast" bug).
1931
+ if (modalSignature !== this.pendingAutoApprovalSignature) {
1932
+ this.pendingAutoApprovalSignature = modalSignature;
1933
+ this.pendingAutoApprovalSince = now;
1934
+ }
1935
+ const settledForMs = now - this.pendingAutoApprovalSince;
1936
+ if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
1937
+ // Not yet settled. Arm a timer to re-check after the remaining quiet
1938
+ // window — the PTY may go silent once the prompt finishes painting,
1939
+ // so there is no guaranteed status-change frame to re-drive us.
1940
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1941
+ this.autoApproveSettleTimer = setTimeout(() => {
1942
+ this.autoApproveSettleTimer = null;
1943
+ this.recheckAutoApproveSettled();
1944
+ }, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
1945
+ return autoApproveActive;
1946
+ }
1947
+
1948
+ // Settled — fire the approve key.
1949
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1950
+ this.autoApproveBusy = true;
1951
+ this.lastAutoApprovalSignature = busySignature;
1952
+ this.pendingAutoApprovalSignature = '';
1953
+ this.pendingAutoApprovalSince = 0;
1954
+ this.autoApproveInactiveSince = 0;
1955
+ // Fired (resolveModal in flight) — the episode resolved; end the mask-stall clock.
1956
+ this.autoApproveMaskSince = 0;
1957
+ if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
1958
+ this.autoApproveBusyTimer = setTimeout(() => {
1959
+ this.autoApproveBusy = false;
1960
+ this.autoApproveBusyTimer = null;
1961
+ this.lastAutoApprovalSignature = '';
1962
+ }, 5000);
1963
+ this.recordAutoApproval(modal?.message, buttonLabel, now);
1964
+ setTimeout(() => {
1965
+ this.adapter.resolveModal(buttonIndex);
1966
+ }, 0);
870
1967
  return autoApproveActive;
871
1968
  }
872
1969
 
1970
+ /**
1971
+ * Re-drive the auto-approve check after the settle quiet window elapses.
1972
+ * The PTY may have gone silent once the approval prompt finished painting,
1973
+ * so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
1974
+ * — this timer-driven re-check picks up the now-settled modal and fires.
1975
+ * Deliberately lighter than detectStatusTransition(): it only re-evaluates
1976
+ * the approval decision; the next real PTY frame refreshes visible status.
1977
+ */
1978
+ private recheckAutoApproveSettled(): void {
1979
+ try {
1980
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1981
+ this.maybeAutoApproveStatus(adapterStatus, Date.now());
1982
+ } catch { /* adapter gone / transient — next frame retries */ }
1983
+ }
1984
+
1985
+ /**
1986
+ * Emit the queue-claim agent:ready event at most once per session. Both the
1987
+ * boot-time starting→idle one-shot and the fsmReadySeen re-arm call this; the
1988
+ * agentReadyEmitted guard ensures the second caller is a no-op so a worker is
1989
+ * never claimed twice and a queued task is never double-dispatched.
1990
+ */
1991
+ private emitAgentReadyOnce(chatTitle: string, now: number): void {
1992
+ if (this.agentReadyEmitted) return;
1993
+ this.agentReadyEmitted = true;
1994
+ this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
1995
+ }
1996
+
873
1997
  private detectStatusTransition(): void {
874
1998
  const now = Date.now();
875
1999
  // Status-change handling is a hot path: PTY output can fire it many times
876
2000
  // during long-running CLI sessions. Keep this path on adapter-owned light
877
2001
  // state only; rich provider parsing is reserved for getState/read_chat.
878
2002
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
2003
+ const adapterProviderSessionId = normalizeProviderSessionId(
2004
+ this.provider,
2005
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
2006
+ );
2007
+ if (adapterProviderSessionId) {
2008
+ this.promoteProviderSessionId(adapterProviderSessionId);
2009
+ }
879
2010
  const parsedStatus = null;
880
2011
  const rawStatus = adapterStatus.status;
881
2012
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
882
- const newStatus = autoApproveActive ? 'generating' : rawStatus;
883
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
2013
+ // During the autoApproveBusy window (2s after firing approval key), the PTY
2014
+ // can briefly report 'idle' before the next generating phase starts. Treat that
2015
+ // transient idle as 'generating' to suppress a spurious agent:generating_completed
2016
+ // push notification. The adapter's status is otherwise authoritative — native
2017
+ // transcript shape does NOT override the FSM's busy/idle decision.
2018
+ const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
2019
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
2020
+ const dirName = workingDirBasename(this.workingDir);
884
2021
  const chatTitle = `${this.provider.name} · ${dirName}`;
885
2022
  const partial = this.adapter.getPartialResponse();
2023
+ // Liveness fingerprint for the no-progress watchdog. The parsed
2024
+ // assistant buffer (`partial`) alone goes static while a tool/build runs
2025
+ // — the assistant emits no tokens even though the PTY is actively
2026
+ // printing tool output — which made the watchdog false-fire a "stuck"
2027
+ // alert mid-turn. Fold in the adapter's raw-activity timestamps so any
2028
+ // visible terminal progress (lastScreenChangeAt) or raw PTY byte
2029
+ // (lastOutputAt) keeps the fingerprint moving. The watchdog then only
2030
+ // survives a genuine stall where nothing at all is happening.
886
2031
  const progressFingerprint = newStatus === 'generating'
887
- ? `${partial || ''}`.slice(-2000)
2032
+ ? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
888
2033
  : undefined;
889
2034
 
890
2035
  const previousStatus = this.lastStatus;
891
2036
  if (newStatus !== this.lastStatus) {
892
2037
  LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
893
- if (this.lastStatus === 'idle' && newStatus === 'generating') {
2038
+ // GENERATING-MISSING (win32 fresh-worktree first-turn): a freshly-launched session
2039
+ // is in 'starting' until its startup-grace settles to idle. When the FIRST inject
2040
+ // lands inside that grace window, the adapter can report status DIRECTLY
2041
+ // starting → generating without an intervening 'idle' frame for
2042
+ // detectStatusTransition() to observe. Previously only the idle→generating arm
2043
+ // armed the bookkeeping, so a starting→generating frame fell straight through to the
2044
+ // bare `this.lastStatus = newStatus` update: generatingStartedAt stayed 0 and no
2045
+ // generating_started was queued. The fast turn's generating→idle completion was then
2046
+ // suppressed by the startup-blip guard below (generatingStartedAt===0 &&
2047
+ // !generatingDebouncePending) — so NO generating_started AND NO generating_completed
2048
+ // ever fired and the mesh coordinator never learned the worker went idle.
2049
+ //
2050
+ // We extend the idle→generating arm to also fire on starting→generating, BUT ONLY
2051
+ // when a real turn is in flight. The adapter script can also report 'generating' from
2052
+ // pure startup PTY noise (no task dispatched) — antigravity/codex/hermes-cli all
2053
+ // exercise that benign starting→generating→idle blip, which must NOT emit a
2054
+ // completion (see "startup-phase spurious completion suppression" tests).
2055
+ // hasAdapterPendingResponse() is the discriminator: a genuine inject sets the
2056
+ // adapter's isWaitingForResponse / currentTurnScope (or leaves a partial response),
2057
+ // whereas startup repaint noise leaves all of them empty. So an armed
2058
+ // starting→generating means "the worker actually started its first turn", and a
2059
+ // bare one stays a suppressed blip via the existing fall-through.
2060
+ const startingToGeneratingWithActiveTurn = this.lastStatus === 'starting'
2061
+ && newStatus === 'generating'
2062
+ && this.hasAdapterPendingResponse();
2063
+ if (((this.lastStatus === 'idle' && newStatus === 'generating') || startingToGeneratingWithActiveTurn)) {
2064
+ // If a completion event is already pending and the turn has ended
2065
+ // (generatingStartedAt===0), the PTY is painting its prompt area
2066
+ // after completing. Ignore this blip — do not cancel the pending
2067
+ // completion and do not advance lastStatus to generating. (On a true
2068
+ // starting→generating the session is fresh: completedDebouncePending is
2069
+ // null, so this blip guard is a no-op and we arm normally below.)
2070
+ if (this.completedDebouncePending && this.generatingStartedAt === 0) {
2071
+ LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
2072
+ return;
2073
+ }
894
2074
  this.suppressIdleHistoryReplay = false;
895
2075
  // Cancel any pending completed event (multi-step: idle→generating resume)
896
2076
  if (this.completedDebouncePending) {
897
- LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
2077
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
898
2078
  if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
899
2079
  this.completedDebouncePending = null;
900
2080
  }
@@ -926,10 +2106,29 @@ export class CliProviderInstance implements ProviderInstance {
926
2106
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
927
2107
  const modal = adapterStatus.activeModal;
928
2108
  LOG.info('CLI', `[${this.type}] approval modal: "${modal?.message?.slice(0, 80) ?? 'none'}"`);
929
- // Only push event if not already in waiting_approval (prevent flood from rapid cycles)
930
- const approvalCooldown = 5000;
931
- if (this.lastStatus !== 'waiting_approval' && (!this.lastApprovalEventAt || now - this.lastApprovalEventAt > approvalCooldown)) {
932
- this.lastApprovalEventAt = now;
2109
+ // Include the FSM's approval entry seq, mirroring the auto-approve
2110
+ // path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
2111
+ // guard. Two distinct back-to-back approvals can carry identical
2112
+ // message/buttons (very common with claude-cli's "Allow Bash
2113
+ // command?"). Without the seq their fingerprints collide and the dedup
2114
+ // below silently drops the second waiting_approval event — it is never
2115
+ // emitted, so it cannot even land in the pending inbox for a later
2116
+ // read_chat reconcile to recover. The seq is bumped by the FSM on every
2117
+ // fresh waiting_approval entry, so a new approval always yields a new
2118
+ // fingerprint and emits.
2119
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
2120
+ ? adapterStatus.approvalEntrySeq
2121
+ : 0;
2122
+ const approvalFingerprint = JSON.stringify({
2123
+ message: typeof modal?.message === 'string' ? modal.message.trim() : '',
2124
+ buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
2125
+ seq: approvalEntrySeq,
2126
+ });
2127
+ // PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
2128
+ // Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
2129
+ // (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
2130
+ if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
2131
+ this.lastApprovalEventFingerprint = approvalFingerprint;
933
2132
  this.appendRuntimeSystemMessage(
934
2133
  this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
935
2134
  `approval_request:${now}`,
@@ -941,22 +2140,127 @@ export class CliProviderInstance implements ProviderInstance {
941
2140
  modalButtons: modal?.buttons,
942
2141
  });
943
2142
  }
2143
+ } else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
2144
+ // Approval resolved and the agent resumed work. Defense-in-depth:
2145
+ // clear the approval emit fingerprint here too (not only on
2146
+ // completion at scheduleCompletedDebounceFlush). A subsequent
2147
+ // waiting_approval with the same modal content as the one just
2148
+ // resolved would otherwise collide with the stale fingerprint and be
2149
+ // dropped. The seq in the fingerprint already separates entries; this
2150
+ // reset is a belt-and-suspenders guard for the re-entry case.
2151
+ this.lastApprovalEventFingerprint = '';
944
2152
  } else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
945
2153
  const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
946
- // If debounce still pending (generating lasted < 1s), cancel both events
2154
+ // Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
2155
+ // was entered from 'starting' state (startup PTY noise), not from a real idle→generating
2156
+ // task dispatch. The idle→generating handler is the only code path that sets
2157
+ // generatingStartedAt and generatingDebouncePending, so both being absent means no
2158
+ // task was ever dispatched. Suppress the spurious completion event and fall through
2159
+ // to a simple lastStatus update.
2160
+ if (!this.generatingStartedAt && !this.generatingDebouncePending) {
2161
+ LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
2162
+ } else
2163
+ // If debounce still pending (generating lasted < 1s), cancel both UI events.
2164
+ // Still emit agent:generating_completed so mesh orchestration can record
2165
+ // task_completed for direct dispatches that complete faster than the debounce.
947
2166
  if (this.generatingDebouncePending) {
948
- LOG.info('CLI', `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
2167
+ const shortDurationMs = this.generatingStartedAt ? now - this.generatingStartedAt : 0;
2168
+ LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms)`);
949
2169
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
2170
+ // Emit completion for mesh task association even though the UI generating
2171
+ // started/completed pair is suppressed (too short for visible UI update).
2172
+ let shortFinalSummary: string | undefined;
2173
+ let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
2174
+ try {
2175
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
2176
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
2177
+ shortEvidenceSource = evidence.source;
2178
+ shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
2179
+ } catch { /* best-effort */ }
2180
+ // If a real response is confirmed, retroactively emit started so the chat
2181
+ // bubble appears even though the debounce suppressed the original event.
2182
+ if (shortFinalSummary) {
2183
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
2184
+ }
950
2185
  this.generatingDebouncePending = null;
951
2186
  this.generatingStartedAt = 0;
2187
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
2188
+ if (missingEvidence) {
2189
+ LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
2190
+ }
2191
+ // When evidence is missing and there is no active mesh task context, suppress
2192
+ // the completion event. Providers with requiresFinalAssistantBeforeIdle or
2193
+ // external-native history must confirm a final assistant message before the
2194
+ // coordinator records task_completed. Only emit here if a mesh task is active
2195
+ // so the coordinator can apply its own timeout/retry logic.
2196
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
2197
+ if (missingEvidence && !hasMeshContext) {
2198
+ LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
2199
+ // completedDebouncePending intentionally left null — the session is now idle
2200
+ // with no confirmed turn, matching the startup-blip suppression semantics.
2201
+ // (No EvtTrace: not a mesh session, so nothing routes to a coordinator.)
2202
+ } else {
2203
+ // EVTTRACE: completion fired (short-generating idle path).
2204
+ if (this.isMeshWorkerSession()) {
2205
+ traceMeshEventStage('fired', this.meshTraceCtx(), `short-generating idle (source=${shortEvidenceSource})`);
2206
+ }
2207
+ this.pushEvent({
2208
+ event: 'agent:generating_completed',
2209
+ chatTitle,
2210
+ duration: 0,
2211
+ timestamp: now,
2212
+ finalSummary: shortFinalSummary,
2213
+ completionDiagnostic: {
2214
+ reason: 'short_generating_suppressed',
2215
+ shortDurationMs,
2216
+ finalAssistantEvidenceSource: shortEvidenceSource,
2217
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
2218
+ },
2219
+ });
2220
+ }
952
2221
  } else {
953
2222
  // Debounce completed, then require the rich transcript path that read_chat
954
2223
  // uses to show an idle turn whose last user-facing message is assistant.
955
- this.completedDebouncePending = { chatTitle, duration, timestamp: now, firstObservedAt: now };
956
- this.scheduleCompletedDebounceFlush(3000);
2224
+ this.completedDebouncePending = {
2225
+ chatTitle,
2226
+ duration,
2227
+ timestamp: now,
2228
+ firstObservedAt: now,
2229
+ previousStatus: this.lastStatus,
2230
+ };
2231
+ const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
2232
+ // (FALSEIDLE-BGCHILD-a) Native-history providers flush immediately (the
2233
+ // transcript is authoritative). For mesh worker sessions, give the
2234
+ // generating→idle transition a short settle window so a background-child
2235
+ // false idle (quiet after a backgrounded test/command while the parent turn
2236
+ // continues) gets caught by the resume guard in flushCompletedDebounceIfFinalized
2237
+ // instead of firing an early completion the coordinator can never correct.
2238
+ const meshWorkerSession = this.isMeshWorkerSession();
2239
+ const flushDelay = ownsExternalHistory
2240
+ ? (meshWorkerSession ? NATIVE_HISTORY_MESH_IDLE_SETTLE_MS : 0)
2241
+ : 3000;
2242
+ LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} meshWorker=${meshWorkerSession} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
2243
+ this.scheduleCompletedDebounceFlush(flushDelay);
957
2244
  }
958
2245
  } else if (newStatus === 'idle' && this.lastStatus === 'starting') {
959
- this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
2246
+ this.emitAgentReadyOnce(chatTitle, now);
2247
+ } else if (newStatus === 'error') {
2248
+ if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
2249
+ this.generatingDebouncePending = null;
2250
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2251
+ this.completedDebouncePending = null;
2252
+ this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
2253
+ this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
2254
+ this.pushEvent({
2255
+ event: 'agent:stopped',
2256
+ chatTitle,
2257
+ timestamp: now,
2258
+ finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
2259
+ completionDiagnostic: {
2260
+ reason: adapterStatus.errorReason || 'provider_error',
2261
+ errorMessage: adapterStatus.errorMessage || undefined,
2262
+ },
2263
+ });
960
2264
  } else if (newStatus === 'stopped') {
961
2265
  // Cancel any pending debounce
962
2266
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
@@ -968,6 +2272,28 @@ export class CliProviderInstance implements ProviderInstance {
968
2272
  this.lastStatus = newStatus;
969
2273
  }
970
2274
 
2275
+ // Re-arm the queue-claim agent:ready on the FSM's first GENUINE ready.
2276
+ //
2277
+ // The boot-time starting→idle one-shot above is the historical claim
2278
+ // trigger, but it is consumed too early for FSM-spec providers whose
2279
+ // INITIAL state already reports status 'idle' (e.g. antigravity-cli): the
2280
+ // adapter reports idle before maybeMarkReady has fired, so lastStatus
2281
+ // advances starting→idle while the prompt is not yet drawn and the worker
2282
+ // cannot yet claim. Subsequent state-driven idle frames are idle→idle (no
2283
+ // status change), so the one-shot never re-fires and the worker strands its
2284
+ // queued task — the coordinator then relaunch-loops every ~90s.
2285
+ //
2286
+ // The adapter surfaces fsmReadySeen=true exactly when the FSM reaches its
2287
+ // first non-initial idle (the prompt is genuinely up). On that signal we
2288
+ // emit agent:ready once more. emitAgentReadyOnce is idempotent (guarded by
2289
+ // agentReadyEmitted), so providers whose boot one-shot already landed on a
2290
+ // real ready (claude-cli / codex-cli / hermes-cli, which use a startup
2291
+ // grace and whose initial state is not idle) treat this as a no-op — no
2292
+ // double claim, no double task injection.
2293
+ if (newStatus === 'idle' && adapterStatus.fsmReadySeen === true && !this.agentReadyEmitted) {
2294
+ this.emitAgentReadyOnce(chatTitle, now);
2295
+ }
2296
+
971
2297
  this.applyProviderResponse(parsedStatus, {
972
2298
  phase: (newStatus === 'idle' && (previousStatus === 'generating' || previousStatus === 'waiting_approval'))
973
2299
  ? 'turn_completed'
@@ -976,8 +2302,43 @@ export class CliProviderInstance implements ProviderInstance {
976
2302
 
977
2303
  // Monitor check (cooldown based notification, IDE/CLI common)
978
2304
  const agentKey = `${this.type}:cli`;
979
- const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint);
2305
+ // Approval pending is detected from the raw adapter status, not `newStatus`:
2306
+ // auto-approve synthesizes `waiting_approval` → 'generating', which would
2307
+ // otherwise let the no-progress watchdog accumulate the approval wait.
2308
+ const approvalPending = rawStatus === 'waiting_approval';
2309
+ const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
2310
+ const monitorParsedStatus: any = parsedStatus;
980
2311
  for (const me of monitorEvents) {
2312
+ if (
2313
+ me.type === 'monitor:no_progress'
2314
+ && this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
2315
+ && !this.hasAdapterPendingResponse()
2316
+ && !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
2317
+ ) {
2318
+ // EVTTRACE: completion fired (no-progress monitor reconciled to completion).
2319
+ if (this.isMeshWorkerSession()) {
2320
+ traceMeshEventStage('fired', this.meshTraceCtx(), 'no_progress_monitor_final_summary');
2321
+ }
2322
+ this.pushEvent({
2323
+ event: 'agent:generating_completed',
2324
+ chatTitle,
2325
+ duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
2326
+ timestamp: me.timestamp,
2327
+ finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
2328
+ completionDiagnostic: {
2329
+ providerType: this.type,
2330
+ sessionId: this.instanceId,
2331
+ providerSessionId: this.providerSessionId || null,
2332
+ reconciliationReason: 'no_progress_monitor_final_summary',
2333
+ finalAssistantPresent: true,
2334
+ },
2335
+ });
2336
+ this.generatingStartedAt = 0;
2337
+ // Cancel any pending debounce flush — monitor already fired completion.
2338
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2339
+ this.completedDebouncePending = null;
2340
+ continue;
2341
+ }
981
2342
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
982
2343
  }
983
2344
  }
@@ -997,15 +2358,49 @@ export class CliProviderInstance implements ProviderInstance {
997
2358
  workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
998
2359
  ? event.workspaceName
999
2360
  : this.workingDir,
2361
+ // Carry the workspace under BOTH `workspace` and `workspaceName` so the
2362
+ // downstream mesh forward/merge path — which reads `workspace` — can
2363
+ // propagate it to the coordinator snapshot. Without `workspace` the live
2364
+ // event path delivers an empty workspace and the dashboard falls back to
2365
+ // the generic "Terminal (Mesh Node)" title.
2366
+ workspace: typeof event.workspace === 'string' && event.workspace.trim()
2367
+ ? event.workspace
2368
+ : this.workingDir,
1000
2369
  providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
1001
2370
  ? event.providerSessionId
1002
2371
  : this.providerSessionId,
1003
2372
  };
2373
+ // TASKIDLESS: stamp the mesh task primary key on lifecycle events emitted by
2374
+ // a mesh worker session. The consumer (updateDirectDispatchStatus) was switched
2375
+ // to key on task_id (CANON-B), but the producer never carried it — so every
2376
+ // forwarded metadataEvent.taskId arrived undefined and the coordinator fell back
2377
+ // to a session_id match, which can flip a sibling dispatch row. The session
2378
+ // already knows its own taskId via attachMeshAssignment (settings.meshActiveTaskId);
2379
+ // surface it here so updateDirectDispatchStatus hits the exact PK row and the
2380
+ // session_id fallback is never exercised. Non-mesh sessions get no taskId
2381
+ // (regression guard) — isMeshWorkerSession() gates the injection.
2382
+ if (this.isMeshWorkerSession() && this.settings.meshActiveTaskId) {
2383
+ const existingTaskId = typeof enrichedEvent.taskId === 'string' && enrichedEvent.taskId.trim()
2384
+ ? enrichedEvent.taskId
2385
+ : undefined;
2386
+ if (!existingTaskId) {
2387
+ enrichedEvent.taskId = this.settings.meshActiveTaskId;
2388
+ }
2389
+ }
1004
2390
  if (this.context?.emitProviderEvent) {
1005
2391
  this.context.emitProviderEvent(enrichedEvent);
1006
- return;
2392
+ } else {
2393
+ this.events.push(enrichedEvent);
2394
+ }
2395
+ // Auto-detach a direct-dispatch mesh assignment once the dispatched
2396
+ // task reaches a terminal state. Leaving meshNodeFor pinned would
2397
+ // route this session's next unrelated turn (a dashboard chat) into
2398
+ // the coordinator as if it were the completion of another task.
2399
+ // We schedule after the emit so the originating coordinator still
2400
+ // observes the completion event with its routing marker intact.
2401
+ if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
2402
+ try { this.detachMeshAssignment(); } catch { /* best-effort */ }
1007
2403
  }
1008
- this.events.push(enrichedEvent);
1009
2404
  }
1010
2405
 
1011
2406
  private flushEvents(): ProviderEvent[] {
@@ -1151,6 +2546,37 @@ export class CliProviderInstance implements ProviderInstance {
1151
2546
  return false;
1152
2547
  }
1153
2548
 
2549
+ /** @see ProviderInstance.noteManualInteraction */
2550
+ noteManualInteraction(now = Date.now()): void {
2551
+ this.manualAttendance.note(now);
2552
+ }
2553
+
2554
+ /**
2555
+ * Whether auto-approve should be treated as active *right now* for display
2556
+ * and firing decisions: the configured intent AND the user is not currently
2557
+ * attending this session by hand. When a human is attending, auto-approve is
2558
+ * held so the modal stays visible and they can drive it via the controlbar.
2559
+ * Provider-agnostic — the attendance signal is the command set, never any
2560
+ * CLI-specific modal text.
2561
+ */
2562
+ private autoApproveEffectivelyActive(status: string | undefined, now = Date.now()): boolean {
2563
+ return status === 'waiting_approval'
2564
+ && this.shouldAutoApprove()
2565
+ && !this.manualAttendance.isAttended(now);
2566
+ }
2567
+
2568
+ // STATUS-MISMATCH: true once the current auto-approve episode has been masking
2569
+ // waiting_approval behind `generating` for longer than AUTO_APPROVE_MASK_STALL_MS without
2570
+ // resolving (the settle gate never fired). When stalled, the surface mask must be dropped
2571
+ // so read_chat / mesh_status / the dashboard see the real waiting_approval + modal (and a
2572
+ // coordinator can mesh_approve it). autoApproveMaskSince is maintained by
2573
+ // maybeAutoApproveStatus (driven by getState + the recheck timer during a waiting episode);
2574
+ // this read is side-effect-free so getStatusMetadata can consult it too.
2575
+ private autoApproveMaskStalled(now = Date.now()): boolean {
2576
+ return this.autoApproveMaskSince > 0
2577
+ && now - this.autoApproveMaskSince > CliProviderInstance.AUTO_APPROVE_MASK_STALL_MS;
2578
+ }
2579
+
1154
2580
  private recordAutoApproval(modalMessage?: string, buttonLabel?: string, now = Date.now()): void {
1155
2581
  this.appendRuntimeSystemMessage(
1156
2582
  formatAutoApprovalMessage(modalMessage, buttonLabel),
@@ -1238,7 +2664,7 @@ export class CliProviderInstance implements ProviderInstance {
1238
2664
  receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
1239
2665
  historyDedupKey: dedupKey,
1240
2666
  }],
1241
- this.adapter.getScriptParsedStatus?.()?.title || this.workingDir.split('/').filter(Boolean).pop() || 'session',
2667
+ this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
1242
2668
  this.instanceId,
1243
2669
  this.providerSessionId,
1244
2670
  );
@@ -1258,12 +2684,28 @@ export class CliProviderInstance implements ProviderInstance {
1258
2684
  index,
1259
2685
  source: 'parsed',
1260
2686
  }));
2687
+ const getRole = (message: ChatMessage): string => typeof message.role === 'string'
2688
+ ? message.role.trim().toLowerCase()
2689
+ : '';
1261
2690
  const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
1262
2691
  message: entry.message,
1263
2692
  index: parsedMessages.length + index,
1264
- source: 'runtime',
2693
+ source: 'runtime' as const,
1265
2694
  runtimeKey: entry.key,
1266
- }));
2695
+ })).filter((entry) => {
2696
+ const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
2697
+ ? entry.message.meta as Record<string, unknown>
2698
+ : {};
2699
+ if (meta.runtimeInputAck !== true) return true;
2700
+ const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
2701
+ if (!runtimeText) return false;
2702
+ return !parsedEntries.some((parsedEntry) => {
2703
+ const parsedRole = getRole(parsedEntry.message);
2704
+ if (parsedRole !== 'user' && parsedRole !== 'human') return false;
2705
+ const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
2706
+ return parsedText === runtimeText;
2707
+ });
2708
+ });
1267
2709
  const getTime = (message: ChatMessage): number => {
1268
2710
  const value = typeof message.receivedAt === 'number'
1269
2711
  ? message.receivedAt
@@ -1273,9 +2715,6 @@ export class CliProviderInstance implements ProviderInstance {
1273
2715
  return Number.isFinite(value) && value > 0 ? value : 0;
1274
2716
  };
1275
2717
 
1276
- const getRole = (message: ChatMessage): string => typeof message.role === 'string'
1277
- ? message.role.trim().toLowerCase()
1278
- : '';
1279
2718
  const isRuntimeOverlay = (entry: MergeEntry): boolean => {
1280
2719
  if (entry.source !== 'runtime') return false;
1281
2720
  const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
@@ -1341,7 +2780,9 @@ export class CliProviderInstance implements ProviderInstance {
1341
2780
  this.providerSessionId = nextSessionId;
1342
2781
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
1343
2782
  this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
1344
- this.restorePersistedHistoryFromCurrentSession();
2783
+ if (this.shouldHydrateExistingProviderHistory()) {
2784
+ this.restorePersistedHistoryFromCurrentSession();
2785
+ }
1345
2786
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
1346
2787
  this.onProviderSessionResolved?.({
1347
2788
  instanceId: this.instanceId,
@@ -1354,13 +2795,39 @@ export class CliProviderInstance implements ProviderInstance {
1354
2795
  LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
1355
2796
  }
1356
2797
 
1357
- private syncCanonicalSavedHistoryIfNeeded(): boolean {
2798
+ private shouldHydrateExistingProviderHistory(): boolean {
2799
+ return this.launchMode === 'resume' || this.launchMode === 'manual';
2800
+ }
2801
+
2802
+ private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
2803
+ if (this.launchMode !== 'new') return false;
2804
+ if (this.providerSessionId) return false;
2805
+ if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
2806
+ if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
2807
+ if (parsedProviderSessionId) return true;
2808
+
2809
+ const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
2810
+
2811
+ // Untimestamped idle parser output during a fresh launch is usually the
2812
+ // provider's last workspace transcript before a new turn exists.
2813
+ return newestMessageAt === 0;
2814
+ }
2815
+
2816
+ private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
1358
2817
  if (!this.providerSessionId) return false;
1359
- const canonicalHistory = this.provider.canonicalHistory;
2818
+ const canonicalHistory = this.provider.nativeHistory;
1360
2819
  if (!canonicalHistory) return false;
1361
2820
 
2821
+ // Per-status-report hydration reads only a bounded tail (snapshot needs at
2822
+ // most the newest 60). The once-per-resume restore path passes full:true
2823
+ // because seedSessionHistory needs the COMPLETE transcript to seed dedup
2824
+ // state. The read-cache key encodes the window so the bounded and full
2825
+ // reads don't share/clobber each other's 2s cache entry.
2826
+ const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
2827
+ const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
2828
+
1362
2829
  if (isNativeSourceCanonicalHistory(canonicalHistory)) {
1363
- const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
2830
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
1364
2831
  const now = Date.now();
1365
2832
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1366
2833
  return true;
@@ -1373,7 +2840,7 @@ export class CliProviderInstance implements ProviderInstance {
1373
2840
  historySessionId: this.providerSessionId,
1374
2841
  workspace: this.workingDir,
1375
2842
  offset: 0,
1376
- limit: Number.MAX_SAFE_INTEGER,
2843
+ limit,
1377
2844
  historyBehavior: this.provider.historyBehavior,
1378
2845
  scripts: this.provider.scripts as any,
1379
2846
  });
@@ -1390,7 +2857,7 @@ export class CliProviderInstance implements ProviderInstance {
1390
2857
  }
1391
2858
 
1392
2859
  try {
1393
- const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
2860
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
1394
2861
  const now = Date.now();
1395
2862
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1396
2863
  return true;
@@ -1401,7 +2868,14 @@ export class CliProviderInstance implements ProviderInstance {
1401
2868
  if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
1402
2869
  return false;
1403
2870
  }
1404
- const restoredHistory = readChatHistory(this.type, 0, Number.MAX_SAFE_INTEGER, this.providerSessionId, 0, this.provider.historyBehavior);
2871
+ // Bounded by default: the per-status-report path only needs the newest
2872
+ // STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
2873
+ // activeChat.messages to the last 60 (status/normalize.ts) and loads
2874
+ // the rest lazily via read_chat on subscribe. The once-per-resume
2875
+ // restore path passes full:true so seedSessionHistory still sees the
2876
+ // COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
2877
+ // a bounded limit as an O(tail) read.
2878
+ const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
1405
2879
  this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
1406
2880
  role: message.role,
1407
2881
  content: message.content,
@@ -1417,10 +2891,13 @@ export class CliProviderInstance implements ProviderInstance {
1417
2891
 
1418
2892
  private restorePersistedHistoryFromCurrentSession(): void {
1419
2893
  if (!this.providerSessionId) return;
1420
- this.syncCanonicalSavedHistoryIfNeeded();
1421
- const restoredHistory = isNativeSourceCanonicalHistory(this.provider.canonicalHistory)
2894
+ // Restore is the once-per-resume seeding path: it needs the COMPLETE
2895
+ // transcript so seedSessionHistory can prime dedup state. Pass full so the
2896
+ // hydration read is unbounded here (and only here).
2897
+ this.syncCanonicalSavedHistoryIfNeeded({ full: true });
2898
+ const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
1422
2899
  ? readProviderChatHistory(this.type, {
1423
- canonicalHistory: this.provider.canonicalHistory,
2900
+ canonicalHistory: this.provider.nativeHistory,
1424
2901
  historySessionId: this.providerSessionId,
1425
2902
  workspace: this.workingDir,
1426
2903
  offset: 0,