@adhdev/daemon-core 0.9.82-rc.43 → 0.9.82-rc.431

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 (425) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -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 +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -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 +69 -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 +29 -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 +142 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +276 -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 +100 -1
  60. package/dist/config/mesh-json-config.d.ts +199 -0
  61. package/dist/config/repo-settings.d.ts +77 -0
  62. package/dist/daemon/dev-server.d.ts +0 -2
  63. package/dist/detection/ide-detector.d.ts +13 -0
  64. package/dist/detection/win32-ide-version.d.ts +37 -0
  65. package/dist/git/change-impact-config.d.ts +159 -0
  66. package/dist/git/git-commands.d.ts +11 -1
  67. package/dist/git/git-diff.d.ts +6 -0
  68. package/dist/git/git-executor.d.ts +11 -0
  69. package/dist/git/git-status.d.ts +57 -0
  70. package/dist/git/git-types.d.ts +2 -50
  71. package/dist/git/git-worktree.d.ts +71 -1
  72. package/dist/git/index.d.ts +3 -1
  73. package/dist/index.d.ts +64 -14
  74. package/dist/index.js +49391 -19228
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +48574 -18570
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/installer.d.ts +1 -4
  79. package/dist/ipc/local-ipc-server.d.ts +91 -0
  80. package/dist/launch.d.ts +1 -1
  81. package/dist/logging/async-batch-writer.d.ts +10 -0
  82. package/dist/logging/log-redactor.d.ts +24 -0
  83. package/dist/logging/log-tail-reader.d.ts +81 -0
  84. package/dist/logging/logger.d.ts +1 -1
  85. package/dist/mesh/contracts.d.ts +164 -0
  86. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  87. package/dist/mesh/coordinator-registry.d.ts +59 -0
  88. package/dist/mesh/mesh-active-work.d.ts +174 -0
  89. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  90. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  91. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  92. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  93. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  94. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  95. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  96. package/dist/mesh/mesh-events-pending.d.ts +69 -0
  97. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  98. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  99. package/dist/mesh/mesh-events.d.ts +6 -49
  100. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  101. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  102. package/dist/mesh/mesh-init.d.ts +86 -0
  103. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  104. package/dist/mesh/mesh-ledger.d.ts +77 -1
  105. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  106. package/dist/mesh/mesh-missions.d.ts +189 -0
  107. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  108. package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
  109. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  110. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  111. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  112. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  113. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  114. package/dist/mesh/mesh-routing.d.ts +70 -0
  115. package/dist/mesh/mesh-runtime-store.d.ts +450 -0
  116. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  117. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  118. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  119. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  120. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  121. package/dist/mesh/mesh-work-queue.d.ts +290 -5
  122. package/dist/mesh/preview-freshness.d.ts +18 -0
  123. package/dist/mesh/refine-config.d.ts +216 -0
  124. package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
  125. package/dist/providers/acp-provider-instance.d.ts +5 -0
  126. package/dist/providers/approval-utils.d.ts +20 -0
  127. package/dist/providers/chat-message-normalization.d.ts +31 -1
  128. package/dist/providers/cli-provider-instance.d.ts +221 -3
  129. package/dist/providers/contracts.d.ts +139 -6
  130. package/dist/providers/external-sources.d.ts +71 -0
  131. package/dist/providers/manual-attendance.d.ts +63 -0
  132. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  133. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  134. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  135. package/dist/providers/native-history/constants.d.ts +12 -0
  136. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  137. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  138. package/dist/providers/native-history/index.d.ts +13 -0
  139. package/dist/providers/provider-instance-manager.d.ts +29 -0
  140. package/dist/providers/provider-instance.d.ts +23 -1
  141. package/dist/providers/provider-loader.d.ts +26 -4
  142. package/dist/providers/provider-trust.d.ts +31 -0
  143. package/dist/providers/read-chat-contract.d.ts +29 -0
  144. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  145. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  146. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  147. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  148. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  149. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  150. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  151. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  152. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  153. package/dist/providers/sdk/v1/index.d.ts +30 -0
  154. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  155. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  156. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  157. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  158. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  159. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  160. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  161. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  162. package/dist/providers/spec/adapter.d.ts +91 -0
  163. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  164. package/dist/providers/spec/evaluator.d.ts +45 -0
  165. package/dist/providers/spec/fsm-driver.d.ts +422 -0
  166. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  167. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  168. package/dist/providers/spec/fsm-types.d.ts +174 -0
  169. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  170. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  171. package/dist/providers/spec/route.d.ts +4 -0
  172. package/dist/providers/spec/types.d.ts +222 -0
  173. package/dist/providers/status-monitor.d.ts +7 -7
  174. package/dist/providers/transcript-v2.d.ts +176 -0
  175. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  176. package/dist/providers/working-dir.d.ts +17 -0
  177. package/dist/repo-mesh-types.d.ts +501 -13
  178. package/dist/runtime-defaults.d.ts +2 -0
  179. package/dist/sessions/registry.d.ts +6 -0
  180. package/dist/shared-types-extra.d.ts +2 -4
  181. package/dist/shared-types.d.ts +59 -2
  182. package/dist/status/normalize.d.ts +1 -1
  183. package/dist/status/normalize.js +1 -0
  184. package/dist/status/normalize.js.map +1 -1
  185. package/dist/status/normalize.mjs +1 -0
  186. package/dist/status/normalize.mjs.map +1 -1
  187. package/dist/status/reporter.d.ts +2 -0
  188. package/dist/status/snapshot.d.ts +26 -0
  189. package/dist/system/hash.d.ts +8 -0
  190. package/dist/system/load-better-sqlite3.d.ts +21 -0
  191. package/dist/types.d.ts +5 -0
  192. package/package.json +7 -3
  193. package/src/agent-stream/poller.ts +2 -3
  194. package/src/agent-stream/provider-adapter.ts +1 -1
  195. package/src/boot/daemon-lifecycle.ts +63 -12
  196. package/src/boot/process-hardening.ts +89 -0
  197. package/src/build-info.ts +73 -0
  198. package/src/chat/source-machine.ts +534 -0
  199. package/src/chat/source-resolver.ts +0 -0
  200. package/src/chat/subscription-updates.ts +20 -1
  201. package/src/cli-adapter-types.d.ts +3 -1
  202. package/src/cli-adapter-types.ts +68 -2
  203. package/src/cli-adapters/cli-script-runner.ts +421 -0
  204. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  205. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  206. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  207. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  208. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  209. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  210. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  211. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  212. package/src/cli-adapters/pty-transport.ts +2 -1
  213. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  214. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  215. package/src/cli-adapters/resolve-executable.ts +204 -0
  216. package/src/cli-adapters/session-host-transport.ts +2 -1
  217. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  218. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  219. package/src/cli-adapters/terminal-screen.ts +16 -81
  220. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  221. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  222. package/src/commands/chat-commands-read.ts +2327 -0
  223. package/src/commands/chat-commands-scope.ts +54 -0
  224. package/src/commands/chat-commands-shared.ts +114 -0
  225. package/src/commands/chat-commands-write.ts +891 -0
  226. package/src/commands/chat-commands.ts +19 -1841
  227. package/src/commands/cli-manager.ts +544 -26
  228. package/src/commands/handler.ts +841 -2
  229. package/src/commands/high-family/index.ts +28 -0
  230. package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
  231. package/src/commands/high-family/mesh-events.ts +80 -0
  232. package/src/commands/high-family/mesh-status.ts +710 -0
  233. package/src/commands/high-family/types.ts +76 -0
  234. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  235. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  236. package/src/commands/low-family/diagnostics.ts +57 -0
  237. package/src/commands/low-family/index.ts +37 -0
  238. package/src/commands/low-family/mesh-ledger.ts +62 -0
  239. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  240. package/src/commands/low-family/notification.ts +116 -0
  241. package/src/commands/low-family/refine-config.ts +106 -0
  242. package/src/commands/low-family/session-host.ts +274 -0
  243. package/src/commands/low-family/spec-providerdev.ts +217 -0
  244. package/src/commands/low-family/status-meta.ts +112 -0
  245. package/src/commands/low-family/types.ts +39 -0
  246. package/src/commands/med-family/cli-agent.ts +238 -0
  247. package/src/commands/med-family/fast-forward.ts +230 -0
  248. package/src/commands/med-family/ide.ts +163 -0
  249. package/src/commands/med-family/index.ts +37 -0
  250. package/src/commands/med-family/mesh-crud.ts +1066 -0
  251. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  252. package/src/commands/med-family/mesh-queue.ts +167 -0
  253. package/src/commands/med-family/mesh-restart.ts +92 -0
  254. package/src/commands/med-family/types.ts +143 -0
  255. package/src/commands/mesh-coordinator.ts +334 -124
  256. package/src/commands/router.ts +2711 -3254
  257. package/src/commands/stream-commands.ts +8 -0
  258. package/src/commands/upgrade-helper.ts +310 -45
  259. package/src/config/chat-history.ts +483 -24
  260. package/src/config/config.ts +12 -0
  261. package/src/config/mesh-config.ts +495 -22
  262. package/src/config/mesh-json-config.ts +376 -0
  263. package/src/config/recent-activity.ts +8 -2
  264. package/src/config/repo-settings.ts +111 -0
  265. package/src/daemon/dev-auto-implement.ts +3 -2
  266. package/src/daemon/dev-cli-debug.ts +10 -1
  267. package/src/daemon/dev-server.ts +0 -541
  268. package/src/detection/cli-detector.ts +28 -9
  269. package/src/detection/ide-detector.ts +55 -16
  270. package/src/detection/win32-ide-version.ts +106 -0
  271. package/src/git/change-impact-config.ts +354 -0
  272. package/src/git/git-commands.ts +59 -15
  273. package/src/git/git-diff.ts +81 -11
  274. package/src/git/git-executor.ts +12 -0
  275. package/src/git/git-status.ts +767 -48
  276. package/src/git/git-types.ts +14 -62
  277. package/src/git/git-worktree.ts +261 -4
  278. package/src/git/index.ts +17 -0
  279. package/src/index.ts +194 -12
  280. package/src/installer.d.ts +1 -1
  281. package/src/installer.ts +8 -6
  282. package/src/ipc/local-ipc-server.ts +278 -0
  283. package/src/launch.d.ts +1 -1
  284. package/src/launch.ts +37 -28
  285. package/src/logging/async-batch-writer.ts +55 -0
  286. package/src/logging/command-log.ts +7 -5
  287. package/src/logging/log-redactor.ts +100 -0
  288. package/src/logging/log-tail-reader.ts +341 -0
  289. package/src/logging/logger.ts +14 -7
  290. package/src/mesh/contracts.ts +338 -0
  291. package/src/mesh/coordinator-prompt.ts +381 -33
  292. package/src/mesh/coordinator-registry.ts +121 -0
  293. package/src/mesh/mesh-active-work.ts +645 -0
  294. package/src/mesh/mesh-clone-grace.ts +68 -0
  295. package/src/mesh/mesh-coordinator-config.ts +97 -0
  296. package/src/mesh/mesh-delivery-policy.ts +315 -0
  297. package/src/mesh/mesh-event-classify.ts +51 -0
  298. package/src/mesh/mesh-event-forwarding.ts +1888 -0
  299. package/src/mesh/mesh-event-trace.ts +67 -0
  300. package/src/mesh/mesh-events-coordinator.ts +32 -0
  301. package/src/mesh/mesh-events-pending.ts +656 -0
  302. package/src/mesh/mesh-events-stale.ts +389 -0
  303. package/src/mesh/mesh-events-utils.ts +443 -0
  304. package/src/mesh/mesh-events.ts +33 -1035
  305. package/src/mesh/mesh-fast-forward.ts +843 -0
  306. package/src/mesh/mesh-host-ownership.ts +73 -0
  307. package/src/mesh/mesh-init.ts +260 -0
  308. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  309. package/src/mesh/mesh-ledger.ts +656 -102
  310. package/src/mesh/mesh-magi-status.ts +223 -0
  311. package/src/mesh/mesh-missions.ts +449 -0
  312. package/src/mesh/mesh-node-identity.ts +1887 -0
  313. package/src/mesh/mesh-queue-assignment.ts +1918 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1780 -0
  315. package/src/mesh/mesh-refine-batch.ts +205 -0
  316. package/src/mesh/mesh-refine-gates.ts +1673 -0
  317. package/src/mesh/mesh-refine-status.ts +231 -0
  318. package/src/mesh/mesh-review-inbox.ts +307 -0
  319. package/src/mesh/mesh-routing.ts +291 -0
  320. package/src/mesh/mesh-runtime-store.ts +1853 -0
  321. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  322. package/src/mesh/mesh-task-inflight.ts +70 -0
  323. package/src/mesh/mesh-task-stats.ts +161 -0
  324. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  325. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  326. package/src/mesh/mesh-work-queue.ts +1243 -141
  327. package/src/mesh/preview-freshness.ts +118 -0
  328. package/src/mesh/refine-config.ts +423 -0
  329. package/src/mesh/worktree-bootstrap-config.ts +450 -0
  330. package/src/providers/acp-provider-instance.ts +43 -10
  331. package/src/providers/approval-utils.d.ts +5 -0
  332. package/src/providers/approval-utils.ts +57 -5
  333. package/src/providers/chat-message-normalization.ts +92 -4
  334. package/src/providers/cli-provider-instance.ts +1933 -104
  335. package/src/providers/contracts.d.ts +55 -0
  336. package/src/providers/contracts.ts +150 -6
  337. package/src/providers/extension-provider-instance.ts +12 -7
  338. package/src/providers/external-sources.ts +218 -0
  339. package/src/providers/ide-provider-instance.ts +35 -12
  340. package/src/providers/manual-attendance.ts +85 -0
  341. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  342. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  343. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  344. package/src/providers/native-history/constants.ts +19 -0
  345. package/src/providers/native-history/dispatcher.ts +339 -0
  346. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  347. package/src/providers/native-history/index.ts +30 -0
  348. package/src/providers/provider-instance-manager.ts +71 -0
  349. package/src/providers/provider-instance.ts +19 -1
  350. package/src/providers/provider-loader.ts +668 -50
  351. package/src/providers/provider-schema.ts +87 -14
  352. package/src/providers/provider-trust.ts +114 -0
  353. package/src/providers/read-chat-contract.ts +76 -16
  354. package/src/providers/sdk/README.md +49 -0
  355. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  356. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  357. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  358. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  359. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  360. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  361. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  362. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  363. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  364. package/src/providers/sdk/v1/index.ts +152 -0
  365. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  366. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  367. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  368. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  369. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  370. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  375. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  376. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  377. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  378. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  379. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  380. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  381. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  382. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  383. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  384. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  385. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  386. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  387. package/src/providers/sdk/v1/validators/index.ts +19 -0
  388. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  389. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  390. package/src/providers/spec/adapter.ts +235 -0
  391. package/src/providers/spec/cli-adapter.ts +1056 -0
  392. package/src/providers/spec/evaluator.ts +407 -0
  393. package/src/providers/spec/fsm-driver.ts +1410 -0
  394. package/src/providers/spec/fsm-evaluator.ts +272 -0
  395. package/src/providers/spec/fsm-loader.ts +120 -0
  396. package/src/providers/spec/fsm-types.ts +273 -0
  397. package/src/providers/spec/native-history-executor.ts +1128 -0
  398. package/src/providers/spec/pre-launch-trust.ts +104 -0
  399. package/src/providers/spec/route.ts +51 -0
  400. package/src/providers/spec/types.ts +262 -0
  401. package/src/providers/status-monitor.d.ts +7 -7
  402. package/src/providers/status-monitor.ts +37 -22
  403. package/src/providers/transcript-v2.ts +567 -0
  404. package/src/providers/types/interactive-prompt.ts +536 -0
  405. package/src/providers/version-archive.ts +64 -24
  406. package/src/providers/working-dir.ts +23 -0
  407. package/src/repo-mesh-types.ts +740 -14
  408. package/src/runtime-defaults.ts +39 -0
  409. package/src/sessions/registry.ts +6 -0
  410. package/src/shared-types-extra.ts +2 -4
  411. package/src/shared-types.d.ts +8 -0
  412. package/src/shared-types.ts +64 -1
  413. package/src/status/builders.ts +26 -6
  414. package/src/status/normalize.ts +2 -0
  415. package/src/status/reporter.ts +19 -1
  416. package/src/status/snapshot.ts +95 -26
  417. package/src/system/hash.ts +23 -0
  418. package/src/system/host-memory.ts +29 -12
  419. package/src/system/load-better-sqlite3.ts +68 -0
  420. package/src/types.ts +5 -0
  421. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  422. package/dist/mesh/mesh-sync.d.ts +0 -53
  423. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  424. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  425. 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
- import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
32
+ import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages, extractFinalSummaryFromMessagesAfter } 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,136 @@ 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
+ // ARCH-REFACTOR R1: the taskId of the turn that produced this (debounced) completion,
66
+ // captured SYNCHRONOUSLY at the generating→idle transition. The actual completion
67
+ // event is emitted later by the debounce flush, by which point a follow-up task may
68
+ // already have started its own turn and overwritten engine.currentTurnTaskId — so the
69
+ // id must be snapshotted here, not re-read at flush time.
70
+ taskId?: string;
71
+ // NOTIF Defect-B: the wall-clock start of the turn that produced this (debounced)
72
+ // completion, snapshotted SYNCHRONOUSLY at the generating→idle transition (same
73
+ // reason as taskId — a follow-up turn moves engine.currentTurnStartedAt). The
74
+ // completion's finalSummary is turn-scoped to bubbles at/after this instant so a
75
+ // debounce that flushes before the producing turn's final assistant bubble lands
76
+ // in the native transcript never echoes the PRIOR task's last bubble.
77
+ turnStartedAt?: number;
78
+ };
79
+
80
+ function isIdleStatus(value: unknown): boolean {
81
+ const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
82
+ return !status || status === 'idle' || status === 'ready';
83
+ }
84
+
85
+
86
+ function getMessageTime(message: unknown): number {
87
+ if (!message || typeof message !== 'object') return 0;
88
+ const record = message as { receivedAt?: unknown; timestamp?: unknown };
89
+ const value = Number(record.receivedAt ?? record.timestamp ?? 0);
90
+ return Number.isFinite(value) ? value : 0;
91
+ }
92
+
93
+ type CompletedFinalizationBlock = {
94
+ reason: string;
95
+ terminal?: boolean;
96
+ allowTimeout?: boolean;
97
+ // (SETTLE-VALLEY) When set, suppress the CANON-C decoupled-immediate emit for this
98
+ // missing_final_assistant block and HOLD (retry up to COMPLETED_FINALIZATION_MAX_WAIT_MS)
99
+ // until the native transcript's final assistant turn arrives (block clears → genuine emit)
100
+ // or the worker resumes (resume guard cancels). Set only for the inter-approval idle valley
101
+ // of a native-history mesh worker, where an immediate weak emit would freeze a truncated
102
+ // preamble summary (evidenceLevel=insufficient) into the append-only ledger before the
103
+ // worker's next approval turn resumes. Independent of valley length.
104
+ holdForTranscript?: boolean;
105
+ };
106
+
107
+ type CompletionFinalAssistantEvidence = {
108
+ present: boolean;
109
+ messages: unknown[];
110
+ source: 'parsed' | 'external-native' | 'unavailable';
111
+ };
112
+
113
+ type ExternalTranscriptProbe = {
114
+ readAt: number;
115
+ msgCount: number;
116
+ lastRole: string | null;
117
+ lastKind: string | null;
118
+ contentLen: number;
119
+ sourcePath: string | null;
120
+ sourceMtimeMs: number | null;
121
+ mtimeAgeMs: number | null;
44
122
  };
45
123
 
46
124
  const COMPLETED_FINALIZATION_RETRY_MS = 1000;
47
125
  const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
126
+ // (FALSEIDLE-BGCHILD-a) Minimum generating→idle settle window for native-history mesh worker
127
+ // sessions. Native-history providers (e.g. claude-cli) normally flush the completion with
128
+ // flushDelay=0 — the transcript is authoritative, so there is no reason to wait. But a worker
129
+ // turn that spawns a BACKGROUND child (e.g. `npm test &`, a backgrounded Bash tool) can paint
130
+ // a burst of child output, fall quiet, and have the screen parser read a PRIOR/intermediate
131
+ // standard assistant as if the turn were done — firing a false idle while the agent is in fact
132
+ // still generating (e.g. mid-commit). With flushDelay=0 there is no window for the resume guard
133
+ // in flushCompletedDebounceIfFinalized (latestVisibleStatus !== 'idle' → cancel) to observe the
134
+ // agent picking the turn back up. A short non-zero settle window restores that resume guard for
135
+ // mesh workers without delaying genuinely-finished turns beyond this bound. Scoped to mesh
136
+ // worker sessions so interactive native-history sessions keep the immediate flush.
137
+ // 4000ms (was 1500): live measurement showed the completion event can fire 1.6–3s
138
+ // BEFORE the worker's final-assistant turn lands in the transcript on a natural
139
+ // generating→idle completion (no approval modal), freezing a prior intermediate
140
+ // bubble as finalSummary (evidenceLevel=insufficient). The 68a3c324 waiting_approval
141
+ // hold only covers the approval-resolved valley; widening this settle window to 4000ms
142
+ // covers that race AND the ~3s waiting_approval valley within the settle bound.
143
+ const NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4000;
144
+ // TASKBUBBLE-DUP: window during which an identical user-input ack (same trimmed
145
+ // content on the same instance) is treated as a redelivery of one dispatch and
146
+ // suppressed from the chat transcript. Matches the coordinator-side
147
+ // DUPLICATE_DISPATCH_WINDOW_MS (mesh-tools) so the daemon's bubble-level guard
148
+ // covers the same retry horizon as the MCP-level dispatch dedup.
149
+ const USER_INPUT_ACK_DEDUP_WINDOW_MS = 60_000;
150
+ // GENERATING-BOUNDARY (R4c): window — measured from the startup-grace COLLAPSE moment
151
+ // (startupGraceCollapseAt), not boot — inside which a "first turn that ran+completed
152
+ // without the FSM ever observing a 'generating' frame" is attributed to the startup-grace
153
+ // collapse and synthesized (reason 'startup_grace_idle_turn_collapse').
154
+ // The spec's startup-grace exit is elapsed_ms=8000, so the FSM spends ~8s in 'starting'
155
+ // before collapsing to idle; a turn can be dispatched a few seconds AFTER that collapse
156
+ // (the live R4b miss: collapse at boot+8s, dispatch at boot+12.4s — already past a 12s
157
+ // boot-anchored window before the turn even started). Anchoring on the collapse moment
158
+ // covers dispatch-delay; R4d additionally anchors on the turn-START moment
159
+ // (engine.currentTurnStartedAt) so a non-trivial turn-DURATION cannot push the completion
160
+ // past a now-anchored window (the live rc.405 Probe2 miss). The strong discriminator is
161
+ // generatingStartedAt===0 (generating was never observed) AND a started-but-finished turn
162
+ // — the window only keeps the synthesized reason honest and scopes the synthesis to the
163
+ // boot collapse, so a much-later unobservably-fast turn is not mislabelled a startup collapse.
164
+ const STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS = 12_000;
165
+
166
+ /** Events that signal a dispatched mesh task has reached a terminal state.
167
+ * Detach the mesh assignment after emitting one of these so the worker's
168
+ * next unrelated turn doesn't impersonate another completion. */
169
+ const TERMINAL_MESH_EVENTS = new Set([
170
+ 'agent:generating_completed',
171
+ 'agent:stopped',
172
+ 'agent:ready',
173
+ ]);
48
174
 
49
175
  const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
50
176
  'image/png': '.png',
@@ -120,7 +246,29 @@ function hasNonEmptyCliModalButtons(activeModal: unknown): boolean {
120
246
  }
121
247
 
122
248
  function isCliGeneratingLikeStatus(status: unknown): boolean {
123
- return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
249
+ return status === 'generating' || status === 'streaming' || status === 'no_progress' || status === 'long_generating' || status === 'starting';
250
+ }
251
+
252
+ /**
253
+ * NOTIF Defect-2a: the REPORTED short-generating duration, anchored on the IMMUTABLE turn
254
+ * start. generatingStartedAt is reset to 0 on every mid-turn waiting_approval/idle blip and
255
+ * re-armed on the next →generating, so a long turn that blips would otherwise measure only the
256
+ * final 1.5-2.5s sliver. engine.currentTurnStartedAt (set once at onTurnStarted, surviving
257
+ * mid-turn blips until the next turn starts) is preferred; generatingStartedAt is the fallback
258
+ * for turns that never recorded an engine turn start. Returns 0 when neither anchor is set.
259
+ * Pure / unit-testable.
260
+ */
261
+ export function computeTurnAnchoredDurationMs(
262
+ engineTurnStartedAt: number | undefined,
263
+ generatingStartedAt: number,
264
+ now: number,
265
+ ): { durationMs: number; anchor: 'turn-start' | 'generatingStartedAt' | 'none' } {
266
+ const engineStart = typeof engineTurnStartedAt === 'number' && Number.isFinite(engineTurnStartedAt)
267
+ ? engineTurnStartedAt
268
+ : 0;
269
+ if (engineStart > 0) return { durationMs: now - engineStart, anchor: 'turn-start' };
270
+ if (generatingStartedAt > 0) return { durationMs: now - generatingStartedAt, anchor: 'generatingStartedAt' };
271
+ return { durationMs: 0, anchor: 'none' };
124
272
  }
125
273
 
126
274
  export function buildCliStructuredInputPrompt(
@@ -300,24 +448,131 @@ export class CliProviderInstance implements ProviderInstance {
300
448
  readonly type: string;
301
449
  readonly category = 'cli' as const;
302
450
 
451
+ /**
452
+ * Quiet period an approval modal's signature must be stable before
453
+ * auto-approve sends the approve key. Guards against firing on a prompt
454
+ * that is still streaming into the PTY (the "resolves too fast" symptom):
455
+ * while the modal text/buttons are still changing, every frame yields a
456
+ * new signature and the settle clock restarts. Once the prompt finishes
457
+ * rendering the signature holds and the key is sent after this window.
458
+ * Bounded + small so genuine approvals stay timely. The FSM is already
459
+ * authoritative over the `waiting_approval` state; this only delays the
460
+ * keystroke until the modal *content* has settled.
461
+ */
462
+ private static readonly AUTO_APPROVE_SETTLE_MS = 600;
463
+
464
+ /**
465
+ * Busy-side hysteresis for the settle gate. A momentary `generating` flip
466
+ * while the SAME approval modal's button block is still on screen (its
467
+ * question line scrolled out of the captured frame, only the buttons + a
468
+ * residual `esc to interrupt` spinner remain) briefly reports
469
+ * status!=waiting_approval. Without hysteresis that flip wipes the settle
470
+ * clock, and the modal→generating→modal flap restarts the 600ms window
471
+ * every time so auto-approve never fires. We keep the in-progress settle
472
+ * gate warm across an inactive blip up to this bound; only once the modal
473
+ * has genuinely stayed gone this long (a real resolution → idle) is the
474
+ * gate cleared. Bounded so a genuinely new, later approval still re-settles
475
+ * from scratch rather than firing on a stale timestamp.
476
+ */
477
+ private static readonly AUTO_APPROVE_GATE_HYSTERESIS_MS = 1500;
478
+
479
+ /**
480
+ * STATUS-MISMATCH: upper bound on how long the auto-approve→`generating` SURFACE
481
+ * mask may hide a worker's `waiting_approval` (status + activeModal) before we give
482
+ * up and surface the real prompt. The mask exists because auto-approve is expected
483
+ * to resolve the modal momentarily; but if it STALLS without ever calling
484
+ * resolveModal — the modal signature never settles for AUTO_APPROVE_SETTLE_MS (a
485
+ * perpetually-flapping/streaming prompt), no concrete modal is ever captured, or the
486
+ * modal is a picker/non-affirmative we never auto-pick — the mask would persist
487
+ * forever and read_chat / mesh_status / the dashboard would NEVER see the pending
488
+ * approval (the coordinator cannot mesh_approve what it cannot see). Once an episode
489
+ * exceeds this bound we stop masking. Generously larger than
490
+ * AUTO_APPROVE_SETTLE_MS (600) + AUTO_APPROVE_GATE_HYSTERESIS_MS (1500) so a
491
+ * legitimately slow-settling / blip-flapping prompt is never unmasked early; a
492
+ * genuine never-resolving stall surfaces within this window. The settle gate keeps
493
+ * running underneath, so a prompt that finally stabilises still auto-approves, and
494
+ * mesh_approve (raw FSM, unmasked) works throughout.
495
+ */
496
+ private static readonly AUTO_APPROVE_MASK_STALL_MS = 4500;
497
+
303
498
  private adapter: ProviderCliAdapter;
304
499
  private context: InstanceContext | null = null;
305
500
  private events: ProviderEvent[] = [];
306
501
  private lastStatus: string = 'starting';
502
+ // Idempotency guard for the queue-claim agent:ready event. agent:ready is the
503
+ // sole signal the mesh coordinator's tryAssignQueueTask waits on to hand a
504
+ // queued task to this worker. It is emitted in two places: the boot-time
505
+ // starting→idle one-shot, and the readySeen re-arm below. This flag makes the
506
+ // event fire AT MOST ONCE per session so a worker is never claimed twice and a
507
+ // queued task is never double-dispatched/double-injected. Whichever path fires
508
+ // first sets it; the other becomes a no-op.
509
+ private agentReadyEmitted = false;
307
510
  private generatingStartedAt: number = 0;
511
+ // GENERATING-BOUNDARY (R4b): the per-turn taskId for which a startup-grace
512
+ // started+completed pair was already synthesized. Both fast-collapse callers
513
+ // (starting→idle transition AND the idle-stayed no-status-change poll) route
514
+ // through maybeSynthesizeStartupGraceCollapse; the idle-stayed caller re-polls
515
+ // steadily while the session sits idle, so this guard makes the synthesis fire
516
+ // AT MOST ONCE per collapsed turn.
517
+ private fastCollapseSynthesizedTaskId: string | null = null;
518
+ // GENERATING-BOUNDARY (R4c): the wall-clock moment the FSM's starting→idle
519
+ // startup-grace collapse was observed (set ONCE, on the first starting→idle
520
+ // transition this boot). The idle-stayed collapse window is anchored on THIS,
521
+ // not on instance/boot time (this.startedAt): the FSM spends the full 8s
522
+ // startup-grace sitting in 'starting' before collapsing, and a turn can be
523
+ // dispatched a few seconds AFTER the collapse — measuring the window from boot
524
+ // would have it already closed by the time that turn lands+completes (the live
525
+ // R4b miss: collapse at boot+8s, dispatch at boot+12.4s > the 12s boot window).
526
+ // Anchoring on the collapse moment makes the window cover dispatch-delay+turn.
527
+ private startupGraceCollapseAt: number | null = null;
308
528
  private settings: Record<string, any> = {};
309
529
  private monitor: StatusMonitor;
310
530
  private generatingDebounceTimer: NodeJS.Timeout | null = null;
311
531
  private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
312
- private lastApprovalEventAt = 0;
532
+ private lastApprovalEventFingerprint = '';
313
533
  private autoApproveBusy = false;
314
534
  private autoApproveBusyTimer: NodeJS.Timeout | null = null;
535
+ private lastAutoApprovalSignature = '';
536
+ // Settle gate: the approval modal's signature + the wall-clock when this
537
+ // exact signature was first observed. Auto-approve only fires once the
538
+ // SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
539
+ // still streaming into the PTY (its buttons/message changing frame to
540
+ // frame) keeps resetting the timer and is never approved half-rendered.
541
+ private pendingAutoApprovalSignature = '';
542
+ private pendingAutoApprovalSince = 0;
543
+ private autoApproveSettleTimer: NodeJS.Timeout | null = null;
544
+ // Wall-clock when auto-approve first observed status!=waiting_approval while
545
+ // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS so a
546
+ // brief generating flip does not immediately wipe the settle clock.
547
+ private autoApproveInactiveSince = 0;
548
+ // STATUS-MISMATCH: wall-clock when the CURRENT auto-approve episode (waiting_approval
549
+ // + shouldAutoApprove) first began wanting to mask. Unlike pendingAutoApprovalSince it
550
+ // is NOT reset when the modal signature changes (a still-streaming/flapping prompt) and
551
+ // survives the same hysteresis blips the settle gate does, so it measures the TRUE age
552
+ // of an unresolved auto-approve. Once it exceeds AUTO_APPROVE_MASK_STALL_MS the surface
553
+ // mask is dropped so the real waiting_approval surfaces. Cleared when the episode ends
554
+ // (modal genuinely gone, manual attendance takes over, or auto-approve fires).
555
+ private autoApproveMaskSince = 0;
556
+ // Provider-common manual-attendance signal: while a human is actively driving
557
+ // this session from the dashboard, auto-approve holds so they can take manual
558
+ // control. Background mesh workers are never attended → delegated auto-approve
559
+ // is unaffected.
560
+ private readonly manualAttendance = new ManualAttendanceTracker();
315
561
  private controlValues: Record<string, string | number | boolean> = {};
316
562
  private summaryMetadata: unknown = undefined;
317
563
  private appliedEffectKeys = new Set<string>();
318
564
  private historyWriter: ChatHistoryWriter;
319
565
  private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
320
566
  private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
567
+ private lastAcknowledgedUserInputAt = 0;
568
+ // TASKBUBBLE-DUP: per-content last-ack timestamps so the same dispatched
569
+ // prompt acked twice in quick succession (the worker buffers the first
570
+ // send during bootstrap/busy, then a redelivery — dispatch-confirm-timeout
571
+ // requeue or a reconcile re-dispatch — fires a SECOND send_chat before the
572
+ // outbound queue drains) collapses to ONE user bubble. Keyed on the trimmed
573
+ // content; an entry older than USER_INPUT_ACK_DEDUP_WINDOW_MS is treated as
574
+ // a fresh, intentional resend and is NOT suppressed.
575
+ private recentUserInputAcks = new Map<string, number>();
321
576
  private lastNativeSourceCanonicalCheckAt = 0;
322
577
  private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
323
578
  private cachedSqliteDb: {
@@ -330,6 +585,7 @@ export class CliProviderInstance implements ProviderInstance {
330
585
  private suppressIdleHistoryReplay = false;
331
586
  private errorMessage: string | undefined = undefined;
332
587
  private errorReason: ProviderErrorReason | undefined = undefined;
588
+ private activeInteractivePrompt: InteractivePrompt | null = null;
333
589
 
334
590
  private presentationMode: 'terminal' | 'chat';
335
591
  private providerSessionId?: string;
@@ -370,7 +626,10 @@ export class CliProviderInstance implements ProviderInstance {
370
626
  this.providerSessionId = options?.providerSessionId;
371
627
  this.launchMode = options?.launchMode || 'new';
372
628
  this.onProviderSessionResolved = options?.onProviderSessionResolved;
373
- this.adapter = new ProviderCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory);
629
+ this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
630
+ if (this.providerSessionId) {
631
+ this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
632
+ }
374
633
  this.monitor = new StatusMonitor();
375
634
  this.historyWriter = new ChatHistoryWriter();
376
635
  }
@@ -389,8 +648,8 @@ export class CliProviderInstance implements ProviderInstance {
389
648
  this.adapter.updateRuntimeSettings?.(this.settings);
390
649
  this.monitor.updateConfig({
391
650
  approvalAlert: this.settings.approvalAlert !== false,
392
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
393
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
651
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
652
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
394
653
  });
395
654
 
396
655
  // Server connection
@@ -412,7 +671,7 @@ export class CliProviderInstance implements ProviderInstance {
412
671
  await this.adapter.spawn();
413
672
  await this.enforceFreshSessionLaunchIfNeeded();
414
673
  this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
415
- if (this.providerSessionId) {
674
+ if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
416
675
  this.restorePersistedHistoryFromCurrentSession();
417
676
  }
418
677
  if (this.providerSessionId && this.launchMode === 'resume') {
@@ -486,14 +745,38 @@ export class CliProviderInstance implements ProviderInstance {
486
745
  }
487
746
 
488
747
  getState(): ProviderState {
748
+ // TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
749
+ // parseSession) are currently invoked by CliScriptRunner.invoke() via direct
750
+ // function calls — the scripts run in the daemon process with full Node.js
751
+ // access and no resource limits.
752
+ //
753
+ // When Phase 5 lands, CliScriptRunner should route these calls through a
754
+ // SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
755
+ // that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
756
+ // a 32 MB memory cap. The execution path to change is:
757
+ // CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
758
+ //
759
+ // This getState() call-site is NOT where the change goes — the wiring belongs
760
+ // in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
761
+ // parseSession), with provider-loader.ts updated to store script source strings
762
+ // alongside the loaded function references for extended-legacy providers.
489
763
  const adapterStatus = this.adapter.getStatus();
764
+ if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
765
+ this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
766
+ }
490
767
  let parsedStatus: any = null;
491
768
  let parseErrorMessage: string | undefined;
492
769
  if (typeof this.adapter.getScriptParsedStatus === 'function') {
493
770
  try {
494
771
  parsedStatus = this.adapter.getScriptParsedStatus() || null;
495
- this.errorMessage = undefined;
496
- this.errorReason = undefined;
772
+ const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
773
+ ? parsedStatus.errorMessage.trim()
774
+ : undefined;
775
+ const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
776
+ ? parsedStatus.errorReason.trim() as ProviderErrorReason
777
+ : undefined;
778
+ this.errorMessage = parsedErrorMessage;
779
+ this.errorReason = parsedErrorReason;
497
780
  } catch (error: any) {
498
781
  parseErrorMessage = error?.message || String(error);
499
782
  this.errorMessage = parseErrorMessage;
@@ -503,22 +786,59 @@ export class CliProviderInstance implements ProviderInstance {
503
786
  this.errorMessage = undefined;
504
787
  this.errorReason = undefined;
505
788
  }
506
- const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
507
- const visibleStatus = parseErrorMessage
508
- ? 'error'
509
- : (autoApproveActive ? 'generating' : adapterStatus.status);
510
- const parsedProviderSessionId = normalizeProviderSessionId(
789
+ const adapterProviderSessionId = normalizeProviderSessionId(
511
790
  this.provider,
512
- typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
791
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
513
792
  );
514
- if (parsedProviderSessionId) {
515
- this.promoteProviderSessionId(parsedProviderSessionId);
793
+ const nowMs = Date.now();
794
+ // STATUS-MISMATCH: maybeAutoApproveStatus still runs for its side effects (settle gate,
795
+ // resolveModal fire), but the SURFACE mask is dropped once the episode has stalled past
796
+ // AUTO_APPROVE_MASK_STALL_MS — otherwise a never-settling auto-approve hides the worker's
797
+ // waiting_approval + modal from read_chat/mesh_status/dashboard forever.
798
+ const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, nowMs)
799
+ && !this.autoApproveMaskStalled(nowMs);
800
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
801
+ let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
802
+ ? 'error'
803
+ : (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
804
+ // getState() must agree with the status the FSM-driven detectStatusTransition()
805
+ // already committed to lastStatus. The adapter's own status is authoritative; we do
806
+ // not second-guess it with native-transcript shape. Only reconcile a generating-like
807
+ // read down to idle when our own lastStatus has already flipped idle (avoids a
808
+ // perpetual dashboard spinner during the brief window before the next getStatus()).
809
+ if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
810
+ visibleStatus = 'idle';
516
811
  }
517
812
  const runtime = this.adapter.getRuntimeMetadata();
518
813
  this.maybeAppendRuntimeRecoveryMessage(runtime);
519
814
  let parsedMessages = Array.isArray(parsedStatus?.messages)
520
815
  ? parsedStatus.messages
521
816
  : [];
817
+ const parsedProviderSessionId = normalizeProviderSessionId(
818
+ this.provider,
819
+ typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
820
+ );
821
+ const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
822
+ parsedMessages,
823
+ parsedStatus,
824
+ adapterStatus,
825
+ parsedProviderSessionId,
826
+ );
827
+ if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
828
+ this.promoteProviderSessionId(adapterProviderSessionId);
829
+ }
830
+ if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
831
+ this.promoteProviderSessionId(parsedProviderSessionId);
832
+ }
833
+ if (suppressFreshLaunchStartupReplay) {
834
+ parsedMessages = [];
835
+ }
836
+ // Adapter runtime metadata is transport-owned and is not guaranteed to
837
+ // identify this conversation. Spec adapters historically exposed the
838
+ // provider spec id (for example "codex-cli") as runtimeId, which made
839
+ // concurrent sessions share one activeChat identity until their native
840
+ // provider session ids were discovered.
841
+ const activeChatId = this.providerSessionId || this.instanceId;
522
842
  const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
523
843
  ? Math.max(0, Number(parsedStatus.historyMessageCount))
524
844
  : null;
@@ -528,9 +848,20 @@ export class CliProviderInstance implements ProviderInstance {
528
848
  : [];
529
849
  }
530
850
  const mergedMessages = this.mergeConversationMessages(parsedMessages);
531
- const canonicalBackedHistory = this.syncCanonicalSavedHistoryIfNeeded();
851
+ const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
852
+ ? this.syncCanonicalSavedHistoryIfNeeded()
853
+ : false;
854
+ const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
855
+ ? this.lastPersistedHistoryMessages.map((message) => ({
856
+ role: message.role,
857
+ content: message.content,
858
+ kind: message.kind,
859
+ senderName: message.senderName,
860
+ receivedAt: message.receivedAt,
861
+ }))
862
+ : mergedMessages;
532
863
 
533
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
864
+ const dirName = workingDirBasename(this.workingDir);
534
865
  const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
535
866
  ? parsedStatus.status.trim()
536
867
  : undefined;
@@ -542,7 +873,7 @@ export class CliProviderInstance implements ProviderInstance {
542
873
  && adapterStatus.status === 'idle'
543
874
  && parsedStatus?.status === 'idle';
544
875
  let messagesToSave = parsedMessages;
545
- if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'long_generating')) {
876
+ if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'no_progress' || parsedChatStatus === 'long_generating')) {
546
877
  const lastIdx = messagesToSave.length - 1;
547
878
  if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === 'assistant') {
548
879
  messagesToSave = messagesToSave.slice(0, lastIdx);
@@ -572,33 +903,48 @@ export class CliProviderInstance implements ProviderInstance {
572
903
  }
573
904
  }
574
905
 
575
- this.applyProviderResponse(parsedStatus, { phase: 'immediate' });
906
+ this.applyProviderResponse(
907
+ suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
908
+ ? { ...parsedStatus, providerSessionId: undefined }
909
+ : parsedStatus,
910
+ { phase: 'immediate' },
911
+ );
576
912
  const surface = resolveProviderStateSurface({
577
913
  summaryMetadata: this.summaryMetadata as any,
578
914
  controlValues: this.controlValues,
579
915
  });
580
916
  const activeChatStatus = parseErrorMessage
581
917
  ? 'error'
582
- : autoApproveActive && parsedStatus?.status === 'waiting_approval'
918
+ : (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
583
919
  ? 'generating'
584
920
  : (adapterStatus.status !== 'idle'
585
921
  ? visibleStatus
586
922
  : (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
587
923
 
924
+ // If an AskUserQuestion prompt is awaiting user input, overlay status as
925
+ // waiting_choice. This is distinct from waiting_approval (tool-use consent)
926
+ // — the engine's isWaitingForResponse state is unchanged, so completion
927
+ // tracking continues normally once the user responds.
928
+ const hasInteractivePrompt = !!this.activeInteractivePrompt;
929
+ const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
930
+ const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
931
+
588
932
  return {
589
933
  type: this.type,
590
934
  name: this.provider.name,
591
935
  category: 'cli',
592
- status: visibleStatus,
936
+ status: finalStatus,
593
937
  mode: this.presentationMode,
594
938
  activeChat: {
595
- id: `${this.type}_${this.workingDir}`,
939
+ id: activeChatId,
596
940
  title: parsedStatus?.title || dirName,
597
- status: activeChatStatus,
598
- messages: mergedMessages,
599
- activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
941
+ status: finalChatStatus,
942
+ messages: statusMessages,
943
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
944
+ activeInteractivePrompt: this.activeInteractivePrompt,
600
945
  inputContent: '',
601
946
  },
947
+ activeInteractivePrompt: this.activeInteractivePrompt,
602
948
  workspace: this.workingDir,
603
949
  instanceId: this.instanceId,
604
950
  providerSessionId: this.providerSessionId,
@@ -638,8 +984,12 @@ export class CliProviderInstance implements ProviderInstance {
638
984
 
639
985
  getHotChatSessionState(): HotChatSessionState {
640
986
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
641
- const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
642
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
987
+ const nowMs = Date.now();
988
+ // STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
989
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
990
+ && !this.autoApproveMaskStalled(nowMs);
991
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
992
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
643
993
  const runtime = this.adapter.getRuntimeMetadata();
644
994
  return {
645
995
  id: this.instanceId,
@@ -651,36 +1001,231 @@ export class CliProviderInstance implements ProviderInstance {
651
1001
  };
652
1002
  }
653
1003
 
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';
1004
+ getSessionModalState(sessionId?: string): SessionModalState {
1005
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
1006
+ const nowMs = Date.now();
1007
+ // STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
1008
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
1009
+ && !this.autoApproveMaskStalled(nowMs);
1010
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
1011
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
1012
+ const dirName = workingDirBasename(this.workingDir);
659
1013
  return {
660
- id: this.instanceId,
1014
+ // Honor the caller-supplied sessionId — InstanceMgr rejects the
1015
+ // projection when projected.id !== requested sessionId, and
1016
+ // this.instanceId is the manager's internal key, not the public
1017
+ // sessionId the dashboard subscribes by.
1018
+ id: sessionId ?? this.instanceId,
661
1019
  status: visibleStatus,
662
1020
  title: dirName,
663
- activeModal: autoApproveActive ? null : adapterStatus.activeModal,
1021
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
664
1022
  };
665
1023
  }
666
1024
 
667
1025
  updateSettings(newSettings: Record<string, any>): void {
668
- this.settings = { ...newSettings };
1026
+ // Merge semantics: a key omitted from newSettings preserves its existing
1027
+ // value, a key present in newSettings (even as false) overrides it.
1028
+ //
1029
+ // This is required because updateSettings has two callers with opposite
1030
+ // intent:
1031
+ // 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
1032
+ // → getSettings → updateInstanceSettings) sends the COMPLETE settings
1033
+ // object, so an explicit autoApprove:false must win.
1034
+ // 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
1035
+ // buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
1036
+ // meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
1037
+ // re-dispatch. It carries no autoApprove, so a full replacement would
1038
+ // wipe the launch-time autoApprove:true the worker was started with,
1039
+ // silently dropping every later approval to a manual gate until the
1040
+ // machine-page toggle re-injected the full settings.
1041
+ //
1042
+ // A plain merge satisfies both: undefined keys fall through to the existing
1043
+ // value (preserving launch-stamp settings like autoApprove + the mesh routing
1044
+ // keys), explicit keys override. This subsumes the previous mesh-key preserve
1045
+ // list, which only protected the routing keys and not autoApprove.
1046
+ this.settings = { ...this.settings, ...newSettings };
669
1047
  this.adapter.updateRuntimeSettings?.(this.settings);
670
1048
  this.monitor.updateConfig({
671
1049
  approvalAlert: this.settings.approvalAlert !== false,
672
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
673
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
1050
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
1051
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
674
1052
  });
675
1053
  }
676
1054
 
1055
+ /**
1056
+ * Stamp a direct-dispatch mesh assignment on this instance.
1057
+ * setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
1058
+ * route generating_completed back to the originating coordinator. Without
1059
+ * this stamp, mesh_send_task --direct targets a plain CLI session whose
1060
+ * completion events silently drop because the forwarder has nothing to
1061
+ * match against.
1062
+ */
1063
+ attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string; coordinatorSessionId?: string }): void {
1064
+ if (!assignment?.meshId) return;
1065
+ this.settings = {
1066
+ ...this.settings,
1067
+ meshNodeFor: assignment.meshId,
1068
+ // WTCLAIM (A): track the bound node id under BOTH the active marker
1069
+ // (meshNodeId, cleared on detach) and a sticky marker (meshLastNodeId,
1070
+ // preserved across detach). The sticky marker lets a detached but still
1071
+ // coordinator-owned session be re-picked ONLY for the SAME node it served
1072
+ // — never auto-adopted for a sibling node (e.g. a cloned worktree) that
1073
+ // shares this daemon. See isMeshOwnedDelegateSession's post-detach gate.
1074
+ ...(assignment.nodeId ? { meshNodeId: assignment.nodeId, meshLastNodeId: assignment.nodeId } : {}),
1075
+ ...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
1076
+ ...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
1077
+ // Session-level routing anchor: the originating coordinator session, so this
1078
+ // worker's completion events route back to the exact session that dispatched it.
1079
+ ...(assignment.coordinatorSessionId ? { meshCoordinatorSessionId: assignment.coordinatorSessionId } : {}),
1080
+ };
1081
+ this.adapter.updateRuntimeSettings?.(this.settings);
1082
+ }
1083
+
1084
+ /**
1085
+ * Clear a previously-attached mesh assignment after the task reaches a
1086
+ * terminal state. Leaving meshNodeFor pinned would route this session's
1087
+ * subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
1088
+ * coordinator as if they were task completions.
1089
+ *
1090
+ * MESHID-DROP-ON-DETACH (Fix C): a coordinator-LAUNCHED worker session
1091
+ * (launchedByCoordinator) holds its mesh membership (meshNodeFor / meshNodeId /
1092
+ * meshCoordinatorDaemonId) at the SESSION level — set once at launch
1093
+ * (mesh_launch_session / queue auto-launch), independent of any single task.
1094
+ * The original detach wiped meshNodeFor + meshNodeId together with the
1095
+ * task-level meshActiveTaskId, so the FIRST task completion stripped the
1096
+ * membership and EVERY subsequent completion forwarded with meshId absent —
1097
+ * resolveWorkerDelegateRouting fell to mesh_unresolved and the coordinator
1098
+ * rejected the forward "meshId required". For a launched member we therefore
1099
+ * clear ONLY the task-level marker (meshActiveTaskId) and preserve the
1100
+ * session-level membership so its next task's completion still resolves.
1101
+ * A task-less ad-hoc turn on a preserved-membership session is NOT misrouted:
1102
+ * its completion carries no taskId and the session holds no active assignment,
1103
+ * so the forwarder's WARMUPGAP guard skips the dispatch-row flip (it only
1104
+ * injects a benign task-less notification). A NON-launched session (a plain CLI
1105
+ * session adopted by mesh_send_task --direct, launchedByCoordinator falsy)
1106
+ * keeps the original full clear so an ad-hoc session is never left pinned.
1107
+ */
1108
+ detachMeshAssignment(): void {
1109
+ if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
1110
+ // Session-level member: keep membership, drop only the task-level marker.
1111
+ if (this.settings.launchedByCoordinator === true) {
1112
+ if (!this.settings.meshActiveTaskId) return;
1113
+ const { meshActiveTaskId, ...rest } = this.settings;
1114
+ void meshActiveTaskId;
1115
+ this.settings = rest;
1116
+ this.adapter.updateRuntimeSettings?.(this.settings);
1117
+ return;
1118
+ }
1119
+ const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
1120
+ void meshNodeFor; void meshActiveTaskId;
1121
+ // WTCLAIM (A): clear the active binding but PRESERVE the last bound node id
1122
+ // (meshLastNodeId) so a later sessionless dispatch can re-adopt this idle
1123
+ // session ONLY for the node it last served. Carry the id being cleared, or
1124
+ // keep an already-present sticky marker if meshNodeId was absent.
1125
+ const lastNodeId = (typeof meshNodeId === 'string' && meshNodeId.trim())
1126
+ ? meshNodeId.trim()
1127
+ : (typeof rest.meshLastNodeId === 'string' && rest.meshLastNodeId.trim() ? rest.meshLastNodeId.trim() : undefined);
1128
+ this.settings = lastNodeId ? { ...rest, meshLastNodeId: lastNodeId } : rest;
1129
+ this.adapter.updateRuntimeSettings?.(this.settings);
1130
+ }
1131
+
1132
+ /**
1133
+ * The resolved modal-park status of this session, or null when it is not
1134
+ * parked on a modal awaiting a human answer. Mirrors the overlay logic in
1135
+ * getState(): an active AskUserQuestion interactive prompt resolves to
1136
+ * waiting_choice; otherwise the adapter's waiting_approval (tool consent)
1137
+ * counts — UNLESS auto-approve will dismiss it, in which case the session is
1138
+ * effectively generating and is NOT modal-parked. This is the single signal
1139
+ * the mesh force-inject guard consults, and the same status string the
1140
+ * reconcile loop reads off get_status_metadata. Lowercase literals only —
1141
+ * the SessionStatus enum is forked across modules and waiting_choice is
1142
+ * absent from some of them.
1143
+ */
1144
+ resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
1145
+ if (this.activeInteractivePrompt) return 'waiting_choice';
1146
+ let adapterStatus: { status?: string };
1147
+ try {
1148
+ adapterStatus = this.adapter.getStatus({ allowParse: false });
1149
+ } catch {
1150
+ return null;
1151
+ }
1152
+ // A session whose auto-approve is held by manual attendance IS parked on a
1153
+ // modal awaiting the human — autoApproveEffectivelyActive folds that in, so
1154
+ // the mesh force-inject guard correctly treats it as modal-parked. STATUS-MISMATCH:
1155
+ // a STALLED auto-approve (never resolving) is likewise effectively parked — treat it
1156
+ // as modal-parked so its events are held/surfaced rather than masked behind generating.
1157
+ if (adapterStatus.status === 'waiting_approval'
1158
+ && (!this.autoApproveEffectivelyActive(adapterStatus.status) || this.autoApproveMaskStalled())) {
1159
+ // NOTIF-HELD-DRAIN (Fix 1): an autonomous mesh session (coordinator or worker)
1160
+ // that is actively progressing a turn — a tool call is in flight
1161
+ // (hasAdapterPendingResponse) and NO human is attending it by hand — surfaces a
1162
+ // routine tool-consent `waiting_approval` on EVERY tool call when auto-approve is
1163
+ // off. That transient consent is part of the turn the harness/operator drives to
1164
+ // completion, NOT a session genuinely wedged awaiting a human's modal answer.
1165
+ // Classifying it modal-parked makes findLiveCoordinators hold the mesh's pending
1166
+ // completion events under `modal_parked` across a busy coordinator's whole work
1167
+ // batch, which is the multi-minute notification stall. Treat such a transient
1168
+ // consent as NOT modal-parked so it is held as ordinary "generating" (released on
1169
+ // the next idle) instead. A manually-attended session, a stalled auto-approve, or a
1170
+ // non-progressing session (no turn in flight) still parks — those are the genuine
1171
+ // human-await cases the guard must keep holding.
1172
+ if (this.isTransientToolConsent()) {
1173
+ return null;
1174
+ }
1175
+ return 'waiting_approval';
1176
+ }
1177
+ return null;
1178
+ }
1179
+
1180
+ /**
1181
+ * NOTIF-HELD-DRAIN: true when this `waiting_approval` is a routine, transient tool-consent
1182
+ * of an autonomously-progressing mesh session rather than a genuine human-await modal —
1183
+ * i.e. it is a mesh coordinator/worker session, a turn is actively in flight
1184
+ * (hasAdapterPendingResponse), and no human is attending it by hand. Such a consent is
1185
+ * driven to resolution by the harness/operator as part of the in-flight turn, so holding
1186
+ * the mesh's completion events behind it (modal_parked) is the false-positive that stalls
1187
+ * delivery. Narrow by design: manual attendance or a non-progressing session falls through
1188
+ * to the genuine-modal classification.
1189
+ */
1190
+ private isTransientToolConsent(now = Date.now()): boolean {
1191
+ const isAutonomousMeshSession = this.isMeshWorkerSession() || !!this.settings.meshCoordinatorFor;
1192
+ return isAutonomousMeshSession
1193
+ && this.hasAdapterPendingResponse()
1194
+ && !this.manualAttendance.isAttended(now);
1195
+ }
1196
+
1197
+ /** True when this session is parked on a modal awaiting a human answer. */
1198
+ isModalParked(): boolean {
1199
+ return this.resolveModalParkStatus() !== null;
1200
+ }
1201
+
677
1202
  onEvent(event: string, data?: any): void {
678
1203
  if (event === 'send_message') {
679
1204
  const input = normalizeInputEnvelope(data);
680
1205
  assertProviderSupportsDeclaredInput(this.provider, input);
681
1206
  const promptText = buildCliStructuredInputPrompt(input);
682
1207
  if (promptText) {
683
- void this.adapter.sendMessage(promptText).catch((e: any) => {
1208
+ // force:true bypasses the busy/generating send guard so terminal mesh
1209
+ // events (completion/failure/bootstrap) land in a coordinator session that
1210
+ // is itself parked in `generating` while awaiting that very event.
1211
+ // Without it the message is queued and only flushed on the coordinator's
1212
+ // own idle transition — which never happens until it receives the message.
1213
+ const force = data?.force === true;
1214
+ // Modal guard: a force-inject still writes raw keystrokes into the PTY,
1215
+ // bypassing the busy send-guard. If the coordinator is parked on a
1216
+ // harness modal (claude-cli AskUserQuestion → waiting_choice, or a
1217
+ // tool-consent waiting_approval), those keystrokes are consumed by the
1218
+ // modal's key handler and silently select a choice the user never made
1219
+ // (data corruption). Hold the force-inject in that narrow window —
1220
+ // the event stays queued and the reconcile loop redelivers it on the
1221
+ // next tick once the modal is resolved. We ONLY hold for the two modal
1222
+ // states; generating is still force-injected (that is the deadlock the
1223
+ // force path exists to break — see mesh-events-coordinator).
1224
+ if (force && this.isModalParked()) {
1225
+ LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
1226
+ return;
1227
+ }
1228
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
684
1229
  LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
685
1230
  });
686
1231
  }
@@ -690,14 +1235,101 @@ export class CliProviderInstance implements ProviderInstance {
690
1235
  void this.adapter.resolveAction(data).catch((e: any) => {
691
1236
  LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
692
1237
  });
1238
+ } else if (event === 'interactive_prompt' && data) {
1239
+ const prompt = normalizeInteractivePrompt(data);
1240
+ if (prompt) {
1241
+ this.activeInteractivePrompt = prompt;
1242
+ this.events.push({
1243
+ event: 'interactive_prompt',
1244
+ timestamp: Date.now(),
1245
+ promptId: prompt.promptId,
1246
+ });
1247
+ }
1248
+ } else if (event === 'interactive_prompt_response' && data) {
1249
+ try {
1250
+ const response = normalizeInteractivePromptResponse(data);
1251
+ if (this.activeInteractivePrompt?.promptId === response.promptId) {
1252
+ this.activeInteractivePrompt = null;
1253
+ }
1254
+ if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
1255
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
1256
+ return;
1257
+ }
1258
+ void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
1259
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
1260
+ });
1261
+ } catch (e: any) {
1262
+ LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
1263
+ }
693
1264
  } else if (event === 'provider_state_patch' && data && typeof data === 'object') {
694
1265
  this.applyProviderResponse(data, { phase: 'immediate' });
695
1266
  }
696
1267
  }
697
1268
 
1269
+ recordAcknowledgedUserInput(input: InputEnvelope | string): void {
1270
+ const content = typeof input === 'string'
1271
+ ? input.trim()
1272
+ : buildCliStructuredInputPrompt(input).trim();
1273
+ if (!content) return;
1274
+
1275
+ const receivedAt = Date.now();
1276
+
1277
+ // TASKBUBBLE-DUP: collapse a redelivered dispatch to one bubble. A single
1278
+ // mesh_send_task can reach this instance as TWO send_chat calls when the
1279
+ // first injection is buffered during bootstrap/busy and a retry (dispatch-
1280
+ // confirm-timeout requeue, or a reconcile re-dispatch) fires before the
1281
+ // outbound queue drains. The previous dedupKey hashed receivedAt, so the
1282
+ // two acks produced different keys and BOTH bubbled. Suppress an identical
1283
+ // content ack seen within USER_INPUT_ACK_DEDUP_WINDOW_MS; a later resend of
1284
+ // the same text (beyond the window) is a genuine new turn and still shows.
1285
+ const ackContentKey = shortHash(`${this.instanceId}:${content}`, 24);
1286
+ const lastAckAt = this.recentUserInputAcks.get(ackContentKey);
1287
+ if (lastAckAt !== undefined && receivedAt - lastAckAt <= USER_INPUT_ACK_DEDUP_WINDOW_MS) {
1288
+ // Refresh the timestamp so a steady stream of redeliveries keeps
1289
+ // collapsing, and prune stale entries to bound the map size.
1290
+ this.recentUserInputAcks.set(ackContentKey, receivedAt);
1291
+ this.pruneRecentUserInputAcks(receivedAt);
1292
+ return;
1293
+ }
1294
+ this.recentUserInputAcks.set(ackContentKey, receivedAt);
1295
+ this.pruneRecentUserInputAcks(receivedAt);
1296
+
1297
+ this.lastAcknowledgedUserInputAt = receivedAt;
1298
+ // The runtimeMessages dedupKey stays per-call unique (includes receivedAt)
1299
+ // so a genuine resend of the same text after the window appends a fresh
1300
+ // bubble; redelivery within the window is already suppressed above.
1301
+ const dedupKey = `user_input_ack:${shortHash(`${this.instanceId}:${content}:${receivedAt}`, 24)}`;
1302
+ this.appendRuntimeMessage(buildChatMessage({
1303
+ role: 'user',
1304
+ senderName: 'User',
1305
+ kind: 'standard',
1306
+ content,
1307
+ receivedAt,
1308
+ timestamp: receivedAt,
1309
+ source: 'runtime_input_ack',
1310
+ meta: {
1311
+ runtimeInputAck: true,
1312
+ provider: this.type,
1313
+ workspace: this.workingDir,
1314
+ },
1315
+ } as ChatMessage), dedupKey);
1316
+ }
1317
+
1318
+ /** Drop user-input ack entries older than the dedup window so the map can't grow unbounded. */
1319
+ private pruneRecentUserInputAcks(now: number): void {
1320
+ if (this.recentUserInputAcks.size <= 1) return;
1321
+ for (const [key, at] of this.recentUserInputAcks) {
1322
+ if (now - at > USER_INPUT_ACK_DEDUP_WINDOW_MS) this.recentUserInputAcks.delete(key);
1323
+ }
1324
+ }
1325
+
698
1326
  dispose(): void {
699
1327
  this.adapter.shutdown();
700
1328
  this.monitor.reset();
1329
+ // Cancel any armed auto-approve timers so a pending settle re-check
1330
+ // can't fire resolveModal/detectStatusTransition against a dead adapter.
1331
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1332
+ if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
701
1333
  this.appliedEffectKeys.clear();
702
1334
  try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
703
1335
  this.cachedSqliteDb = null;
@@ -706,6 +1338,7 @@ export class CliProviderInstance implements ProviderInstance {
706
1338
 
707
1339
  private completedDebounceTimer: NodeJS.Timeout | null = null;
708
1340
  private completedDebouncePending: CompletedDebouncePending | null = null;
1341
+ private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
709
1342
 
710
1343
  private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
711
1344
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
@@ -740,7 +1373,191 @@ export class CliProviderInstance implements ProviderInstance {
740
1373
  const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
741
1374
  const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
742
1375
  const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
743
- return role === 'assistant' && !!content;
1376
+ if (role !== 'assistant' || !content) return false;
1377
+ // Guard: if the last assistant message looks like an active approval/input prompt,
1378
+ // it is not a real completion — the session is still awaiting user input.
1379
+ if (looksLikeActiveApprovalPromptText(content)) return false;
1380
+ return true;
1381
+ }
1382
+
1383
+ private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
1384
+ const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1385
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1386
+ const readAt = Date.now();
1387
+ const mtimeMs = Number(sourceMtimeMs) || 0;
1388
+ return {
1389
+ readAt,
1390
+ msgCount: messages.length,
1391
+ lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
1392
+ lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
1393
+ contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
1394
+ sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
1395
+ sourceMtimeMs: mtimeMs || null,
1396
+ mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
1397
+ };
1398
+ }
1399
+
1400
+ private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
1401
+ const probe = this.lastExternalCompletionProbe;
1402
+ if (!probe) return null;
1403
+ const history = pending.transcriptProbeHistory || [];
1404
+ const last = history[history.length - 1];
1405
+ if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
1406
+ history.push(probe);
1407
+ pending.transcriptProbeHistory = history.slice(-5);
1408
+ }
1409
+ return probe;
1410
+ }
1411
+
1412
+ private readExternalCompletionMessages(): unknown[] | null {
1413
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1414
+ if (!adapterOwnsMessagesElsewhere) return null;
1415
+ if (!this.providerSessionId) return null;
1416
+ if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
1417
+
1418
+ if (this.lastExternalCompletionProbe?.sourcePath) {
1419
+ try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
1420
+ }
1421
+ const restoredHistory = readProviderChatHistory(this.type, {
1422
+ canonicalHistory: this.provider.nativeHistory,
1423
+ historySessionId: this.providerSessionId,
1424
+ workspace: this.workingDir,
1425
+ offset: 0,
1426
+ limit: Number.MAX_SAFE_INTEGER,
1427
+ historyBehavior: this.provider.historyBehavior,
1428
+ scripts: this.provider.scripts as any,
1429
+ sessionStartedAtMs: this.startedAt,
1430
+ forceRefresh: true,
1431
+ });
1432
+ if (restoredHistory.source !== 'provider-native') {
1433
+ this.lastExternalCompletionProbe = null;
1434
+ return null;
1435
+ }
1436
+ this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
1437
+ restoredHistory.messages,
1438
+ restoredHistory.sourcePath,
1439
+ restoredHistory.sourceMtimeMs,
1440
+ );
1441
+ return restoredHistory.messages;
1442
+ }
1443
+
1444
+ private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
1445
+ if (this.completionHasFinalAssistantMessage(parsedMessages)) {
1446
+ return {
1447
+ present: true,
1448
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1449
+ source: 'parsed',
1450
+ };
1451
+ }
1452
+
1453
+ const externalMessages = this.readExternalCompletionMessages();
1454
+ if (externalMessages) {
1455
+ return {
1456
+ present: this.completionHasFinalAssistantMessage(externalMessages),
1457
+ messages: externalMessages,
1458
+ source: 'external-native',
1459
+ };
1460
+ }
1461
+
1462
+ return {
1463
+ present: false,
1464
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1465
+ source: 'unavailable',
1466
+ };
1467
+ }
1468
+
1469
+ private completionFinalSummary(parsedMessages: unknown, turnStartedAt?: number): string | undefined {
1470
+ // For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
1471
+ // screen parse is NOT the source of truth for the final summary — the terminal
1472
+ // wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
1473
+ // prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
1474
+ // the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
1475
+ // to the parsed screen only when the transcript is unavailable. This is the real cause
1476
+ // of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
1477
+ // any short, fast-completing task where screen parse wins the race).
1478
+ //
1479
+ // NOTIF Defect-B: `turnStartedAt` (the producing turn's start, snapshotted on the
1480
+ // completedDebouncePending record) turn-scopes the NATIVE transcript read. The native
1481
+ // transcript holds the WHOLE session filtered only by session start, so a debounce that
1482
+ // flushes before the producing turn's final assistant bubble has landed would otherwise
1483
+ // return the PRIOR task's last bubble (event taskId=B but summary=A). Filtering to bubbles
1484
+ // at/after turnStartedAt yields '' in that race instead of the stale tail; the weak/empty
1485
+ // summary is later upgraded by the mesh reconcile loop once the real bubble is written.
1486
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1487
+ const parsedSummary = extractFinalSummaryFromMessages(
1488
+ (this.completionHasFinalAssistantMessage(parsedMessages)
1489
+ ? (Array.isArray(parsedMessages) ? parsedMessages : [])
1490
+ : []) as any,
1491
+ );
1492
+ if (adapterOwnsMessagesElsewhere) {
1493
+ const externalMessages = this.readExternalCompletionMessages();
1494
+ // Turn-scope the external transcript: never return a bubble produced before this
1495
+ // turn started. With no boundary known (turnStartedAt falsy) behaviour is unchanged.
1496
+ const externalSummary = externalMessages
1497
+ ? extractFinalSummaryFromMessagesAfter(externalMessages as any, turnStartedAt)
1498
+ : '';
1499
+ // The transcript is authoritative for native-source providers. Use it unless it is
1500
+ // empty (not yet written, or no in-turn bubble) — only then fall back to the screen
1501
+ // parse, which reflects the LIVE screen (this turn's output), not the stale tail.
1502
+ if (externalSummary) return externalSummary;
1503
+ return parsedSummary || undefined;
1504
+ }
1505
+ return parsedSummary || undefined;
1506
+ }
1507
+
1508
+ private buildCompletedFinalizationDiagnostic(args: {
1509
+ blockReason: string;
1510
+ latestStatus?: any;
1511
+ latestVisibleStatus: string;
1512
+ waitedMs: number;
1513
+ pending: CompletedDebouncePending;
1514
+ emittedAfterFinalizationTimeout: boolean;
1515
+ }): Record<string, unknown> {
1516
+ let parsed: any = null;
1517
+ let parseError: string | undefined;
1518
+ try {
1519
+ parsed = this.adapter.getScriptParsedStatus();
1520
+ } catch (error: any) {
1521
+ parseError = error?.message || String(error);
1522
+ }
1523
+
1524
+ const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
1525
+ if (evidence.source === 'external-native') {
1526
+ this.recordPendingTranscriptProbe(args.pending);
1527
+ }
1528
+ const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
1529
+ .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1530
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1531
+ const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
1532
+ const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
1533
+ const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
1534
+
1535
+ return {
1536
+ providerType: this.type,
1537
+ sessionId: this.instanceId,
1538
+ providerSessionId: this.providerSessionId || null,
1539
+ workspace: this.workingDir,
1540
+ blockReason: args.blockReason,
1541
+ emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
1542
+ waitedMs: args.waitedMs,
1543
+ maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
1544
+ adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
1545
+ latestVisibleStatus: args.latestVisibleStatus,
1546
+ parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
1547
+ parseError: parseError || undefined,
1548
+ finalAssistantPresent: evidence.present,
1549
+ finalAssistantEvidenceSource: evidence.source,
1550
+ visibleMessageCount: visibleMessages.length,
1551
+ lastVisibleRole,
1552
+ lastVisibleKind,
1553
+ lastVisibleContentLength,
1554
+ pendingStartedAt: this.generatingStartedAt || null,
1555
+ pendingFirstObservedAt: args.pending.firstObservedAt,
1556
+ pendingTimestamp: args.pending.timestamp,
1557
+ pendingDurationSec: args.pending.duration,
1558
+ previousBlockReason: args.pending.loggedBlockReason || null,
1559
+ transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
1560
+ };
744
1561
  }
745
1562
 
746
1563
  private hasAdapterPendingResponse(): boolean {
@@ -765,41 +1582,206 @@ export class CliProviderInstance implements ProviderInstance {
765
1582
  if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
766
1583
  if (adapterRawStatus !== 'idle') return false;
767
1584
  if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
768
- return !this.hasAdapterPendingResponse();
1585
+ if (this.hasAdapterPendingResponse()) return false;
1586
+ // Do not suppress when the adapter's raw response buffer is still non-empty.
1587
+ // This catches the case where isWaitingForResponse has already flipped to false
1588
+ // (so getPartialResponse() returns '') but the provider's native parser still
1589
+ // reports generating because it's parsing buffered content. Suppressing the
1590
+ // finalization block here would emit a false completion event while the provider
1591
+ // session is still actively processing its response stream.
1592
+ const adapterAny = this.adapter as any;
1593
+ if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
1594
+ return true;
769
1595
  }
770
1596
 
771
- private getCompletedFinalizationBlockReason(latestVisibleStatus: string): string | null {
772
- if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}`;
1597
+ private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1598
+ if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
773
1599
 
774
1600
  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';
1601
+ const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
1602
+ if (!approvalResolvedIdle) {
1603
+ if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
1604
+ if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
1605
+ if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
1606
+ }
777
1607
 
778
1608
  const partial = typeof this.adapter.getPartialResponse === 'function'
779
1609
  ? this.adapter.getPartialResponse()
780
1610
  : '';
781
- if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
1611
+ if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
782
1612
 
783
1613
  let parsed: any;
784
1614
  try {
785
1615
  parsed = this.adapter.getScriptParsedStatus();
786
1616
  } catch (error: any) {
787
- return `parse_error:${error?.message || String(error)}`;
1617
+ return { reason: `parse_error:${error?.message || String(error)}` };
788
1618
  }
789
1619
 
790
1620
  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';
1621
+ if (parsedStatus !== 'idle') {
1622
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1623
+ if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
1624
+ return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
1625
+ }
1626
+ if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
1627
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1628
+ const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
1629
+ const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1630
+ LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
1631
+ if (!finalAssistantEvidence.present) {
1632
+ if (adapterOwnsMessagesElsewhere) {
1633
+ if (finalAssistantEvidence.source === 'external-native') {
1634
+ const probe = this.recordPendingTranscriptProbe(pending);
1635
+ if (probe && !pending.loggedTranscriptProbe) {
1636
+ 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`);
1637
+ pending.loggedTranscriptProbe = true;
1638
+ }
1639
+ LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
1640
+ if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
1641
+ return null;
1642
+ }
1643
+ if (this.type === 'antigravity-cli') {
1644
+ return null;
1645
+ }
1646
+ // (SETTLE-VALLEY) The inter-approval idle valley: a native-history mesh worker
1647
+ // that resolved an approval and fell briefly idle (waiting_approval→idle) BEFORE
1648
+ // the next approval turn resumes. The live valley (~3s) is mostly covered by the
1649
+ // 4000ms NATIVE_HISTORY_MESH_IDLE_SETTLE_MS settle window, but a longer valley can
1650
+ // still let the flush run while the transcript's final assistant turn is not yet
1651
+ // written (source still the screen parse → finalAssistantPresent=false,
1652
+ // workerResult.source='default'). CANON-C would emit immediately here, freezing a
1653
+ // truncated preamble summary as evidenceLevel=insufficient. Instead HOLD: this
1654
+ // waiting_approval hold complements the settle window. Retry until the transcript finalizes
1655
+ // (block clears → genuine emit) or the worker resumes (resume guard cancels),
1656
+ // bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS. Scoped to the approval-resolved
1657
+ // idle so a genuinely-finished background-child turn keeps the CANON-C immediate
1658
+ // emit (its transcript trails by a write, not by a whole resume).
1659
+ if (allowMissingAssistantTimeout && pending.previousStatus === 'waiting_approval') {
1660
+ return { reason: 'missing_final_assistant', terminal: false, holdForTranscript: true };
1661
+ }
1662
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1663
+ }
1664
+ if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
1665
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1666
+ }
1667
+ } else {
1668
+ LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
1669
+ return {
1670
+ reason: 'missing_final_assistant',
1671
+ terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
1672
+ allowTimeout: allowMissingAssistantTimeout,
1673
+ };
1674
+ }
1675
+ }
1676
+
1677
+ // (FALSEIDLE-a) Structural approval-resolution gate. Runs BEFORE the brittle
1678
+ // screen-text heuristic below so it also catches modals whose text does not match
1679
+ // looksLikeActiveApprovalPromptText (e.g. claude-cli's cd / "untrusted hooks" prompt).
1680
+ const approvalResolutionBlock = this.approvalResolutionFinalizationBlock(pending);
1681
+ if (approvalResolutionBlock) return approvalResolutionBlock;
1682
+
1683
+ // Guard: if the screen still shows an approval/choice prompt as the last visible text,
1684
+ // the turn is not complete even if the parsed status says idle and there is an assistant
1685
+ // message. This catches the case where waiting_approval→idle transitions occur before
1686
+ // the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
1687
+ try {
1688
+ const screenText = typeof (this.adapter as any).getScreenText === 'function'
1689
+ ? String((this.adapter as any).getScreenText() || '')
1690
+ : '';
1691
+ if (screenText) {
1692
+ const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
1693
+ if (looksLikeActiveApprovalPromptText(tailLines)) {
1694
+ return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
1695
+ }
1696
+ }
1697
+ } catch { /* defensive: screen text read is best-effort */ }
794
1698
 
795
1699
  return null;
796
1700
  }
797
1701
 
1702
+ // (FALSEIDLE-a) Positive, structural proof that the latest approval entry was resolved
1703
+ // through ADHDev. resolveModal() — driven by auto-approve, dashboard/mesh_approve, and
1704
+ // dev-cli-debug alike — advances the engine's lastResolvedEntrySeq to the current
1705
+ // approvalEntrySeq. So `lastResolvedEntrySeq >= approvalEntrySeq` (with a real entry,
1706
+ // approvalEntrySeq > 0) means the modal we last saw was actually answered. Absence of this
1707
+ // evidence after a waiting_approval→idle transition means the idle is suspect: the spec's
1708
+ // text-based approval→idle rule false-tripped while the modal is still unresolved.
1709
+ // Fails OPEN (returns true) when the seq fields are unavailable, so the gate can never wedge
1710
+ // a session on a provider/adapter that does not surface the counters.
1711
+ private hasApprovalResolutionEvidence(): boolean {
1712
+ try {
1713
+ const status = this.adapter.getStatus({ allowParse: false }) as any;
1714
+ const entrySeq = typeof status?.approvalEntrySeq === 'number' ? status.approvalEntrySeq : 0;
1715
+ if (entrySeq <= 0) return true;
1716
+ const resolvedSeq = typeof status?.lastResolvedEntrySeq === 'number' ? status.lastResolvedEntrySeq : undefined;
1717
+ if (resolvedSeq === undefined) return true;
1718
+ return resolvedSeq >= entrySeq;
1719
+ } catch {
1720
+ return true;
1721
+ }
1722
+ }
1723
+
1724
+ // (FALSEIDLE-a) Hold a completion that is the anomalous DIRECT waiting_approval→idle
1725
+ // transition with no positive resolution evidence. A genuinely resolved approval routes
1726
+ // through resolveModal → setStatus('generating'), so its completion's previousStatus is
1727
+ // 'generating' (not 'waiting_approval') and this gate never fires for it. Scoped to
1728
+ // delegated mesh/coordinator sessions — whose only modal-resolution path is auto-approve /
1729
+ // mesh_approve (both advance lastResolvedEntrySeq) — so an interactive local session, where
1730
+ // a human may answer the PTY prompt directly and leave no resolveModal record, is untouched.
1731
+ // Non-terminal: the hold is bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS (30s), giving a
1732
+ // settling auto-approve time to fire and advance the seq, and guaranteeing no permanent wedge
1733
+ // if resolution ever happens via a path that does not record evidence.
1734
+ private approvalResolutionFinalizationBlock(pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1735
+ if (pending.previousStatus !== 'waiting_approval') return null;
1736
+ const meshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1737
+ if (!meshContext) return null;
1738
+ if (this.hasApprovalResolutionEvidence()) return null;
1739
+ return { reason: 'approval_resolution_unconfirmed', terminal: false };
1740
+ }
1741
+
798
1742
  private scheduleCompletedDebounceFlush(delayMs: number): void {
799
1743
  if (this.completedDebounceTimer) clearTimeout(this.completedDebounceTimer);
800
1744
  this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
801
1745
  }
802
1746
 
1747
+ // EVTTRACE (observation-only): is this a mesh worker session whose completion
1748
+ // events must route to a coordinator? Used purely to gate trace logging so a
1749
+ // non-mesh CLI session's completions don't add EvtTrace noise. No decision logic.
1750
+ private isMeshWorkerSession(): boolean {
1751
+ return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId
1752
+ || this.settings.meshNodeId || this.settings.launchedByCoordinator);
1753
+ }
1754
+
1755
+ /**
1756
+ * ARCH-REFACTOR R1: the taskId to attribute the CURRENTLY-completing turn to.
1757
+ * Prefers the per-turn binding (engine.currentTurnTaskId, set when the turn was
1758
+ * submitted and surviving until the next turn starts) over the last-write-wins
1759
+ * session scalar (settings.meshActiveTaskId). The scalar is retained only as a
1760
+ * backward-compat alias for the "current/last assignment" and is the source of the
1761
+ * NOTIF-MISDELIVER / TASK-MSG-MISROUTE race: a second task attaching before this
1762
+ * turn completes overwrites it. Returns undefined for a non-task ad-hoc turn.
1763
+ */
1764
+ private completingTurnTaskId(): string | undefined {
1765
+ const turnTaskId = this.adapter?.currentTurnTaskId;
1766
+ if (typeof turnTaskId === 'string' && turnTaskId.trim()) return turnTaskId;
1767
+ const scalar = this.settings.meshActiveTaskId;
1768
+ return typeof scalar === 'string' && scalar.trim() ? scalar : undefined;
1769
+ }
1770
+
1771
+ // EVTTRACE correlation context for this session's completion lifecycle. taskId is
1772
+ // the primary grep anchor; instanceId is the session fallback.
1773
+ private meshTraceCtx(event = 'agent:generating_completed'): Record<string, unknown> {
1774
+ return {
1775
+ // ARCH-REFACTOR R1: trace the per-turn taskId (falling back to the scalar) so
1776
+ // EvtTrace anchors on the same id the completion event actually carries.
1777
+ taskId: this.completingTurnTaskId(),
1778
+ sessionId: this.instanceId,
1779
+ nodeId: this.settings.meshNodeId,
1780
+ meshId: this.settings.meshNodeFor,
1781
+ event,
1782
+ };
1783
+ }
1784
+
803
1785
  private flushCompletedDebounceIfFinalized(): void {
804
1786
  const pending = this.completedDebouncePending;
805
1787
  if (!pending) {
@@ -809,7 +1791,8 @@ export class CliProviderInstance implements ProviderInstance {
809
1791
 
810
1792
  const latestStatus = this.adapter.getStatus({ allowParse: false });
811
1793
  const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
812
- const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
1794
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
1795
+ 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
1796
  if (latestVisibleStatus !== 'idle') {
814
1797
  LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
815
1798
  this.completedDebouncePending = null;
@@ -817,84 +1800,514 @@ export class CliProviderInstance implements ProviderInstance {
817
1800
  return;
818
1801
  }
819
1802
 
820
- const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
821
- if (blockReason) {
1803
+ const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
1804
+ if (block) {
1805
+ const blockReason = block.reason;
822
1806
  const waitedMs = Date.now() - pending.firstObservedAt;
823
- if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
1807
+ // CANON-C (completion-gate decouple): a block carrying `allowTimeout` is the
1808
+ // transcript-evidence gate — the worker FSM has ALREADY reached idle and the only
1809
+ // thing missing is the append-only transcript's final assistant turn (a native-source
1810
+ // race: claude-cli owns its history externally and the file write trails the idle
1811
+ // transition). `allowTimeout` is set ONLY on the missing_final_assistant block, and
1812
+ // ONLY for mesh worker sessions (meshNodeFor / meshActiveTaskId / launchedByCoordinator).
1813
+ // The coordinator's sole path to learn this session is idle is agent:generating_completed,
1814
+ // so holding it up to COMPLETED_FINALIZATION_MAX_WAIT_MS (30s) leaves the coordinator
1815
+ // false-generating while the worker is done. Decouple the idle NOTIFICATION from the
1816
+ // transcript evidence: emit the completion immediately, marked weak
1817
+ // (completionDiagnostic.blockReason=missing_final_assistant, finalAssistantPresent=false).
1818
+ // The finalSummary is enriched on a SEPARATE path — the mesh reconcile loop reads the
1819
+ // transcript once written and re-emits a GENUINE completion (CANON-B weak→genuine
1820
+ // upgrade; buildPendingEventFingerprint keeps weak and genuine distinct so the enriched
1821
+ // one still surfaces, and isFalseIdleCompletion keeps the direct dispatch active until
1822
+ // then). All OTHER blocks (genuinely-busy adapter/partial/parsed states, transient
1823
+ // parse_error) keep the existing terminal-hold / 30s-retry behavior unchanged.
1824
+ //
1825
+ // (SETTLE-VALLEY) Exception: a `holdForTranscript` block is the inter-approval idle
1826
+ // valley of a native-history mesh worker (waiting_approval→idle that will resume into
1827
+ // the next approval). It deliberately does NOT carry allowTimeout, so it falls into the
1828
+ // hold-and-retry path below (terminal:false) rather than the CANON-C immediate emit —
1829
+ // the retry loop re-runs the resume guard each cycle, so when the worker resumes the
1830
+ // pending completion is cancelled, and when the transcript's final assistant arrives the
1831
+ // block clears for a GENUINE emit. This blocks the truncated weak (insufficient) summary
1832
+ // from ever being emitted during the valley, without depending on the valley's length.
1833
+ const isTranscriptEvidenceGate = block.allowTimeout === true;
1834
+ LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} allowTimeout=${isTranscriptEvidenceGate} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
1835
+ if (!isTranscriptEvidenceGate && (block.terminal || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS)) {
824
1836
  if (pending.loggedBlockReason !== blockReason) {
825
1837
  LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
1838
+ // EVTTRACE: completion held by the finalization gate (CANON-C). Observation
1839
+ // only — does not change the hold decision above.
1840
+ if (this.isMeshWorkerSession()) {
1841
+ traceMeshEventDrop('completion_gate_hold', this.meshTraceCtx(), `${blockReason} waited=${waitedMs}ms`);
1842
+ }
826
1843
  pending.loggedBlockReason = blockReason;
827
1844
  }
828
1845
  this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
829
1846
  return;
830
1847
  }
831
- LOG.warn('CLI', `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1848
+ const emittedAfterFinalizationTimeout = waitedMs >= COMPLETED_FINALIZATION_MAX_WAIT_MS;
1849
+ const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
1850
+ blockReason,
1851
+ latestStatus,
1852
+ latestVisibleStatus,
1853
+ waitedMs,
1854
+ pending,
1855
+ emittedAfterFinalizationTimeout,
1856
+ });
1857
+ // Surface the CANON-C immediate-emit path distinctly so a delegated worker's idle
1858
+ // notification (transcript still pending) is not mistaken for a 30s-timeout fallback.
1859
+ (completionDiagnostic as Record<string, unknown>).decoupledImmediateEmit = isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout;
1860
+ LOG.warn('CLI', `[${this.type}] emitting completed event (${isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'CANON-C decoupled-immediate, transcript pending' : `after ${waitedMs}ms`}) without finalized assistant turn (${blockReason})`);
1861
+ // EVTTRACE: completion fired (forced past the finalization timeout / CANON-C decoupled-immediate).
1862
+ if (this.isMeshWorkerSession()) {
1863
+ traceMeshEventStage('fired', this.meshTraceCtx(), `forced after ${waitedMs}ms (${blockReason})`);
1864
+ }
1865
+ this.pushEvent({
1866
+ event: 'agent:generating_completed',
1867
+ chatTitle: pending.chatTitle,
1868
+ duration: pending.duration,
1869
+ timestamp: pending.timestamp,
1870
+ // ARCH-REFACTOR R1: attribute to the turn captured at idle-transition.
1871
+ ...(pending.taskId ? { taskId: pending.taskId } : {}),
1872
+ // When finalization is forced past the timeout on a `parsed_status:` block
1873
+ // (the parser never confirmed a final assistant turn) we previously rode an
1874
+ // empty `finalSummary` unconditionally. That empty value propagates to the
1875
+ // mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
1876
+ // delegated session's inbox preview blank — or, for a LOCAL worktree session,
1877
+ // stuck on the dispatched user task. If the parser DID surface assistant text,
1878
+ // prefer it; only fall back to '' when no assistant summary can be derived.
1879
+ finalSummary: blockReason.startsWith('parsed_status:')
1880
+ ? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages, pending.turnStartedAt) ?? '')
1881
+ : this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages, pending.turnStartedAt),
1882
+ completionDiagnostic,
1883
+ });
832
1884
  this.completedDebouncePending = null;
833
1885
  this.completedDebounceTimer = null;
834
1886
  this.generatingStartedAt = 0;
1887
+ this.lastApprovalEventFingerprint = '';
835
1888
  return;
836
1889
  }
837
1890
 
838
1891
  LOG.info('CLI', `[${this.type}] completed in ${pending.duration}s`);
1892
+ // EVTTRACE: completion fired (transcript finalized cleanly).
1893
+ if (this.isMeshWorkerSession()) {
1894
+ traceMeshEventStage('fired', this.meshTraceCtx(), `duration=${pending.duration}s`);
1895
+ }
839
1896
  this.pushEvent({
840
1897
  event: 'agent:generating_completed',
841
1898
  chatTitle: pending.chatTitle,
842
1899
  duration: pending.duration,
843
1900
  timestamp: pending.timestamp,
844
- finalSummary: extractFinalSummaryFromMessages(this.adapter?.getScriptParsedStatus()?.messages),
1901
+ // ARCH-REFACTOR R1: attribute to the turn captured at idle-transition.
1902
+ ...(pending.taskId ? { taskId: pending.taskId } : {}),
1903
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages, pending.turnStartedAt),
845
1904
  });
846
1905
  this.completedDebouncePending = null;
847
1906
  this.completedDebounceTimer = null;
848
1907
  this.generatingStartedAt = 0;
1908
+ this.lastApprovalEventFingerprint = '';
849
1909
  }
850
1910
 
851
1911
  private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
1912
+ // Manual-attendance suppression (provider-common): when a human is
1913
+ // actively driving this session from the dashboard, hold auto-approve so
1914
+ // the modal stays visible and they can pick a button / use the controlbar
1915
+ // themselves. Return false (NOT auto-approving) so getState keeps the
1916
+ // modal surfaced. Clear any in-progress settle gate — a genuine fire
1917
+ // after the window lapses must re-settle from scratch — and arm a
1918
+ // re-check for the lapse moment, because the PTY may have gone silent and
1919
+ // would otherwise never re-drive this decision. Background mesh workers
1920
+ // are never attended, so their delegated auto-approve is untouched.
1921
+ if (adapterStatus?.status === 'waiting_approval'
1922
+ && this.shouldAutoApprove()
1923
+ && this.manualAttendance.isAttended(now)) {
1924
+ this.lastAutoApprovalSignature = '';
1925
+ this.pendingAutoApprovalSignature = '';
1926
+ this.pendingAutoApprovalSince = 0;
1927
+ this.autoApproveInactiveSince = 0;
1928
+ // Manual attendance takes over — the modal stays surfaced (maybeAutoApproveStatus
1929
+ // returns false), so end the mask episode.
1930
+ this.autoApproveMaskSince = 0;
1931
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1932
+ this.autoApproveSettleTimer = setTimeout(() => {
1933
+ this.autoApproveSettleTimer = null;
1934
+ this.recheckAutoApproveSettled();
1935
+ }, this.manualAttendance.remainingMs(now) + 20);
1936
+ return false;
1937
+ }
852
1938
  const autoApproveActive = adapterStatus?.status === 'waiting_approval' && this.shouldAutoApprove();
853
1939
  // Guard re-entry: onStatusChange/getState can observe the same modal multiple
854
1940
  // times while the PTY absorbs the approval key. Without this flag, repeated
855
1941
  // 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);
1942
+ // However, Claude Code can present a second approval immediately after the
1943
+ // first. Resolve a changed modal signature even while the previous write is
1944
+ // still inside the short busy window.
1945
+ if (!autoApproveActive) {
1946
+ this.lastAutoApprovalSignature = '';
1947
+ // Hysteresis: if a settle gate is mid-progress, a momentary
1948
+ // status!=waiting_approval blip (a generating flip while the same
1949
+ // modal's button block is still on screen) must NOT wipe the settle
1950
+ // clock otherwise the modal→generating→modal flap restarts the
1951
+ // 600ms window every time and auto-approve never fires. Keep the
1952
+ // gate warm for AUTO_APPROVE_GATE_HYSTERESIS_MS; re-arm a timer so
1953
+ // that if the modal does NOT come back the gate is cleared on the
1954
+ // re-check (a genuine resolution → idle frees the gate normally).
1955
+ if (this.pendingAutoApprovalSince) {
1956
+ if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
1957
+ const goneForMs = now - this.autoApproveInactiveSince;
1958
+ if (goneForMs < CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS) {
1959
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1960
+ this.autoApproveSettleTimer = setTimeout(() => {
1961
+ this.autoApproveSettleTimer = null;
1962
+ this.recheckAutoApproveSettled();
1963
+ }, CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS - goneForMs + 20);
1964
+ return autoApproveActive;
1965
+ }
1966
+ }
1967
+ // Clear the settle gate so the next approval starts its own quiet
1968
+ // window from scratch (a stale timestamp would let it fire instantly).
1969
+ this.pendingAutoApprovalSignature = '';
1970
+ this.pendingAutoApprovalSince = 0;
1971
+ this.autoApproveInactiveSince = 0;
1972
+ // Modal has genuinely been gone past the hysteresis window → the episode ended;
1973
+ // end the mask episode too (a later approval starts a fresh stall clock).
1974
+ this.autoApproveMaskSince = 0;
1975
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1976
+ return autoApproveActive;
1977
+ }
1978
+ // Active approval observed — reset the inactivity tracker so a later
1979
+ // blip starts its hysteresis window fresh.
1980
+ this.autoApproveInactiveSince = 0;
1981
+ // STATUS-MISMATCH: start (or keep) the mask-stall clock for this episode. Set ONLY
1982
+ // when zero so it survives modal-signature changes and hysteresis blips — it measures
1983
+ // the true age of the unresolved auto-approve, not the per-signature settle window.
1984
+ if (!this.autoApproveMaskSince) this.autoApproveMaskSince = now;
1985
+ const modal = adapterStatus.activeModal;
1986
+ // (fix) Do not auto-approve when no concrete modal/buttons are present.
1987
+ // Claude TUI flaps between paints; without this guard adapterStatus
1988
+ // could report status=waiting_approval with activeModal=null (or with
1989
+ // an empty buttons array briefly) and we'd still call
1990
+ // resolveModal(-1) — which used to type "1" into the prompt
1991
+ // repeatedly. Skip until a real modal is captured.
1992
+ const buttons = Array.isArray(modal?.buttons)
1993
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
1994
+ : [];
1995
+ if (!modal || buttons.length === 0) {
1996
+ return autoApproveActive;
1997
+ }
1998
+ // Picker/confirm exclusion (provider-common). A /model or /mode picker is
1999
+ // surfaced with status=waiting_approval so the dashboard shows it, but it
2000
+ // has no "correct" answer to auto-pick — blindly selecting the first
2001
+ // option silently switches the model (the "always Opus, before I even
2002
+ // choose" bug). Two independent gates, BOTH must pass to fire:
2003
+ //
2004
+ // (1) modal_kind — the spec/FSM tells us this is an 'approval' modal,
2005
+ // not a 'picker'/'confirm'. A modal whose kind is unknown (legacy
2006
+ // adapter, or a spec that predates modal_kind) reads as 'approval'
2007
+ // so genuine approvals keep auto-approving; only an explicit
2008
+ // 'picker'/'confirm' is excluded here.
2009
+ // (2) structural anchor — a real approval offers an affirmative AND a
2010
+ // decline option (pickApprovalButton finds a positive that isn't a
2011
+ // decline, and hasNegativeApprovalOption confirms a No/Cancel/Deny
2012
+ // is present). A model picker ("1. Default 2. Opus 3. Sonnet")
2013
+ // has no decline, so even an un-migrated picker is caught here.
2014
+ //
2015
+ // Mirrors the SDK v1 detect-status approval heuristic (detect-status.ts).
2016
+ const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
2017
+ if (modalKind !== 'approval') {
2018
+ // Picker/confirm — leave it for the user; keep the modal surfaced.
2019
+ return autoApproveActive;
869
2020
  }
2021
+ const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
2022
+ if (buttonIndex < 0 || !hasNegativeApprovalOption(buttons)) {
2023
+ // No affirmative matched, or no decline option present (→ not a real
2024
+ // consent prompt, e.g. a picker that slipped past the kind gate).
2025
+ // Surface the modal so the user decides; never pick blindly.
2026
+ return autoApproveActive;
2027
+ }
2028
+ // Modal *identity* signature — the question/button set only, NO volatile
2029
+ // counters. This is what the settle gate tracks: the FSM bumps
2030
+ // approvalEntrySeq on every fresh waiting_approval entry, and a
2031
+ // modal→generating→modal flap (the question line scrolled out of the
2032
+ // captured frame while the button block stays) re-enters and bumps it
2033
+ // again. Folding that seq into the settle signature made the 600ms
2034
+ // settle clock restart on every flap, so the modal never stayed stable
2035
+ // long enough to fire — the gate was never satisfied. Identity excludes
2036
+ // the seq so button/seq flap of the SAME modal keeps one settle clock.
2037
+ const modalSignature = [
2038
+ typeof modal?.message === 'string' ? modal.message.trim() : '',
2039
+ buttons.join('|'),
2040
+ buttonIndex,
2041
+ ].join('::');
2042
+ // Busy-window re-entry guard still needs the seq: two DISTINCT
2043
+ // back-to-back approvals can carry identical message/buttons (common
2044
+ // with claude-cli). Without the seq their busy signatures collide and
2045
+ // the 5s busy-window guard below would swallow the second auto-approve,
2046
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
2047
+ // waiting_approval entry, so a new approval always yields a new busy
2048
+ // signature and fires through.
2049
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
2050
+ ? adapterStatus.approvalEntrySeq
2051
+ : 0;
2052
+ const busySignature = `${approvalEntrySeq}::${modalSignature}`;
2053
+ // Already fired for this exact modal entry and still inside the busy
2054
+ // window — nothing to do (re-entry guard for repeated snapshots of one
2055
+ // modal).
2056
+ if (this.autoApproveBusy && busySignature === this.lastAutoApprovalSignature) {
2057
+ return autoApproveActive;
2058
+ }
2059
+
2060
+ // Settle gate: only fire once this modal identity has been stable for
2061
+ // AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
2062
+ // message/buttons each frame → new identity → clock restarts, so we
2063
+ // never approve a half-rendered prompt (the "resolves too fast" bug).
2064
+ if (modalSignature !== this.pendingAutoApprovalSignature) {
2065
+ this.pendingAutoApprovalSignature = modalSignature;
2066
+ this.pendingAutoApprovalSince = now;
2067
+ }
2068
+ const settledForMs = now - this.pendingAutoApprovalSince;
2069
+ if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
2070
+ // Not yet settled. Arm a timer to re-check after the remaining quiet
2071
+ // window — the PTY may go silent once the prompt finishes painting,
2072
+ // so there is no guaranteed status-change frame to re-drive us.
2073
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
2074
+ this.autoApproveSettleTimer = setTimeout(() => {
2075
+ this.autoApproveSettleTimer = null;
2076
+ this.recheckAutoApproveSettled();
2077
+ }, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
2078
+ return autoApproveActive;
2079
+ }
2080
+
2081
+ // Settled — fire the approve key.
2082
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
2083
+ this.autoApproveBusy = true;
2084
+ this.lastAutoApprovalSignature = busySignature;
2085
+ this.pendingAutoApprovalSignature = '';
2086
+ this.pendingAutoApprovalSince = 0;
2087
+ this.autoApproveInactiveSince = 0;
2088
+ // Fired (resolveModal in flight) — the episode resolved; end the mask-stall clock.
2089
+ this.autoApproveMaskSince = 0;
2090
+ if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
2091
+ this.autoApproveBusyTimer = setTimeout(() => {
2092
+ this.autoApproveBusy = false;
2093
+ this.autoApproveBusyTimer = null;
2094
+ this.lastAutoApprovalSignature = '';
2095
+ }, 5000);
2096
+ this.recordAutoApproval(modal?.message, buttonLabel, now);
2097
+ setTimeout(() => {
2098
+ this.adapter.resolveModal(buttonIndex);
2099
+ }, 0);
870
2100
  return autoApproveActive;
871
2101
  }
872
2102
 
2103
+ /**
2104
+ * Re-drive the auto-approve check after the settle quiet window elapses.
2105
+ * The PTY may have gone silent once the approval prompt finished painting,
2106
+ * so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
2107
+ * — this timer-driven re-check picks up the now-settled modal and fires.
2108
+ * Deliberately lighter than detectStatusTransition(): it only re-evaluates
2109
+ * the approval decision; the next real PTY frame refreshes visible status.
2110
+ */
2111
+ private recheckAutoApproveSettled(): void {
2112
+ try {
2113
+ // APPROVAL Defect-C (auto-approve gap): re-probe with a LIVE parse, not the cached
2114
+ // engine snapshot. This timer is the ONLY re-drive when the PTY goes silent after the
2115
+ // approval prompt finishes painting (its whole reason to exist) — but with
2116
+ // allowParse:false it read only engine.activeModal, which the engine's per-frame settle
2117
+ // pass can leave null/stale when the modal arrived between writes. The re-check then saw
2118
+ // no modal and never fired, so the delegated worker's transient/quiet approval was missed
2119
+ // and the coordinator had to step in with a manual mesh_approve. allowParse:true makes
2120
+ // getStatus re-run runDetectStatus/runParseApproval on the current screen buffer (the same
2121
+ // live re-probe the coordinator's resolveAction path uses), recovering the modal so
2122
+ // auto-approve fires on its own. The half-rendered-frame guard (buttons.length===0) and
2123
+ // the settle gate in maybeAutoApproveStatus still protect against firing on a partial modal.
2124
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
2125
+ this.maybeAutoApproveStatus(adapterStatus, Date.now());
2126
+ } catch { /* adapter gone / transient — next frame retries */ }
2127
+ }
2128
+
2129
+ /**
2130
+ * Emit the queue-claim agent:ready event at most once per session. Both the
2131
+ * boot-time starting→idle one-shot and the fsmReadySeen re-arm call this; the
2132
+ * agentReadyEmitted guard ensures the second caller is a no-op so a worker is
2133
+ * never claimed twice and a queued task is never double-dispatched.
2134
+ */
2135
+ private emitAgentReadyOnce(chatTitle: string, now: number): void {
2136
+ if (this.agentReadyEmitted) return;
2137
+ this.agentReadyEmitted = true;
2138
+ this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
2139
+ }
2140
+
2141
+ /**
2142
+ * GENERATING-BOUNDARY synthetic emit for a first turn that started AND finished
2143
+ * inside the startup-grace window without the FSM ever observing a 'generating'
2144
+ * frame (an unobservably-fast turn). Synthesizes the agent:generating_started +
2145
+ * agent:generating_completed pair so the mesh coordinator learns the worker went
2146
+ * idle. Returns true iff it synthesized.
2147
+ *
2148
+ * Two callers share this defense line:
2149
+ * - 'startup_grace_fast_collapse' — the starting→idle transition (the FSM whose
2150
+ * spec lacks/hadn't-synced the starting→busy edge collapses starting→idle
2151
+ * directly, with no intervening 'generating' frame).
2152
+ * - 'startup_grace_idle_turn_collapse' — the idle→idle no-status-change poll
2153
+ * (the launch settle already drained starting→idle BEFORE the first turn, so
2154
+ * the turn runs+completes while status stays 'idle' the whole time and
2155
+ * detectStatusTransition never re-enters its change block — the live rc.403
2156
+ * Probe1 miss).
2157
+ *
2158
+ * False-positive safety (must NOT fire on a benign boot): currentTurnTaskId is
2159
+ * set ONLY by onTurnStarted (a real turn STARTED this boot) and persists past
2160
+ * completion, so it excludes a true idle boot (null) and a queued-pending first
2161
+ * turn that only runs after grace (onTurnStarted not yet called → null).
2162
+ * !hasAdapterPendingResponse() excludes a turn still mid-flight. generating
2163
+ * never armed (generatingStartedAt===0 && !generatingDebouncePending) means the
2164
+ * whole idle→busy→idle never happened for this turn. The once-per-turn guard
2165
+ * (fastCollapseSynthesizedTaskId) keeps the re-polled idle-stayed caller from
2166
+ * re-emitting every poll.
2167
+ */
2168
+ private maybeSynthesizeStartupGraceCollapse(
2169
+ chatTitle: string,
2170
+ now: number,
2171
+ reason: 'startup_grace_fast_collapse' | 'startup_grace_idle_turn_collapse',
2172
+ ): boolean {
2173
+ const startedTurnTaskId = typeof (this.adapter as any)?.currentTurnTaskId === 'string'
2174
+ && (this.adapter as any).currentTurnTaskId.trim()
2175
+ ? (this.adapter as any).currentTurnTaskId as string
2176
+ : undefined;
2177
+ const fastCollapsed = !!startedTurnTaskId
2178
+ && !this.hasAdapterPendingResponse()
2179
+ && !this.generatingStartedAt
2180
+ && !this.generatingDebouncePending;
2181
+ if (!fastCollapsed) return false;
2182
+ // Once-per-turn: the idle-stayed caller re-polls steadily while the session
2183
+ // sits idle; without this guard it would re-emit the pair every poll.
2184
+ if (this.fastCollapseSynthesizedTaskId === startedTurnTaskId) return false;
2185
+
2186
+ let fcFinalSummary: string | undefined;
2187
+ let fcEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
2188
+ try {
2189
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
2190
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
2191
+ fcEvidenceSource = evidence.source;
2192
+ fcFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
2193
+ } catch { /* best-effort */ }
2194
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || fcEvidenceSource === 'external-native') && !fcFinalSummary;
2195
+ // Mirror the short-generating idle path's suppression: a provider that
2196
+ // requires a final assistant (or external-native history) with NO confirmed
2197
+ // summary and NO mesh context emits nothing — the session is idle with no
2198
+ // confirmed turn, matching startup-blip semantics. With mesh context we still
2199
+ // emit so the coordinator can apply its own timeout/retry logic. Left UNMARKED
2200
+ // so a later poll can retry once the transcript's final assistant lands.
2201
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
2202
+ if (missingEvidence && !hasMeshContext) {
2203
+ LOG.info('CLI', `[${this.type}] ${reason} suppressed: missing final assistant evidence, no mesh context (source=${fcEvidenceSource})`);
2204
+ return false;
2205
+ }
2206
+ // Mark BEFORE emitting so a re-entrant poll cannot double-fire.
2207
+ this.fastCollapseSynthesizedTaskId = startedTurnTaskId;
2208
+ LOG.info('CLI', `[${this.type}] ${reason}: synthesizing started+completed (taskId=${startedTurnTaskId} source=${fcEvidenceSource} hadFinalSummary=${!!fcFinalSummary})`);
2209
+ // Retroactive started so the started→completed pair (and the chat bubble) is
2210
+ // well-formed; pushEvent stamps the per-turn taskId for CANON-B ack.
2211
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now });
2212
+ if (this.isMeshWorkerSession()) {
2213
+ traceMeshEventStage('fired', this.meshTraceCtx(), `${reason} (source=${fcEvidenceSource})`);
2214
+ }
2215
+ this.pushEvent({
2216
+ event: 'agent:generating_completed',
2217
+ chatTitle,
2218
+ duration: 0,
2219
+ timestamp: now,
2220
+ finalSummary: fcFinalSummary,
2221
+ completionDiagnostic: {
2222
+ reason,
2223
+ finalAssistantEvidenceSource: fcEvidenceSource,
2224
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
2225
+ },
2226
+ });
2227
+ return true;
2228
+ }
2229
+
873
2230
  private detectStatusTransition(): void {
874
2231
  const now = Date.now();
875
2232
  // Status-change handling is a hot path: PTY output can fire it many times
876
2233
  // during long-running CLI sessions. Keep this path on adapter-owned light
877
2234
  // state only; rich provider parsing is reserved for getState/read_chat.
878
2235
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
2236
+ const adapterProviderSessionId = normalizeProviderSessionId(
2237
+ this.provider,
2238
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
2239
+ );
2240
+ if (adapterProviderSessionId) {
2241
+ this.promoteProviderSessionId(adapterProviderSessionId);
2242
+ }
879
2243
  const parsedStatus = null;
880
2244
  const rawStatus = adapterStatus.status;
881
2245
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
882
- const newStatus = autoApproveActive ? 'generating' : rawStatus;
883
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
2246
+ // During the autoApproveBusy window (2s after firing approval key), the PTY
2247
+ // can briefly report 'idle' before the next generating phase starts. Treat that
2248
+ // transient idle as 'generating' to suppress a spurious agent:generating_completed
2249
+ // push notification. The adapter's status is otherwise authoritative — native
2250
+ // transcript shape does NOT override the FSM's busy/idle decision.
2251
+ const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
2252
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
2253
+ const dirName = workingDirBasename(this.workingDir);
884
2254
  const chatTitle = `${this.provider.name} · ${dirName}`;
885
2255
  const partial = this.adapter.getPartialResponse();
2256
+ // Liveness fingerprint for the no-progress watchdog. The parsed
2257
+ // assistant buffer (`partial`) alone goes static while a tool/build runs
2258
+ // — the assistant emits no tokens even though the PTY is actively
2259
+ // printing tool output — which made the watchdog false-fire a "stuck"
2260
+ // alert mid-turn. Fold in the adapter's raw-activity timestamps so any
2261
+ // visible terminal progress (lastScreenChangeAt) or raw PTY byte
2262
+ // (lastOutputAt) keeps the fingerprint moving. The watchdog then only
2263
+ // survives a genuine stall where nothing at all is happening.
886
2264
  const progressFingerprint = newStatus === 'generating'
887
- ? `${partial || ''}`.slice(-2000)
2265
+ ? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
888
2266
  : undefined;
889
2267
 
890
2268
  const previousStatus = this.lastStatus;
891
2269
  if (newStatus !== this.lastStatus) {
892
2270
  LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
893
- if (this.lastStatus === 'idle' && newStatus === 'generating') {
2271
+ // GENERATING-MISSING (win32 fresh-worktree first-turn): a freshly-launched session
2272
+ // is in 'starting' until its startup-grace settles to idle. When the FIRST inject
2273
+ // lands inside that grace window, the adapter can report status DIRECTLY
2274
+ // starting → generating without an intervening 'idle' frame for
2275
+ // detectStatusTransition() to observe. Previously only the idle→generating arm
2276
+ // armed the bookkeeping, so a starting→generating frame fell straight through to the
2277
+ // bare `this.lastStatus = newStatus` update: generatingStartedAt stayed 0 and no
2278
+ // generating_started was queued. The fast turn's generating→idle completion was then
2279
+ // suppressed by the startup-blip guard below (generatingStartedAt===0 &&
2280
+ // !generatingDebouncePending) — so NO generating_started AND NO generating_completed
2281
+ // ever fired and the mesh coordinator never learned the worker went idle.
2282
+ //
2283
+ // We extend the idle→generating arm to also fire on starting→generating, BUT ONLY
2284
+ // when a real turn is in flight. The adapter script can also report 'generating' from
2285
+ // pure startup PTY noise (no task dispatched) — antigravity/codex/hermes-cli all
2286
+ // exercise that benign starting→generating→idle blip, which must NOT emit a
2287
+ // completion (see "startup-phase spurious completion suppression" tests).
2288
+ // hasAdapterPendingResponse() is the discriminator: a genuine inject sets the
2289
+ // adapter's isWaitingForResponse / currentTurnScope (or leaves a partial response),
2290
+ // whereas startup repaint noise leaves all of them empty. So an armed
2291
+ // starting→generating means "the worker actually started its first turn", and a
2292
+ // bare one stays a suppressed blip via the existing fall-through.
2293
+ const startingToGeneratingWithActiveTurn = this.lastStatus === 'starting'
2294
+ && newStatus === 'generating'
2295
+ && this.hasAdapterPendingResponse();
2296
+ if (((this.lastStatus === 'idle' && newStatus === 'generating') || startingToGeneratingWithActiveTurn)) {
2297
+ // If a completion event is already pending and the turn has ended
2298
+ // (generatingStartedAt===0), the PTY is painting its prompt area
2299
+ // after completing. Ignore this blip — do not cancel the pending
2300
+ // completion and do not advance lastStatus to generating. (On a true
2301
+ // starting→generating the session is fresh: completedDebouncePending is
2302
+ // null, so this blip guard is a no-op and we arm normally below.)
2303
+ if (this.completedDebouncePending && this.generatingStartedAt === 0) {
2304
+ LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
2305
+ return;
2306
+ }
894
2307
  this.suppressIdleHistoryReplay = false;
895
2308
  // Cancel any pending completed event (multi-step: idle→generating resume)
896
2309
  if (this.completedDebouncePending) {
897
- LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
2310
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
898
2311
  if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
899
2312
  this.completedDebouncePending = null;
900
2313
  }
@@ -926,10 +2339,29 @@ export class CliProviderInstance implements ProviderInstance {
926
2339
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
927
2340
  const modal = adapterStatus.activeModal;
928
2341
  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;
2342
+ // Include the FSM's approval entry seq, mirroring the auto-approve
2343
+ // path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
2344
+ // guard. Two distinct back-to-back approvals can carry identical
2345
+ // message/buttons (very common with claude-cli's "Allow Bash
2346
+ // command?"). Without the seq their fingerprints collide and the dedup
2347
+ // below silently drops the second waiting_approval event — it is never
2348
+ // emitted, so it cannot even land in the pending inbox for a later
2349
+ // read_chat reconcile to recover. The seq is bumped by the FSM on every
2350
+ // fresh waiting_approval entry, so a new approval always yields a new
2351
+ // fingerprint and emits.
2352
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
2353
+ ? adapterStatus.approvalEntrySeq
2354
+ : 0;
2355
+ const approvalFingerprint = JSON.stringify({
2356
+ message: typeof modal?.message === 'string' ? modal.message.trim() : '',
2357
+ buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
2358
+ seq: approvalEntrySeq,
2359
+ });
2360
+ // PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
2361
+ // Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
2362
+ // (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
2363
+ if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
2364
+ this.lastApprovalEventFingerprint = approvalFingerprint;
933
2365
  this.appendRuntimeSystemMessage(
934
2366
  this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
935
2367
  `approval_request:${now}`,
@@ -941,22 +2373,183 @@ export class CliProviderInstance implements ProviderInstance {
941
2373
  modalButtons: modal?.buttons,
942
2374
  });
943
2375
  }
2376
+ } else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
2377
+ // Approval resolved and the agent resumed work. Defense-in-depth:
2378
+ // clear the approval emit fingerprint here too (not only on
2379
+ // completion at scheduleCompletedDebounceFlush). A subsequent
2380
+ // waiting_approval with the same modal content as the one just
2381
+ // resolved would otherwise collide with the stale fingerprint and be
2382
+ // dropped. The seq in the fingerprint already separates entries; this
2383
+ // reset is a belt-and-suspenders guard for the re-entry case.
2384
+ this.lastApprovalEventFingerprint = '';
944
2385
  } else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
945
2386
  const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
946
- // If debounce still pending (generating lasted < 1s), cancel both events
2387
+ // Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
2388
+ // was entered from 'starting' state (startup PTY noise), not from a real idle→generating
2389
+ // task dispatch. The idle→generating handler is the only code path that sets
2390
+ // generatingStartedAt and generatingDebouncePending, so both being absent means no
2391
+ // task was ever dispatched. Suppress the spurious completion event and fall through
2392
+ // to a simple lastStatus update.
2393
+ if (!this.generatingStartedAt && !this.generatingDebouncePending) {
2394
+ LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
2395
+ } else
2396
+ // If debounce still pending (generating lasted < 1s), cancel both UI events.
2397
+ // Still emit agent:generating_completed so mesh orchestration can record
2398
+ // task_completed for direct dispatches that complete faster than the debounce.
947
2399
  if (this.generatingDebouncePending) {
948
- LOG.info('CLI', `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
2400
+ // NOTIF Defect-2a: shortDurationMs is the REPORTED turn duration, so it must be
2401
+ // measured from the IMMUTABLE turn start — not generatingStartedAt, which is
2402
+ // reset to 0 on every mid-turn waiting_approval/idle blip (see :1864/1885/2397/
2403
+ // 2503/2521) and re-armed on the next →generating, so a long turn that blipped
2404
+ // would measure only the final 1.5-2.5s sliver. engine.currentTurnStartedAt is
2405
+ // stamped once at onTurnStarted and persists past mid-turn blips until the next
2406
+ // turn starts, so it captures the true turn length. generatingStartedAt remains
2407
+ // the fallback (and the debounce itself stays a pure UI-suppression signal,
2408
+ // decoupled from the reported duration).
2409
+ const { durationMs: shortDurationMs, anchor: durationAnchor } = computeTurnAnchoredDurationMs(
2410
+ (this.adapter as any)?.currentTurnStartedAt,
2411
+ this.generatingStartedAt,
2412
+ now,
2413
+ );
2414
+ LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms, anchor=${durationAnchor})`);
949
2415
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
2416
+ // Emit completion for mesh task association even though the UI generating
2417
+ // started/completed pair is suppressed (too short for visible UI update).
2418
+ let shortFinalSummary: string | undefined;
2419
+ let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
2420
+ try {
2421
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
2422
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
2423
+ shortEvidenceSource = evidence.source;
2424
+ shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
2425
+ } catch { /* best-effort */ }
2426
+ // If a real response is confirmed, retroactively emit started so the chat
2427
+ // bubble appears even though the debounce suppressed the original event.
2428
+ if (shortFinalSummary) {
2429
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
2430
+ }
950
2431
  this.generatingDebouncePending = null;
951
2432
  this.generatingStartedAt = 0;
2433
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
2434
+ if (missingEvidence) {
2435
+ LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
2436
+ }
2437
+ // When evidence is missing and there is no active mesh task context, suppress
2438
+ // the completion event. Providers with requiresFinalAssistantBeforeIdle or
2439
+ // external-native history must confirm a final assistant message before the
2440
+ // coordinator records task_completed. Only emit here if a mesh task is active
2441
+ // so the coordinator can apply its own timeout/retry logic.
2442
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
2443
+ if (missingEvidence && !hasMeshContext) {
2444
+ LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
2445
+ // completedDebouncePending intentionally left null — the session is now idle
2446
+ // with no confirmed turn, matching the startup-blip suppression semantics.
2447
+ // (No EvtTrace: not a mesh session, so nothing routes to a coordinator.)
2448
+ } else {
2449
+ // EVTTRACE: completion fired (short-generating idle path).
2450
+ if (this.isMeshWorkerSession()) {
2451
+ traceMeshEventStage('fired', this.meshTraceCtx(), `short-generating idle (source=${shortEvidenceSource})`);
2452
+ }
2453
+ this.pushEvent({
2454
+ event: 'agent:generating_completed',
2455
+ chatTitle,
2456
+ duration: 0,
2457
+ timestamp: now,
2458
+ finalSummary: shortFinalSummary,
2459
+ completionDiagnostic: {
2460
+ reason: 'short_generating_suppressed',
2461
+ shortDurationMs,
2462
+ finalAssistantEvidenceSource: shortEvidenceSource,
2463
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
2464
+ },
2465
+ });
2466
+ }
952
2467
  } else {
953
2468
  // Debounce completed, then require the rich transcript path that read_chat
954
2469
  // 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);
2470
+ this.completedDebouncePending = {
2471
+ chatTitle,
2472
+ duration,
2473
+ timestamp: now,
2474
+ firstObservedAt: now,
2475
+ previousStatus: this.lastStatus,
2476
+ // ARCH-REFACTOR R1: snapshot the completing turn's taskId NOW (sync),
2477
+ // before any follow-up task's flush can start a new turn and move
2478
+ // engine.currentTurnTaskId.
2479
+ ...(this.completingTurnTaskId() ? { taskId: this.completingTurnTaskId() } : {}),
2480
+ // NOTIF Defect-B: snapshot the producing turn's START instant NOW, for the
2481
+ // same reason as taskId — a follow-up turn moves engine.currentTurnStartedAt.
2482
+ // Prefer the engine's per-turn start (set at onTurnStarted, earliest reliable
2483
+ // anchor) and fall back to generatingStartedAt (when generating was observed).
2484
+ ...((() => {
2485
+ const engineTurnStart = typeof (this.adapter as any)?.currentTurnStartedAt === 'number'
2486
+ && Number.isFinite((this.adapter as any).currentTurnStartedAt)
2487
+ ? (this.adapter as any).currentTurnStartedAt as number
2488
+ : 0;
2489
+ const turnStartedAt = engineTurnStart || this.generatingStartedAt || 0;
2490
+ return turnStartedAt ? { turnStartedAt } : {};
2491
+ })()),
2492
+ };
2493
+ const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
2494
+ // (FALSEIDLE-BGCHILD-a) Native-history providers flush immediately (the
2495
+ // transcript is authoritative). For mesh worker sessions, give the
2496
+ // generating→idle transition a short settle window so a background-child
2497
+ // false idle (quiet after a backgrounded test/command while the parent turn
2498
+ // continues) gets caught by the resume guard in flushCompletedDebounceIfFinalized
2499
+ // instead of firing an early completion the coordinator can never correct.
2500
+ const meshWorkerSession = this.isMeshWorkerSession();
2501
+ const flushDelay = ownsExternalHistory
2502
+ ? (meshWorkerSession ? NATIVE_HISTORY_MESH_IDLE_SETTLE_MS : 0)
2503
+ : 3000;
2504
+ LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} meshWorker=${meshWorkerSession} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
2505
+ this.scheduleCompletedDebounceFlush(flushDelay);
957
2506
  }
958
2507
  } else if (newStatus === 'idle' && this.lastStatus === 'starting') {
959
- this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
2508
+ this.emitAgentReadyOnce(chatTitle, now);
2509
+ // GENERATING-BOUNDARY (R4c): stamp the collapse moment ONCE so the
2510
+ // idle-stayed window below is anchored on the startup-grace collapse,
2511
+ // not on boot. Set only the first time so a later starting re-entry
2512
+ // cannot slide the window forward.
2513
+ if (this.startupGraceCollapseAt === null) this.startupGraceCollapseAt = now;
2514
+ // GENERATING-BOUNDARY fast-collapse (R4, win32 startup-grace first turn):
2515
+ // a turn dispatched into the startup-grace window can START and FINISH while
2516
+ // the FSM is still in 'starting'. On a daemon whose claude-cli spec has NOT yet
2517
+ // synced the starting→busy edge (the primary cure lives in the spec's
2518
+ // idle→busy.from), the FSM never reaches 'busy'/generating, so
2519
+ // detectStatusTransition observes starting→idle DIRECTLY with no intervening
2520
+ // 'generating' frame. The idle→generating arm — the only path that sets
2521
+ // generatingStartedAt and arms the completion — never fired, so the completing
2522
+ // turn's agent:generating_completed is never emitted and the mesh coordinator
2523
+ // never learns the worker went idle. Synthesize the started+completed pair here.
2524
+ //
2525
+ // Discriminator (false-positive safe — must NOT fire on a benign boot):
2526
+ // adapter.currentTurnTaskId is set ONLY by onTurnStarted (a real turn STARTED
2527
+ // this boot) and persists past completion, so it cleanly separates the three
2528
+ // non-firing cases — a true idle boot (no turn → null), a queued-pending
2529
+ // first turn that only runs AFTER startup-grace drains the composer (onTurnStarted
2530
+ // not yet called → null; it completes normally later via idle→busy→idle), and a
2531
+ // turn STILL running at the 8s mark (hasAdapterPendingResponse() still true →
2532
+ // excluded so we don't fire a premature mid-turn completion; idle→busy self-
2533
+ // corrects once the FSM reaches idle). We fire only when a turn started AND has
2534
+ // already finished: started-this-boot && !still-in-flight.
2535
+ this.maybeSynthesizeStartupGraceCollapse(chatTitle, now, 'startup_grace_fast_collapse');
2536
+ } else if (newStatus === 'error') {
2537
+ if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
2538
+ this.generatingDebouncePending = null;
2539
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2540
+ this.completedDebouncePending = null;
2541
+ this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
2542
+ this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
2543
+ this.pushEvent({
2544
+ event: 'agent:stopped',
2545
+ chatTitle,
2546
+ timestamp: now,
2547
+ finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
2548
+ completionDiagnostic: {
2549
+ reason: adapterStatus.errorReason || 'provider_error',
2550
+ errorMessage: adapterStatus.errorMessage || undefined,
2551
+ },
2552
+ });
960
2553
  } else if (newStatus === 'stopped') {
961
2554
  // Cancel any pending debounce
962
2555
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
@@ -968,6 +2561,79 @@ export class CliProviderInstance implements ProviderInstance {
968
2561
  this.lastStatus = newStatus;
969
2562
  }
970
2563
 
2564
+ // GENERATING-BOUNDARY idle-stayed collapse (R4b): the starting→idle
2565
+ // fast-collapse arm above only fires when the FIRST turn itself drives the
2566
+ // starting→idle transition. When the launch settle already drained
2567
+ // starting→idle BEFORE the first turn arrives, the session is already 'idle'
2568
+ // and a turn that runs+completes inside the startup-grace window — too fast
2569
+ // for any poll to observe a 'generating' frame — produces NO status change
2570
+ // at all (idle→idle). detectStatusTransition's change block above is skipped
2571
+ // entirely, so neither the idle→generating arm nor the starting→idle
2572
+ // fast-collapse arm ever runs, and the mesh coordinator never learns the
2573
+ // worker went idle (the live rc.403 Probe1 miss). Catch it here: an
2574
+ // already-idle poll (no status change), still inside the startup-grace
2575
+ // window, where a turn started this boot and has already finished without
2576
+ // ever arming generating. The same false-positive-safe discriminators apply
2577
+ // (currentTurnTaskId set && !pending && generating never armed), plus a
2578
+ // once-per-turn guard since this branch is re-polled while the session sits
2579
+ // idle. Normal turns that DO reach 'busy' set generatingStartedAt and are
2580
+ // excluded; a queued-pending first turn that only runs after grace falls
2581
+ // outside the window and completes normally via idle→busy→idle.
2582
+ //
2583
+ // R4d (the live rc.405 Probe2 miss): R4c anchored the window on the collapse
2584
+ // moment but still measured its END against `now` (the poll/completion time). The
2585
+ // helper only fires once the turn has FINISHED (!hasAdapterPendingResponse()), so
2586
+ // the first eligible poll happens at completion. When the first turn is dispatched
2587
+ // a few seconds after the collapse AND runs for a non-trivial duration, that
2588
+ // completion lands PAST the 12s now-anchored window even though the turn was a
2589
+ // genuine startup-grace first turn (live: collapse→dispatch +5.2s, turn ~11s →
2590
+ // completion at collapse+16.2s > 12s). Anchor the window on when the first turn
2591
+ // STARTED (engine.currentTurnStartedAt, set by onTurnStarted) instead: a turn that
2592
+ // STARTED within the collapse window is a startup-grace first turn no matter how
2593
+ // long it then ran. The now-anchored check is retained as a union so a fast turn
2594
+ // (dispatched+completed quickly within 12s of collapse) keeps firing too; both
2595
+ // close for a much-later turn, preserving the "don't mislabel a late fast turn"
2596
+ // honesty the window exists for.
2597
+ const firstTurnStartedAt = typeof (this.adapter as any)?.currentTurnStartedAt === 'number'
2598
+ ? (this.adapter as any).currentTurnStartedAt as number
2599
+ : 0;
2600
+ const collapsedAt = this.startupGraceCollapseAt;
2601
+ const turnStartedWithinCollapseWindow = collapsedAt !== null
2602
+ && firstTurnStartedAt > 0
2603
+ && firstTurnStartedAt >= collapsedAt
2604
+ && (firstTurnStartedAt - collapsedAt) < STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS;
2605
+ const nowWithinCollapseWindow = collapsedAt !== null
2606
+ && (now - collapsedAt) < STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS;
2607
+ if (
2608
+ newStatus === 'idle'
2609
+ && previousStatus === 'idle'
2610
+ && (turnStartedWithinCollapseWindow || nowWithinCollapseWindow)
2611
+ ) {
2612
+ this.maybeSynthesizeStartupGraceCollapse(chatTitle, now, 'startup_grace_idle_turn_collapse');
2613
+ }
2614
+
2615
+ // Re-arm the queue-claim agent:ready on the FSM's first GENUINE ready.
2616
+ //
2617
+ // The boot-time starting→idle one-shot above is the historical claim
2618
+ // trigger, but it is consumed too early for FSM-spec providers whose
2619
+ // INITIAL state already reports status 'idle' (e.g. antigravity-cli): the
2620
+ // adapter reports idle before maybeMarkReady has fired, so lastStatus
2621
+ // advances starting→idle while the prompt is not yet drawn and the worker
2622
+ // cannot yet claim. Subsequent state-driven idle frames are idle→idle (no
2623
+ // status change), so the one-shot never re-fires and the worker strands its
2624
+ // queued task — the coordinator then relaunch-loops every ~90s.
2625
+ //
2626
+ // The adapter surfaces fsmReadySeen=true exactly when the FSM reaches its
2627
+ // first non-initial idle (the prompt is genuinely up). On that signal we
2628
+ // emit agent:ready once more. emitAgentReadyOnce is idempotent (guarded by
2629
+ // agentReadyEmitted), so providers whose boot one-shot already landed on a
2630
+ // real ready (claude-cli / codex-cli / hermes-cli, which use a startup
2631
+ // grace and whose initial state is not idle) treat this as a no-op — no
2632
+ // double claim, no double task injection.
2633
+ if (newStatus === 'idle' && adapterStatus.fsmReadySeen === true && !this.agentReadyEmitted) {
2634
+ this.emitAgentReadyOnce(chatTitle, now);
2635
+ }
2636
+
971
2637
  this.applyProviderResponse(parsedStatus, {
972
2638
  phase: (newStatus === 'idle' && (previousStatus === 'generating' || previousStatus === 'waiting_approval'))
973
2639
  ? 'turn_completed'
@@ -976,8 +2642,43 @@ export class CliProviderInstance implements ProviderInstance {
976
2642
 
977
2643
  // Monitor check (cooldown based notification, IDE/CLI common)
978
2644
  const agentKey = `${this.type}:cli`;
979
- const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint);
2645
+ // Approval pending is detected from the raw adapter status, not `newStatus`:
2646
+ // auto-approve synthesizes `waiting_approval` → 'generating', which would
2647
+ // otherwise let the no-progress watchdog accumulate the approval wait.
2648
+ const approvalPending = rawStatus === 'waiting_approval';
2649
+ const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
2650
+ const monitorParsedStatus: any = parsedStatus;
980
2651
  for (const me of monitorEvents) {
2652
+ if (
2653
+ me.type === 'monitor:no_progress'
2654
+ && this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
2655
+ && !this.hasAdapterPendingResponse()
2656
+ && !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
2657
+ ) {
2658
+ // EVTTRACE: completion fired (no-progress monitor reconciled to completion).
2659
+ if (this.isMeshWorkerSession()) {
2660
+ traceMeshEventStage('fired', this.meshTraceCtx(), 'no_progress_monitor_final_summary');
2661
+ }
2662
+ this.pushEvent({
2663
+ event: 'agent:generating_completed',
2664
+ chatTitle,
2665
+ duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
2666
+ timestamp: me.timestamp,
2667
+ finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
2668
+ completionDiagnostic: {
2669
+ providerType: this.type,
2670
+ sessionId: this.instanceId,
2671
+ providerSessionId: this.providerSessionId || null,
2672
+ reconciliationReason: 'no_progress_monitor_final_summary',
2673
+ finalAssistantPresent: true,
2674
+ },
2675
+ });
2676
+ this.generatingStartedAt = 0;
2677
+ // Cancel any pending debounce flush — monitor already fired completion.
2678
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2679
+ this.completedDebouncePending = null;
2680
+ continue;
2681
+ }
981
2682
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
982
2683
  }
983
2684
  }
@@ -997,15 +2698,61 @@ export class CliProviderInstance implements ProviderInstance {
997
2698
  workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
998
2699
  ? event.workspaceName
999
2700
  : this.workingDir,
2701
+ // Carry the workspace under BOTH `workspace` and `workspaceName` so the
2702
+ // downstream mesh forward/merge path — which reads `workspace` — can
2703
+ // propagate it to the coordinator snapshot. Without `workspace` the live
2704
+ // event path delivers an empty workspace and the dashboard falls back to
2705
+ // the generic "Terminal (Mesh Node)" title.
2706
+ workspace: typeof event.workspace === 'string' && event.workspace.trim()
2707
+ ? event.workspace
2708
+ : this.workingDir,
1000
2709
  providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
1001
2710
  ? event.providerSessionId
1002
2711
  : this.providerSessionId,
1003
2712
  };
2713
+ // TASKIDLESS: stamp the mesh task primary key on lifecycle events emitted by
2714
+ // a mesh worker session. The consumer (updateDirectDispatchStatus) was switched
2715
+ // to key on task_id (CANON-B), but the producer never carried it — so every
2716
+ // forwarded metadataEvent.taskId arrived undefined and the coordinator fell back
2717
+ // to a session_id match, which can flip a sibling dispatch row. Surface it here so
2718
+ // updateDirectDispatchStatus hits the exact PK row and the session_id fallback is
2719
+ // never exercised. Non-mesh sessions get no taskId (regression guard) —
2720
+ // isMeshWorkerSession() gates the injection.
2721
+ //
2722
+ // ARCH-REFACTOR R1 (per-turn identity): resolution order is
2723
+ // (1) an explicit taskId already on the event — the debounce-flush completion
2724
+ // path stamps the taskId captured at the generating→idle transition (the
2725
+ // turn that actually produced this completion);
2726
+ // (2) the per-turn binding (engine.currentTurnTaskId) for synchronously-emitted
2727
+ // events whose turn is still the current one;
2728
+ // (3) the legacy session scalar (settings.meshActiveTaskId) as a last-resort
2729
+ // backward-compat alias.
2730
+ // The scalar is last because it is last-write-wins: a second task attaching while
2731
+ // this turn was still running overwrites it, which is the exact NOTIF-MISDELIVER /
2732
+ // TASK-MSG-MISROUTE race this refactor removes.
2733
+ if (this.isMeshWorkerSession()) {
2734
+ const existingTaskId = typeof enrichedEvent.taskId === 'string' && enrichedEvent.taskId.trim()
2735
+ ? enrichedEvent.taskId
2736
+ : undefined;
2737
+ if (!existingTaskId) {
2738
+ const resolved = this.completingTurnTaskId();
2739
+ if (resolved) enrichedEvent.taskId = resolved;
2740
+ }
2741
+ }
1004
2742
  if (this.context?.emitProviderEvent) {
1005
2743
  this.context.emitProviderEvent(enrichedEvent);
1006
- return;
2744
+ } else {
2745
+ this.events.push(enrichedEvent);
2746
+ }
2747
+ // Auto-detach a direct-dispatch mesh assignment once the dispatched
2748
+ // task reaches a terminal state. Leaving meshNodeFor pinned would
2749
+ // route this session's next unrelated turn (a dashboard chat) into
2750
+ // the coordinator as if it were the completion of another task.
2751
+ // We schedule after the emit so the originating coordinator still
2752
+ // observes the completion event with its routing marker intact.
2753
+ if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
2754
+ try { this.detachMeshAssignment(); } catch { /* best-effort */ }
1007
2755
  }
1008
- this.events.push(enrichedEvent);
1009
2756
  }
1010
2757
 
1011
2758
  private flushEvents(): ProviderEvent[] {
@@ -1151,6 +2898,37 @@ export class CliProviderInstance implements ProviderInstance {
1151
2898
  return false;
1152
2899
  }
1153
2900
 
2901
+ /** @see ProviderInstance.noteManualInteraction */
2902
+ noteManualInteraction(now = Date.now()): void {
2903
+ this.manualAttendance.note(now);
2904
+ }
2905
+
2906
+ /**
2907
+ * Whether auto-approve should be treated as active *right now* for display
2908
+ * and firing decisions: the configured intent AND the user is not currently
2909
+ * attending this session by hand. When a human is attending, auto-approve is
2910
+ * held so the modal stays visible and they can drive it via the controlbar.
2911
+ * Provider-agnostic — the attendance signal is the command set, never any
2912
+ * CLI-specific modal text.
2913
+ */
2914
+ private autoApproveEffectivelyActive(status: string | undefined, now = Date.now()): boolean {
2915
+ return status === 'waiting_approval'
2916
+ && this.shouldAutoApprove()
2917
+ && !this.manualAttendance.isAttended(now);
2918
+ }
2919
+
2920
+ // STATUS-MISMATCH: true once the current auto-approve episode has been masking
2921
+ // waiting_approval behind `generating` for longer than AUTO_APPROVE_MASK_STALL_MS without
2922
+ // resolving (the settle gate never fired). When stalled, the surface mask must be dropped
2923
+ // so read_chat / mesh_status / the dashboard see the real waiting_approval + modal (and a
2924
+ // coordinator can mesh_approve it). autoApproveMaskSince is maintained by
2925
+ // maybeAutoApproveStatus (driven by getState + the recheck timer during a waiting episode);
2926
+ // this read is side-effect-free so getStatusMetadata can consult it too.
2927
+ private autoApproveMaskStalled(now = Date.now()): boolean {
2928
+ return this.autoApproveMaskSince > 0
2929
+ && now - this.autoApproveMaskSince > CliProviderInstance.AUTO_APPROVE_MASK_STALL_MS;
2930
+ }
2931
+
1154
2932
  private recordAutoApproval(modalMessage?: string, buttonLabel?: string, now = Date.now()): void {
1155
2933
  this.appendRuntimeSystemMessage(
1156
2934
  formatAutoApprovalMessage(modalMessage, buttonLabel),
@@ -1238,7 +3016,7 @@ export class CliProviderInstance implements ProviderInstance {
1238
3016
  receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
1239
3017
  historyDedupKey: dedupKey,
1240
3018
  }],
1241
- this.adapter.getScriptParsedStatus?.()?.title || this.workingDir.split('/').filter(Boolean).pop() || 'session',
3019
+ this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
1242
3020
  this.instanceId,
1243
3021
  this.providerSessionId,
1244
3022
  );
@@ -1258,12 +3036,28 @@ export class CliProviderInstance implements ProviderInstance {
1258
3036
  index,
1259
3037
  source: 'parsed',
1260
3038
  }));
3039
+ const getRole = (message: ChatMessage): string => typeof message.role === 'string'
3040
+ ? message.role.trim().toLowerCase()
3041
+ : '';
1261
3042
  const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
1262
3043
  message: entry.message,
1263
3044
  index: parsedMessages.length + index,
1264
- source: 'runtime',
3045
+ source: 'runtime' as const,
1265
3046
  runtimeKey: entry.key,
1266
- }));
3047
+ })).filter((entry) => {
3048
+ const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
3049
+ ? entry.message.meta as Record<string, unknown>
3050
+ : {};
3051
+ if (meta.runtimeInputAck !== true) return true;
3052
+ const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
3053
+ if (!runtimeText) return false;
3054
+ return !parsedEntries.some((parsedEntry) => {
3055
+ const parsedRole = getRole(parsedEntry.message);
3056
+ if (parsedRole !== 'user' && parsedRole !== 'human') return false;
3057
+ const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
3058
+ return parsedText === runtimeText;
3059
+ });
3060
+ });
1267
3061
  const getTime = (message: ChatMessage): number => {
1268
3062
  const value = typeof message.receivedAt === 'number'
1269
3063
  ? message.receivedAt
@@ -1273,9 +3067,6 @@ export class CliProviderInstance implements ProviderInstance {
1273
3067
  return Number.isFinite(value) && value > 0 ? value : 0;
1274
3068
  };
1275
3069
 
1276
- const getRole = (message: ChatMessage): string => typeof message.role === 'string'
1277
- ? message.role.trim().toLowerCase()
1278
- : '';
1279
3070
  const isRuntimeOverlay = (entry: MergeEntry): boolean => {
1280
3071
  if (entry.source !== 'runtime') return false;
1281
3072
  const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
@@ -1341,7 +3132,9 @@ export class CliProviderInstance implements ProviderInstance {
1341
3132
  this.providerSessionId = nextSessionId;
1342
3133
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
1343
3134
  this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
1344
- this.restorePersistedHistoryFromCurrentSession();
3135
+ if (this.shouldHydrateExistingProviderHistory()) {
3136
+ this.restorePersistedHistoryFromCurrentSession();
3137
+ }
1345
3138
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
1346
3139
  this.onProviderSessionResolved?.({
1347
3140
  instanceId: this.instanceId,
@@ -1354,13 +3147,39 @@ export class CliProviderInstance implements ProviderInstance {
1354
3147
  LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
1355
3148
  }
1356
3149
 
1357
- private syncCanonicalSavedHistoryIfNeeded(): boolean {
3150
+ private shouldHydrateExistingProviderHistory(): boolean {
3151
+ return this.launchMode === 'resume' || this.launchMode === 'manual';
3152
+ }
3153
+
3154
+ private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
3155
+ if (this.launchMode !== 'new') return false;
3156
+ if (this.providerSessionId) return false;
3157
+ if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
3158
+ if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
3159
+ if (parsedProviderSessionId) return true;
3160
+
3161
+ const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
3162
+
3163
+ // Untimestamped idle parser output during a fresh launch is usually the
3164
+ // provider's last workspace transcript before a new turn exists.
3165
+ return newestMessageAt === 0;
3166
+ }
3167
+
3168
+ private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
1358
3169
  if (!this.providerSessionId) return false;
1359
- const canonicalHistory = this.provider.canonicalHistory;
3170
+ const canonicalHistory = this.provider.nativeHistory;
1360
3171
  if (!canonicalHistory) return false;
1361
3172
 
3173
+ // Per-status-report hydration reads only a bounded tail (snapshot needs at
3174
+ // most the newest 60). The once-per-resume restore path passes full:true
3175
+ // because seedSessionHistory needs the COMPLETE transcript to seed dedup
3176
+ // state. The read-cache key encodes the window so the bounded and full
3177
+ // reads don't share/clobber each other's 2s cache entry.
3178
+ const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
3179
+ const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
3180
+
1362
3181
  if (isNativeSourceCanonicalHistory(canonicalHistory)) {
1363
- const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
3182
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
1364
3183
  const now = Date.now();
1365
3184
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1366
3185
  return true;
@@ -1373,7 +3192,7 @@ export class CliProviderInstance implements ProviderInstance {
1373
3192
  historySessionId: this.providerSessionId,
1374
3193
  workspace: this.workingDir,
1375
3194
  offset: 0,
1376
- limit: Number.MAX_SAFE_INTEGER,
3195
+ limit,
1377
3196
  historyBehavior: this.provider.historyBehavior,
1378
3197
  scripts: this.provider.scripts as any,
1379
3198
  });
@@ -1390,7 +3209,7 @@ export class CliProviderInstance implements ProviderInstance {
1390
3209
  }
1391
3210
 
1392
3211
  try {
1393
- const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
3212
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
1394
3213
  const now = Date.now();
1395
3214
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1396
3215
  return true;
@@ -1401,7 +3220,14 @@ export class CliProviderInstance implements ProviderInstance {
1401
3220
  if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
1402
3221
  return false;
1403
3222
  }
1404
- const restoredHistory = readChatHistory(this.type, 0, Number.MAX_SAFE_INTEGER, this.providerSessionId, 0, this.provider.historyBehavior);
3223
+ // Bounded by default: the per-status-report path only needs the newest
3224
+ // STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
3225
+ // activeChat.messages to the last 60 (status/normalize.ts) and loads
3226
+ // the rest lazily via read_chat on subscribe. The once-per-resume
3227
+ // restore path passes full:true so seedSessionHistory still sees the
3228
+ // COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
3229
+ // a bounded limit as an O(tail) read.
3230
+ const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
1405
3231
  this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
1406
3232
  role: message.role,
1407
3233
  content: message.content,
@@ -1417,10 +3243,13 @@ export class CliProviderInstance implements ProviderInstance {
1417
3243
 
1418
3244
  private restorePersistedHistoryFromCurrentSession(): void {
1419
3245
  if (!this.providerSessionId) return;
1420
- this.syncCanonicalSavedHistoryIfNeeded();
1421
- const restoredHistory = isNativeSourceCanonicalHistory(this.provider.canonicalHistory)
3246
+ // Restore is the once-per-resume seeding path: it needs the COMPLETE
3247
+ // transcript so seedSessionHistory can prime dedup state. Pass full so the
3248
+ // hydration read is unbounded here (and only here).
3249
+ this.syncCanonicalSavedHistoryIfNeeded({ full: true });
3250
+ const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
1422
3251
  ? readProviderChatHistory(this.type, {
1423
- canonicalHistory: this.provider.canonicalHistory,
3252
+ canonicalHistory: this.provider.nativeHistory,
1424
3253
  historySessionId: this.providerSessionId,
1425
3254
  workspace: this.workingDir,
1426
3255
  offset: 0,