@adhdev/daemon-core 0.9.82-rc.47 → 0.9.82-rc.471

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 (468) 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 +25 -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 +64 -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 +48 -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 +152 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router-aggregate-status.d.ts +24 -0
  56. package/dist/commands/router-mesh-session-owner.d.ts +59 -0
  57. package/dist/commands/router-refine.d.ts +137 -0
  58. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  59. package/dist/commands/router.d.ts +204 -15
  60. package/dist/commands/upgrade-helper.d.ts +41 -1
  61. package/dist/config/chat-history.d.ts +9 -0
  62. package/dist/config/config.d.ts +19 -0
  63. package/dist/config/mesh-config.d.ts +136 -1
  64. package/dist/config/mesh-json-config.d.ts +199 -0
  65. package/dist/config/registry-resolver.d.ts +54 -0
  66. package/dist/config/repo-settings.d.ts +77 -0
  67. package/dist/daemon/dev-server.d.ts +0 -2
  68. package/dist/detection/cli-detector.d.ts +17 -0
  69. package/dist/detection/ide-detector.d.ts +13 -0
  70. package/dist/detection/win32-ide-version.d.ts +37 -0
  71. package/dist/git/change-impact-config.d.ts +159 -0
  72. package/dist/git/git-commands.d.ts +26 -2
  73. package/dist/git/git-diff.d.ts +6 -0
  74. package/dist/git/git-executor.d.ts +11 -0
  75. package/dist/git/git-status.d.ts +57 -0
  76. package/dist/git/git-types.d.ts +2 -50
  77. package/dist/git/git-worktree.d.ts +71 -1
  78. package/dist/git/index.d.ts +3 -1
  79. package/dist/index.d.ts +70 -16
  80. package/dist/index.js +58296 -24540
  81. package/dist/index.js.map +1 -1
  82. package/dist/index.mjs +59238 -25657
  83. package/dist/index.mjs.map +1 -1
  84. package/dist/installer.d.ts +1 -4
  85. package/dist/ipc/local-ipc-server.d.ts +91 -0
  86. package/dist/launch.d.ts +1 -1
  87. package/dist/logging/async-batch-writer.d.ts +10 -0
  88. package/dist/logging/debug-config.d.ts +16 -0
  89. package/dist/logging/log-redactor.d.ts +24 -0
  90. package/dist/logging/log-tail-reader.d.ts +81 -0
  91. package/dist/logging/logger.d.ts +1 -1
  92. package/dist/mesh/contracts.d.ts +230 -0
  93. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  94. package/dist/mesh/coordinator-registry.d.ts +59 -0
  95. package/dist/mesh/mesh-active-work.d.ts +203 -0
  96. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  97. package/dist/mesh/mesh-completion-synthesis.d.ts +4 -0
  98. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  99. package/dist/mesh/mesh-delivery-policy.d.ts +104 -0
  100. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  101. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  102. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  103. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  104. package/dist/mesh/mesh-events-pending.d.ts +246 -0
  105. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  106. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  107. package/dist/mesh/mesh-events.d.ts +6 -49
  108. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  109. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  110. package/dist/mesh/mesh-init.d.ts +128 -0
  111. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  112. package/dist/mesh/mesh-ledger.d.ts +139 -1
  113. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  114. package/dist/mesh/mesh-missions.d.ts +226 -0
  115. package/dist/mesh/mesh-node-identity.d.ts +310 -0
  116. package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
  117. package/dist/mesh/mesh-reconcile-acked-hold.d.ts +17 -0
  118. package/dist/mesh/mesh-reconcile-config.d.ts +6 -0
  119. package/dist/mesh/mesh-reconcile-identity.d.ts +6 -0
  120. package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
  121. package/dist/mesh/mesh-reconcile-v2-backstop.d.ts +16 -0
  122. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  123. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  124. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  125. package/dist/mesh/mesh-remote-event-pull.d.ts +15 -0
  126. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  127. package/dist/mesh/mesh-routing.d.ts +70 -0
  128. package/dist/mesh/mesh-runtime-store.d.ts +508 -0
  129. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  130. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  131. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  132. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  133. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  134. package/dist/mesh/mesh-work-queue.d.ts +363 -5
  135. package/dist/mesh/preview-freshness.d.ts +28 -0
  136. package/dist/mesh/refine-config.d.ts +216 -0
  137. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  138. package/dist/providers/acp-provider-instance.d.ts +5 -0
  139. package/dist/providers/approval-utils.d.ts +46 -0
  140. package/dist/providers/chat-message-normalization.d.ts +58 -1
  141. package/dist/providers/cli-provider-effect-format.d.ts +30 -0
  142. package/dist/providers/cli-provider-history-dedup.d.ts +17 -0
  143. package/dist/providers/cli-provider-input-prompt.d.ts +12 -0
  144. package/dist/providers/cli-provider-instance-types.d.ts +45 -0
  145. package/dist/providers/cli-provider-instance.d.ts +375 -30
  146. package/dist/providers/cli-provider-status-helpers.d.ts +46 -0
  147. package/dist/providers/cli-provider-transcript-merge.d.ts +7 -0
  148. package/dist/providers/contracts.d.ts +149 -6
  149. package/dist/providers/external-sources.d.ts +71 -0
  150. package/dist/providers/manual-attendance.d.ts +79 -0
  151. package/dist/providers/native-history/antigravity-claim-registry.d.ts +28 -0
  152. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  153. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  154. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  155. package/dist/providers/native-history/constants.d.ts +12 -0
  156. package/dist/providers/native-history/dispatcher.d.ts +31 -0
  157. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  158. package/dist/providers/native-history/index.d.ts +13 -0
  159. package/dist/providers/provider-instance-manager.d.ts +29 -0
  160. package/dist/providers/provider-instance.d.ts +30 -1
  161. package/dist/providers/provider-loader.d.ts +42 -5
  162. package/dist/providers/provider-trust.d.ts +31 -0
  163. package/dist/providers/read-chat-contract.d.ts +29 -0
  164. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  165. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  166. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  167. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  168. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  169. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  170. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  171. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  172. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  173. package/dist/providers/sdk/v1/index.d.ts +30 -0
  174. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  175. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  176. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  177. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  178. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  179. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  180. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  181. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  182. package/dist/providers/spec/adapter.d.ts +98 -0
  183. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  184. package/dist/providers/spec/evaluator.d.ts +45 -0
  185. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  186. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  187. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  188. package/dist/providers/spec/fsm-types.d.ts +202 -0
  189. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  190. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  191. package/dist/providers/spec/route.d.ts +4 -0
  192. package/dist/providers/spec/types.d.ts +244 -0
  193. package/dist/providers/status-monitor.d.ts +7 -7
  194. package/dist/providers/transcript-v2.d.ts +176 -0
  195. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  196. package/dist/providers/working-dir.d.ts +17 -0
  197. package/dist/repo-mesh-types.d.ts +629 -12
  198. package/dist/runtime-defaults.d.ts +2 -0
  199. package/dist/session-host/managed-host.d.ts +64 -0
  200. package/dist/session-host/runtime-surface.d.ts +10 -16
  201. package/dist/sessions/registry.d.ts +6 -0
  202. package/dist/shared-types-extra.d.ts +2 -4
  203. package/dist/shared-types.d.ts +86 -55
  204. package/dist/status/normalize.d.ts +1 -1
  205. package/dist/status/normalize.js +1 -0
  206. package/dist/status/normalize.js.map +1 -1
  207. package/dist/status/normalize.mjs +1 -0
  208. package/dist/status/normalize.mjs.map +1 -1
  209. package/dist/status/reporter.d.ts +2 -0
  210. package/dist/status/snapshot.d.ts +26 -0
  211. package/dist/system/hash.d.ts +8 -0
  212. package/dist/system/load-better-sqlite3.d.ts +21 -0
  213. package/dist/types.d.ts +5 -0
  214. package/package.json +11 -4
  215. package/src/agent-stream/poller.ts +2 -3
  216. package/src/agent-stream/provider-adapter.ts +1 -1
  217. package/src/boot/daemon-lifecycle.ts +80 -14
  218. package/src/boot/process-hardening.ts +89 -0
  219. package/src/build-info.ts +73 -0
  220. package/src/chat/source-machine.ts +534 -0
  221. package/src/chat/source-resolver.ts +0 -0
  222. package/src/chat/subscription-updates.ts +20 -1
  223. package/src/cli-adapter-types.d.ts +3 -1
  224. package/src/cli-adapter-types.ts +68 -2
  225. package/src/cli-adapters/cli-script-runner.ts +421 -0
  226. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  227. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  228. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  229. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  230. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  231. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  232. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  233. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  234. package/src/cli-adapters/pty-transport.ts +2 -1
  235. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  236. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  237. package/src/cli-adapters/resolve-executable.ts +204 -0
  238. package/src/cli-adapters/session-host-transport.ts +2 -1
  239. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  240. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  241. package/src/cli-adapters/terminal-screen.ts +16 -81
  242. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  243. package/src/commands/chat-commands-read.ts +2488 -0
  244. package/src/commands/chat-commands-scope.ts +54 -0
  245. package/src/commands/chat-commands-shared.ts +114 -0
  246. package/src/commands/chat-commands-write.ts +891 -0
  247. package/src/commands/chat-commands.ts +19 -1841
  248. package/src/commands/cli-manager.ts +596 -27
  249. package/src/commands/handler.ts +845 -2
  250. package/src/commands/high-family/index.ts +28 -0
  251. package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
  252. package/src/commands/high-family/mesh-events.ts +102 -0
  253. package/src/commands/high-family/mesh-status.ts +849 -0
  254. package/src/commands/high-family/types.ts +80 -0
  255. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  256. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  257. package/src/commands/low-family/diagnostics.ts +57 -0
  258. package/src/commands/low-family/index.ts +37 -0
  259. package/src/commands/low-family/mesh-ledger.ts +62 -0
  260. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  261. package/src/commands/low-family/notification.ts +116 -0
  262. package/src/commands/low-family/refine-config.ts +106 -0
  263. package/src/commands/low-family/session-host.ts +274 -0
  264. package/src/commands/low-family/spec-providerdev.ts +217 -0
  265. package/src/commands/low-family/status-meta.ts +112 -0
  266. package/src/commands/low-family/types.ts +39 -0
  267. package/src/commands/med-family/cli-agent.ts +241 -0
  268. package/src/commands/med-family/fast-forward.ts +230 -0
  269. package/src/commands/med-family/ide.ts +163 -0
  270. package/src/commands/med-family/index.ts +37 -0
  271. package/src/commands/med-family/mesh-crud.ts +1287 -0
  272. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  273. package/src/commands/med-family/mesh-queue.ts +167 -0
  274. package/src/commands/med-family/mesh-restart.ts +92 -0
  275. package/src/commands/med-family/types.ts +153 -0
  276. package/src/commands/mesh-coordinator.ts +334 -124
  277. package/src/commands/router-aggregate-status.ts +209 -0
  278. package/src/commands/router-mesh-session-owner.ts +114 -0
  279. package/src/commands/router-refine.ts +1711 -0
  280. package/src/commands/router-worktree-cleanup.ts +870 -0
  281. package/src/commands/router.ts +795 -4143
  282. package/src/commands/stream-commands.ts +8 -0
  283. package/src/commands/upgrade-helper.ts +310 -45
  284. package/src/config/chat-history.ts +493 -24
  285. package/src/config/config.ts +30 -0
  286. package/src/config/mesh-config.ts +632 -23
  287. package/src/config/mesh-json-config.ts +376 -0
  288. package/src/config/recent-activity.ts +8 -2
  289. package/src/config/registry-resolver.ts +100 -0
  290. package/src/config/repo-settings.ts +111 -0
  291. package/src/daemon/dev-auto-implement.ts +3 -2
  292. package/src/daemon/dev-cli-debug.ts +10 -1
  293. package/src/daemon/dev-server.ts +0 -541
  294. package/src/detection/cli-detector.ts +94 -9
  295. package/src/detection/ide-detector.ts +55 -16
  296. package/src/detection/win32-ide-version.ts +106 -0
  297. package/src/git/change-impact-config.ts +354 -0
  298. package/src/git/git-commands.ts +112 -16
  299. package/src/git/git-diff.ts +81 -11
  300. package/src/git/git-executor.ts +12 -0
  301. package/src/git/git-status.ts +767 -48
  302. package/src/git/git-types.ts +14 -62
  303. package/src/git/git-worktree.ts +261 -4
  304. package/src/git/index.ts +17 -0
  305. package/src/index.ts +207 -13
  306. package/src/installer.d.ts +1 -1
  307. package/src/installer.ts +8 -6
  308. package/src/ipc/local-ipc-server.ts +278 -0
  309. package/src/launch.d.ts +1 -1
  310. package/src/launch.ts +37 -28
  311. package/src/logging/async-batch-writer.ts +55 -0
  312. package/src/logging/command-log.ts +7 -5
  313. package/src/logging/debug-config.ts +25 -0
  314. package/src/logging/debug-trace.ts +7 -2
  315. package/src/logging/log-redactor.ts +100 -0
  316. package/src/logging/log-tail-reader.ts +341 -0
  317. package/src/logging/logger.ts +14 -7
  318. package/src/mesh/contracts.ts +469 -0
  319. package/src/mesh/coordinator-prompt.ts +572 -34
  320. package/src/mesh/coordinator-registry.ts +121 -0
  321. package/src/mesh/mesh-active-work.ts +706 -0
  322. package/src/mesh/mesh-clone-grace.ts +68 -0
  323. package/src/mesh/mesh-completion-synthesis.ts +398 -0
  324. package/src/mesh/mesh-coordinator-config.ts +97 -0
  325. package/src/mesh/mesh-delivery-policy.ts +284 -0
  326. package/src/mesh/mesh-event-classify.ts +78 -0
  327. package/src/mesh/mesh-event-forwarding.ts +1964 -0
  328. package/src/mesh/mesh-event-trace.ts +67 -0
  329. package/src/mesh/mesh-events-coordinator.ts +32 -0
  330. package/src/mesh/mesh-events-pending.ts +1494 -0
  331. package/src/mesh/mesh-events-stale.ts +440 -0
  332. package/src/mesh/mesh-events-utils.ts +443 -0
  333. package/src/mesh/mesh-events.ts +43 -1035
  334. package/src/mesh/mesh-fast-forward.ts +856 -0
  335. package/src/mesh/mesh-host-ownership.ts +111 -0
  336. package/src/mesh/mesh-init.ts +350 -0
  337. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  338. package/src/mesh/mesh-ledger.ts +898 -102
  339. package/src/mesh/mesh-magi-status.ts +223 -0
  340. package/src/mesh/mesh-missions.ts +568 -0
  341. package/src/mesh/mesh-node-identity.ts +2065 -0
  342. package/src/mesh/mesh-queue-assignment.ts +2247 -0
  343. package/src/mesh/mesh-reconcile-acked-hold.ts +230 -0
  344. package/src/mesh/mesh-reconcile-config.ts +66 -0
  345. package/src/mesh/mesh-reconcile-identity.ts +103 -0
  346. package/src/mesh/mesh-reconcile-loop.ts +1473 -0
  347. package/src/mesh/mesh-reconcile-v2-backstop.ts +62 -0
  348. package/src/mesh/mesh-refine-batch.ts +205 -0
  349. package/src/mesh/mesh-refine-gates.ts +1686 -0
  350. package/src/mesh/mesh-refine-status.ts +231 -0
  351. package/src/mesh/mesh-remote-event-pull.ts +279 -0
  352. package/src/mesh/mesh-review-inbox.ts +308 -0
  353. package/src/mesh/mesh-routing.ts +291 -0
  354. package/src/mesh/mesh-runtime-store.ts +2150 -0
  355. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  356. package/src/mesh/mesh-task-inflight.ts +70 -0
  357. package/src/mesh/mesh-task-stats.ts +161 -0
  358. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  359. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  360. package/src/mesh/mesh-work-queue.ts +1437 -147
  361. package/src/mesh/preview-freshness.ts +163 -0
  362. package/src/mesh/refine-config.ts +423 -0
  363. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  364. package/src/providers/acp-provider-instance.ts +43 -10
  365. package/src/providers/approval-utils.d.ts +5 -0
  366. package/src/providers/approval-utils.ts +100 -6
  367. package/src/providers/chat-message-normalization.ts +126 -4
  368. package/src/providers/cli-provider-effect-format.ts +53 -0
  369. package/src/providers/cli-provider-history-dedup.ts +75 -0
  370. package/src/providers/cli-provider-input-prompt.ts +133 -0
  371. package/src/providers/cli-provider-instance-types.ts +131 -0
  372. package/src/providers/cli-provider-instance.ts +2554 -499
  373. package/src/providers/cli-provider-status-helpers.ts +123 -0
  374. package/src/providers/cli-provider-transcript-merge.ts +114 -0
  375. package/src/providers/contracts.d.ts +55 -0
  376. package/src/providers/contracts.ts +160 -6
  377. package/src/providers/extension-provider-instance.ts +12 -7
  378. package/src/providers/external-sources.ts +218 -0
  379. package/src/providers/ide-provider-instance.ts +35 -12
  380. package/src/providers/manual-attendance.ts +105 -0
  381. package/src/providers/native-history/antigravity-claim-registry.ts +131 -0
  382. package/src/providers/native-history/antigravity-cli-transcript.ts +1193 -0
  383. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  384. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  385. package/src/providers/native-history/constants.ts +19 -0
  386. package/src/providers/native-history/dispatcher.ts +503 -0
  387. package/src/providers/native-history/hermes-cli-transcript.ts +312 -0
  388. package/src/providers/native-history/index.ts +30 -0
  389. package/src/providers/provider-instance-manager.ts +71 -0
  390. package/src/providers/provider-instance.ts +24 -1
  391. package/src/providers/provider-loader.ts +700 -55
  392. package/src/providers/provider-schema.ts +87 -14
  393. package/src/providers/provider-trust.ts +114 -0
  394. package/src/providers/read-chat-contract.ts +76 -16
  395. package/src/providers/sdk/README.md +49 -0
  396. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  397. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  398. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  399. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  400. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  401. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  402. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  403. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  404. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  405. package/src/providers/sdk/v1/index.ts +152 -0
  406. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  407. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  408. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  409. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  410. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  411. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  412. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  413. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  414. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  415. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  416. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  417. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  418. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  419. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  420. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  421. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  422. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  423. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  424. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  425. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  426. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  427. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  428. package/src/providers/sdk/v1/validators/index.ts +19 -0
  429. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  430. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  431. package/src/providers/spec/adapter.ts +246 -0
  432. package/src/providers/spec/cli-adapter.ts +1064 -0
  433. package/src/providers/spec/evaluator.ts +407 -0
  434. package/src/providers/spec/fsm-driver.ts +1528 -0
  435. package/src/providers/spec/fsm-evaluator.ts +290 -0
  436. package/src/providers/spec/fsm-loader.ts +128 -0
  437. package/src/providers/spec/fsm-types.ts +301 -0
  438. package/src/providers/spec/native-history-executor.ts +1241 -0
  439. package/src/providers/spec/pre-launch-trust.ts +104 -0
  440. package/src/providers/spec/route.ts +51 -0
  441. package/src/providers/spec/types.ts +284 -0
  442. package/src/providers/status-monitor.d.ts +7 -7
  443. package/src/providers/status-monitor.ts +37 -22
  444. package/src/providers/transcript-v2.ts +567 -0
  445. package/src/providers/types/interactive-prompt.ts +536 -0
  446. package/src/providers/version-archive.ts +64 -24
  447. package/src/providers/working-dir.ts +23 -0
  448. package/src/repo-mesh-types.ts +868 -13
  449. package/src/runtime-defaults.ts +39 -0
  450. package/src/session-host/managed-host.ts +218 -0
  451. package/src/session-host/runtime-surface.ts +20 -80
  452. package/src/sessions/registry.ts +6 -0
  453. package/src/shared-types-extra.ts +2 -4
  454. package/src/shared-types.d.ts +8 -0
  455. package/src/shared-types.ts +124 -55
  456. package/src/status/builders.ts +26 -6
  457. package/src/status/normalize.ts +2 -0
  458. package/src/status/reporter.ts +19 -1
  459. package/src/status/snapshot.ts +95 -26
  460. package/src/system/hash.ts +23 -0
  461. package/src/system/host-memory.ts +29 -12
  462. package/src/system/load-better-sqlite3.ts +68 -0
  463. package/src/types.ts +5 -0
  464. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  465. package/dist/mesh/mesh-sync.d.ts +0 -53
  466. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  467. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  468. package/src/mesh/mesh-sync.ts +0 -111
@@ -9,315 +9,291 @@ import * as os from 'os';
9
9
  import * as path from 'path';
10
10
  import * as crypto from 'crypto';
11
11
  import * as fs from 'fs';
12
- import { createRequire } from 'node:module';
13
- import { normalizeInputEnvelope, type ProviderModule, flattenContent, type InputEnvelope, type InputPart } from './contracts.js';
12
+ import { normalizeInputEnvelope, type ProviderModule, flattenContent, type InputEnvelope } from './contracts.js';
14
13
  import { assertProviderSupportsDeclaredInput, getEffectiveMessageInputSupport } from './provider-input-support.js';
15
14
  import type { ProviderInstance, ProviderState, ProviderEvent, InstanceContext, ProviderErrorReason, HotChatSessionState, SessionModalState } from './provider-instance.js';
15
+ import { normalizeInteractivePrompt, normalizeInteractivePromptResponse, type InteractivePrompt } from './types/interactive-prompt.js';
16
16
  import { ProviderCliAdapter } from '../cli-adapters/provider-cli-adapter.js';
17
+ import { shortHash } from '../system/hash.js';
17
18
  import type { CliProviderModule } from '../cli-adapters/provider-cli-adapter.js';
19
+ import { createCliAdapter } from './spec/route.js';
18
20
  import type { PtyRuntimeMetadata, PtyTransportFactory } from '../cli-adapters/pty-transport.js';
19
21
  import { StatusMonitor } from './status-monitor.js';
20
22
  import { ChatHistoryWriter, isNativeSourceCanonicalHistory, materializeProviderNativeHistory, readChatHistory, readProviderChatHistory } from '../config/chat-history.js';
21
23
  import { LOG } from '../logging/logger.js';
24
+ import { recordDebugTrace } from '../logging/debug-trace.js';
25
+ import { shouldCollectTraceCategory } from '../logging/debug-config.js';
26
+ import { traceMeshEventStage, traceMeshEventDrop } from '../mesh/mesh-event-trace.js';
22
27
  import type { ChatMessage } from '../types.js';
23
28
  import { buildPersistedProviderEffectMessage, normalizeProviderEffects } from './control-effects.js';
24
- import { formatAutoApprovalMessage, pickApprovalButton } from './approval-utils.js';
29
+ import { formatAutoApprovalMessage, pickApprovalButton, hasNegativeApprovalOption, hasReliableApprovalAffirmative, looksLikeActiveApprovalPromptText, normalizeApprovalLabel } from './approval-utils.js';
25
30
  import { getCliScriptCommand, parseCliScriptResult } from './cli-script-results.js';
26
31
  import { mergeProviderPatchState, resolveProviderStateSurface } from './provider-patch-state.js';
27
32
  import { normalizeProviderSessionId } from './provider-session-id.js';
28
- import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
29
-
30
- type PersistableCliHistoryMessage = {
31
- role: string;
32
- content: string;
33
- kind?: string;
34
- senderName?: string;
35
- receivedAt?: number;
36
- };
37
-
38
- type CompletedDebouncePending = {
39
- chatTitle: string;
40
- duration: number;
41
- timestamp: number;
42
- firstObservedAt: number;
43
- loggedBlockReason?: string;
44
- };
45
-
46
- const COMPLETED_FINALIZATION_RETRY_MS = 1000;
47
- const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
48
-
49
- const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
50
- 'image/png': '.png',
51
- 'image/jpeg': '.jpg',
52
- 'image/jpg': '.jpg',
53
- 'image/gif': '.gif',
54
- 'image/webp': '.webp',
55
- 'image/bmp': '.bmp',
56
- 'image/tiff': '.tiff',
57
- 'image/svg+xml': '.svg',
58
- };
59
-
60
- function filePathFromUri(uri: string): string | null {
61
- if (!uri) return null;
62
- if (uri.startsWith('file://')) {
63
- try {
64
- return decodeURIComponent(new URL(uri).pathname);
65
- } catch {
66
- return uri.slice('file://'.length);
67
- }
68
- }
69
- if (path.isAbsolute(uri)) return uri;
70
- return null;
71
- }
72
-
73
- function extensionForImageMime(mimeType: string): string {
74
- return IMAGE_MIME_EXTENSIONS[mimeType.toLowerCase()] || '.img';
75
- }
76
-
77
- function safeInputImageBasename(index: number, mimeType: string): string {
78
- const extension = extensionForImageMime(mimeType);
79
- const suffix = crypto.randomBytes(6).toString('hex');
80
- return `adhdev-input-image-${Date.now()}-${index}-${suffix}${extension}`;
81
- }
82
-
83
- function materializeImageDataPart(part: Extract<InputPart, { type: 'image' }>, index: number, dir: string): string | null {
84
- if (!part.data) return null;
85
- const rawData = part.data.includes(',') ? part.data.split(',').pop() || '' : part.data;
86
- if (!rawData) return null;
87
- fs.mkdirSync(dir, { recursive: true });
88
- const filePath = path.join(dir, safeInputImageBasename(index, part.mimeType));
89
- fs.writeFileSync(filePath, Buffer.from(rawData, 'base64'));
90
- cleanupStaleMaterializedImages(dir);
91
- return filePath;
92
- }
93
-
94
- const MATERIALIZED_IMAGE_MAX_AGE_MS = 60 * 60 * 1000; // 1 hour
95
- const MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
96
- let lastMaterializedImageCleanupAt = 0;
97
-
98
- function cleanupStaleMaterializedImages(dir: string): void {
99
- const now = Date.now();
100
- if (now - lastMaterializedImageCleanupAt < MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS) return;
101
- lastMaterializedImageCleanupAt = now;
102
- try {
103
- const entries = fs.readdirSync(dir);
104
- for (const entry of entries) {
105
- if (!entry.startsWith('adhdev-input-image-')) continue;
106
- const fullPath = path.join(dir, entry);
107
- try {
108
- const stat = fs.statSync(fullPath);
109
- if (now - stat.mtimeMs > MATERIALIZED_IMAGE_MAX_AGE_MS) {
110
- fs.unlinkSync(fullPath);
111
- }
112
- } catch { /* file may have been removed concurrently */ }
113
- }
114
- } catch { /* dir may not exist or be inaccessible */ }
115
- }
116
-
117
- function hasNonEmptyCliModalButtons(activeModal: unknown): boolean {
118
- const buttons = (activeModal as any)?.buttons;
119
- return Array.isArray(buttons) && buttons.some((button) => String(button || '').trim().length > 0);
120
- }
121
-
122
- function isCliGeneratingLikeStatus(status: unknown): boolean {
123
- return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
124
- }
125
-
126
- export function buildCliStructuredInputPrompt(
127
- input: InputEnvelope,
128
- options: { materializeDir?: string } = {},
129
- ): string {
130
- const promptParts: string[] = [];
131
- const imageRefs: string[] = [];
132
- const resourceRefs: string[] = [];
133
- const materializeDir = options.materializeDir || path.join(os.tmpdir(), 'adhdev-input-media');
134
-
135
- input.parts.forEach((part, index) => {
136
- if (part.type === 'text' && part.text.trim()) {
137
- promptParts.push(part.text.trim());
138
- return;
139
- }
140
-
141
- if (part.type === 'image') {
142
- const localPath = typeof part.uri === 'string' ? filePathFromUri(part.uri) : null;
143
- const materializedPath = !localPath && part.data ? materializeImageDataPart(part, index, materializeDir) : null;
144
- const ref = localPath || materializedPath || part.uri || '';
145
- if (ref) imageRefs.push(ref);
146
- if (part.alt?.trim()) promptParts.push(part.alt.trim());
147
- return;
148
- }
149
-
150
- if (part.type === 'resource_link') {
151
- resourceRefs.push([part.title, part.name, part.description, part.uri].filter(Boolean).join('\n'));
152
- return;
153
- }
154
-
155
- if (part.type === 'resource') {
156
- resourceRefs.push([part.name, part.text, part.uri].filter(Boolean).join('\n'));
157
- }
158
- });
159
-
160
- // Only use textFallback when no explicit text parts were collected — it is
161
- // the flattened version of the same parts, so appending it alongside them
162
- // would duplicate the content for multipart inputs.
163
- const hasExplicitTextParts = input.parts.some((part) => part.type === 'text' && part.text.trim());
164
- if (!hasExplicitTextParts && input.textFallback.trim()) {
165
- promptParts.push(input.textFallback.trim());
166
- }
167
-
168
- const ordered = [
169
- ...imageRefs,
170
- ...promptParts,
171
- ...resourceRefs,
172
- ].filter((value, index, values) => value.trim().length > 0 && values.indexOf(value) === index);
33
+ import {
34
+ antigravityOwnerToken,
35
+ claimAntigravityConversation,
36
+ releaseAntigravityOwner,
37
+ } from './native-history/antigravity-claim-registry.js';
38
+ import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages, extractFinalSummaryFromMessagesAfter, readChatMessageTimestampMs } from './chat-message-normalization.js';
39
+ import { workingDirBasename } from './working-dir.js';
40
+ import { ManualAttendanceTracker } from './manual-attendance.js';
41
+ import { buildCliStructuredInputPrompt } from './cli-provider-input-prompt.js';
42
+ import { type PersistableCliHistoryMessage, buildIncrementalHistoryAppendMessages } from './cli-provider-history-dedup.js';
43
+ import {
44
+ isIdleStatus,
45
+ getMessageTime,
46
+ hasNonEmptyCliModalButtons,
47
+ isCliGeneratingLikeStatus,
48
+ computeTurnAnchoredDurationMs,
49
+ getDatabaseSync,
50
+ getForcedNewSessionScriptName,
51
+ waitForCliAdapterReady,
52
+ } from './cli-provider-status-helpers.js';
53
+ import {
54
+ STATUS_HYDRATION_TAIL_LIMIT,
55
+ COMPLETED_FINALIZATION_RETRY_MS,
56
+ COMPLETED_FINALIZATION_MAX_WAIT_MS,
57
+ NATIVE_HISTORY_MESH_IDLE_SETTLE_MS,
58
+ USER_INPUT_ACK_DEDUP_WINDOW_MS,
59
+ STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS,
60
+ TERMINAL_MESH_EVENTS,
61
+ } from './cli-provider-instance-types.js';
62
+ import type {
63
+ CompletedDebouncePending,
64
+ CompletedFinalizationBlock,
65
+ CompletionFinalAssistantEvidence,
66
+ ExternalTranscriptProbe,
67
+ } from './cli-provider-instance-types.js';
68
+ import { mergeConversationMessages, buildExternalTranscriptProbe } from './cli-provider-transcript-merge.js';
69
+ import { getEffectDedupKey, formatApprovalRequestMessage, formatMarkerTimestamp } from './cli-provider-effect-format.js';
70
+
71
+ // Re-export moved public symbols so existing importers (index.ts, tests) keep
72
+ // their `./cli-provider-instance.js` path. Pure move — no behavior change.
73
+ export { buildCliStructuredInputPrompt } from './cli-provider-input-prompt.js';
74
+ export { buildIncrementalHistoryAppendMessages } from './cli-provider-history-dedup.js';
75
+ export {
76
+ computeTurnAnchoredDurationMs,
77
+ getForcedNewSessionScriptName,
78
+ waitForCliAdapterReady,
79
+ } from './cli-provider-status-helpers.js';
173
80
 
174
- return ordered.join('\n');
175
- }
176
-
177
- function normalizePersistableCliHistoryContent(content: unknown): string {
178
- return flattenContent(content as any).replace(/\s+/g, ' ').trim();
179
- }
180
-
181
- function buildPersistableCliHistorySignature(message: PersistableCliHistoryMessage): string {
182
- return [
183
- String(message.role || ''),
184
- String(message.kind || ''),
185
- String(message.senderName || ''),
186
- normalizePersistableCliHistoryContent(message.content),
187
- ].join('|');
188
- }
189
-
190
- function hasSamePersistableCliHistoryIdentity(a: PersistableCliHistoryMessage, b: PersistableCliHistoryMessage): boolean {
191
- return String(a?.role || '') === String(b?.role || '')
192
- && String(a?.kind || '') === String(b?.kind || '')
193
- && String(a?.senderName || '') === String(b?.senderName || '')
194
- && String(a?.content || '') === String(b?.content || '');
195
- }
196
-
197
- export function buildIncrementalHistoryAppendMessages(
198
- previousMessages: PersistableCliHistoryMessage[],
199
- currentMessages: PersistableCliHistoryMessage[],
200
- ): PersistableCliHistoryMessage[] {
201
- if (!Array.isArray(currentMessages) || currentMessages.length === 0) return [];
202
- if (!Array.isArray(previousMessages) || previousMessages.length === 0) return currentMessages;
203
-
204
- const comparableLength = Math.min(previousMessages.length, currentMessages.length);
205
- let sharedPrefixLength = 0;
206
- while (
207
- sharedPrefixLength < comparableLength
208
- && hasSamePersistableCliHistoryIdentity(previousMessages[sharedPrefixLength], currentMessages[sharedPrefixLength])
209
- ) {
210
- sharedPrefixLength += 1;
211
- }
212
-
213
- if (sharedPrefixLength === currentMessages.length) return [];
214
- if (sharedPrefixLength === previousMessages.length) return currentMessages.slice(sharedPrefixLength);
215
-
216
- // Rare fallback: preserve the older whitespace-normalized behavior only when
217
- // the cheap identity check detects a changed prefix. Recomputing normalized
218
- // signatures for the full transcript on every idle status poll was a CPU
219
- // hot path for long CLI sessions.
220
- while (
221
- sharedPrefixLength < comparableLength
222
- && buildPersistableCliHistorySignature(previousMessages[sharedPrefixLength])
223
- === buildPersistableCliHistorySignature(currentMessages[sharedPrefixLength])
224
- ) {
225
- sharedPrefixLength += 1;
226
- }
227
-
228
- if (sharedPrefixLength === currentMessages.length) return [];
229
- if (sharedPrefixLength === previousMessages.length) return currentMessages.slice(sharedPrefixLength);
230
- return currentMessages;
231
- }
232
-
233
- let CachedDatabaseSync: (new (path: string, options?: { readOnly?: boolean }) => {
234
- prepare(sql: string): { get(...params: Array<string | number>): unknown };
235
- close(): void;
236
- }) | null = null;
237
-
238
- function getDatabaseSync() {
239
- if (CachedDatabaseSync) return CachedDatabaseSync;
240
- const requireFn = typeof require === 'function'
241
- ? require
242
- : createRequire(path.join(process.cwd(), '__adhdev_sqlite_loader__.js'));
243
- const sqliteModule = requireFn(`node:${'sqlite'}`) as {
244
- DatabaseSync: typeof CachedDatabaseSync;
245
- };
246
- CachedDatabaseSync = sqliteModule.DatabaseSync;
247
- if (!CachedDatabaseSync) {
248
- throw new Error('node:sqlite DatabaseSync unavailable');
249
- }
250
- return CachedDatabaseSync;
81
+ /**
82
+ * The auto-approve settle-gate identity signature: the modal's question line plus
83
+ * the NORMALIZED affirmative label, no volatile counters or raw button set. Shared
84
+ * by the fire path (maybeAutoApproveStatus) and the mask-stall nudge so both compare
85
+ * the SAME identity the settle clock tracks (AUTOAPPROVE-SETTLE-FLAP).
86
+ */
87
+ function approvalModalSignature(message: unknown, affirmativeAnchor: string): string {
88
+ return [typeof message === 'string' ? message.trim() : '', affirmativeAnchor].join('::');
251
89
  }
252
90
 
253
- export function getForcedNewSessionScriptName(
254
- provider: ProviderModule | undefined,
255
- launchMode: 'new' | 'resume' | 'manual',
256
- ): string | null {
257
- if (!provider || launchMode !== 'new') return null;
258
- const resume = provider.resume;
259
- if (!resume?.supported) return null;
260
- if (Array.isArray(resume.newSessionArgs) && resume.newSessionArgs.length > 0) return null;
261
-
262
- const controls = Array.isArray((provider as any).controls) ? (provider as any).controls : [];
263
- for (const control of controls) {
264
- if (control?.type !== 'action') continue;
265
- if (typeof control?.confirmTitle === 'string' && control.confirmTitle.trim()) continue;
266
- if (typeof control?.confirmMessage === 'string' && control.confirmMessage.trim()) continue;
267
- if (typeof control?.confirmLabel === 'string' && control.confirmLabel.trim()) continue;
268
- const invokeScript = typeof control?.invokeScript === 'string' ? control.invokeScript.trim() : '';
269
- if (!invokeScript) continue;
270
- const controlId = typeof control?.id === 'string' ? control.id.trim() : '';
271
- if (controlId === 'new_session' || /^new.?session$/i.test(invokeScript)) {
272
- return invokeScript;
273
- }
274
- }
275
-
276
- return null;
277
- }
91
+ export class CliProviderInstance implements ProviderInstance {
92
+ readonly type: string;
93
+ readonly category = 'cli' as const;
278
94
 
279
- export async function waitForCliAdapterReady(
280
- adapter: { isReady?: () => boolean; getStatus?: () => { status?: string } },
281
- options?: { timeoutMs?: number; pollMs?: number },
282
- ): Promise<void> {
283
- const timeoutMs = Math.max(100, options?.timeoutMs ?? 15_000);
284
- const pollMs = Math.max(10, options?.pollMs ?? 50);
285
- const deadline = Date.now() + timeoutMs;
95
+ /**
96
+ * Quiet period an approval modal's signature must be stable before
97
+ * auto-approve sends the approve key. Guards against firing on a prompt
98
+ * that is still streaming into the PTY (the "resolves too fast" symptom):
99
+ * while the modal text/buttons are still changing, every frame yields a
100
+ * new signature and the settle clock restarts. Once the prompt finishes
101
+ * rendering the signature holds and the key is sent after this window.
102
+ * Bounded + small so genuine approvals stay timely. The FSM is already
103
+ * authoritative over the `waiting_approval` state; this only delays the
104
+ * keystroke until the modal *content* has settled.
105
+ */
106
+ private static readonly AUTO_APPROVE_SETTLE_MS = 600;
286
107
 
287
- while (Date.now() < deadline) {
288
- if (adapter?.isReady?.()) return;
289
- const status = adapter?.getStatus?.()?.status;
290
- if (status === 'stopped') {
291
- throw new Error('CLI runtime stopped before it became ready');
292
- }
293
- await new Promise((resolve) => setTimeout(resolve, pollMs));
294
- }
108
+ /**
109
+ * Busy-side hysteresis for the settle gate. A momentary `generating` flip
110
+ * while the SAME approval modal's button block is still on screen (its
111
+ * question line scrolled out of the captured frame, only the buttons + a
112
+ * residual `esc to interrupt` spinner remain) briefly reports
113
+ * status!=waiting_approval. Without hysteresis that flip wipes the settle
114
+ * clock, and the modal→generating→modal flap restarts the 600ms window
115
+ * every time so auto-approve never fires. We keep the in-progress settle
116
+ * gate warm across an inactive blip up to this bound; only once the modal
117
+ * has genuinely stayed gone this long (a real resolution → idle) is the
118
+ * gate cleared. Bounded so a genuinely new, later approval still re-settles
119
+ * from scratch rather than firing on a stale timestamp.
120
+ */
121
+ private static readonly AUTO_APPROVE_GATE_HYSTERESIS_MS = 1500;
295
122
 
296
- throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
297
- }
123
+ /**
124
+ * AUTOAPPROVE-FLAP-RECUR (Fix B): extended busy-side continuity window for a
125
+ * DELEGATED-WORKER auto-approve episode that is genuinely still cycling.
126
+ *
127
+ * The default AUTO_APPROVE_GATE_HYSTERESIS_MS (1500) absorbs a *momentary*
128
+ * `generating` blip. But a delegated worker running a Bash approval observed
129
+ * the FSM cycle the FULL state waiting_approval → busy → waiting_approval on a
130
+ * 2–5s period (the button set scrolls in/out AND the modal question repaints,
131
+ * so the adapter genuinely reports status=generating for whole seconds between
132
+ * approval frames). Each busy phase outran the 1500ms hysteresis, so the
133
+ * settle clock was WIPED (the genuine-resolution branch), the 600ms settle
134
+ * window never accumulated across the flap, resolveModal never fired
135
+ * (resolveModal count 0), and the mask-stall clock instead tripped at 4500ms →
136
+ * coordinator nudge → the flap the coordinator observed.
137
+ *
138
+ * A genuine resolution and a flap both start with a busy phase; they diverge
139
+ * only in whether waiting_approval RETURNS. So we cannot simply lengthen the
140
+ * blanket hysteresis (that would make every real resolution hold the gate
141
+ * open for seconds). Instead this longer window applies ONLY while an active
142
+ * mask episode is alive (autoApproveMaskSince > 0) AND the session is a
143
+ * delegated worker — i.e. exactly the never-resolving-flap case. A foreground
144
+ * / attended session keeps the tight 1500ms window unchanged. The mask-stall
145
+ * bound below still caps the episode, so a worker whose approval truly never
146
+ * returns is surfaced to the coordinator within AUTO_APPROVE_MASK_STALL_MS
147
+ * rather than held forever.
148
+ *
149
+ * INVARIANT (do not regress the ordering): this window must fully BRIDGE a
150
+ * single busy phase, and the mask-stall bound below must in turn exceed it —
151
+ * AUTO_APPROVE_MASK_STALL_MS > AUTO_APPROVE_FLAP_CONTINUITY_MS + max_busy_phase
152
+ * + AUTO_APPROVE_SETTLE_MS. Observed flap geometry (delegated-worker Bash
153
+ * approval): approval frames last ~1.5s, busy phases (modal=none) last
154
+ * ~4.3–4.5s. With the old 4000ms this window was SHORTER than a busy phase, so
155
+ * the settle clock was torn down every cycle and never accrued 600ms while the
156
+ * 4500ms mask-stall tripped INSIDE the first busy phase → a stalled-approval
157
+ * nudge leaked to the coordinator. 6000ms bridges the ~4.5s busy phase with
158
+ * margin so the returning approval frame survives to resume its settle clock.
159
+ */
160
+ private static readonly AUTO_APPROVE_FLAP_CONTINUITY_MS = 6000;
298
161
 
299
- export class CliProviderInstance implements ProviderInstance {
300
- readonly type: string;
301
- readonly category = 'cli' as const;
162
+ /**
163
+ * STATUS-MISMATCH: upper bound on how long the auto-approve→`generating` SURFACE
164
+ * mask may hide a worker's `waiting_approval` (status + activeModal) before we give
165
+ * up and surface the real prompt. The mask exists because auto-approve is expected
166
+ * to resolve the modal momentarily; but if it STALLS without ever calling
167
+ * resolveModal — the modal signature never settles for AUTO_APPROVE_SETTLE_MS (a
168
+ * perpetually-flapping/streaming prompt), no concrete modal is ever captured, or the
169
+ * modal is a picker/non-affirmative we never auto-pick — the mask would persist
170
+ * forever and read_chat / mesh_status / the dashboard would NEVER see the pending
171
+ * approval (the coordinator cannot mesh_approve what it cannot see). Once an episode
172
+ * exceeds this bound we stop masking. Generously larger than
173
+ * AUTO_APPROVE_SETTLE_MS (600) + AUTO_APPROVE_GATE_HYSTERESIS_MS (1500) so a
174
+ * legitimately slow-settling / blip-flapping prompt is never unmasked early; a
175
+ * genuine never-resolving stall surfaces within this window. The settle gate keeps
176
+ * running underneath, so a prompt that finally stabilises still auto-approves, and
177
+ * mesh_approve (raw FSM, unmasked) works throughout.
178
+ *
179
+ * INVARIANT (do not regress): must be STRICTLY GREATER than
180
+ * AUTO_APPROVE_FLAP_CONTINUITY_MS + max_busy_phase + AUTO_APPROVE_SETTLE_MS so
181
+ * that during a flap the settle clock (which FLAP_CONTINUITY keeps alive across
182
+ * each ~4.3–4.5s busy phase) gets to accrue its 600ms on the RETURNING approval
183
+ * frame before this stall bound can trip. Observed geometry: approval ~1.5s,
184
+ * busy ~4.3–4.5s. 9000ms ≥ CONTINUITY(6000) + busy(~4.5s) + SETTLE(600) headroom;
185
+ * the old 4500ms tripped inside the very first busy phase (while modal=none, so
186
+ * the nudge was NOT deferred) and leaked to the coordinator.
187
+ */
188
+ private static readonly AUTO_APPROVE_MASK_STALL_MS = 9000;
302
189
 
303
190
  private adapter: ProviderCliAdapter;
304
191
  private context: InstanceContext | null = null;
305
192
  private events: ProviderEvent[] = [];
306
193
  private lastStatus: string = 'starting';
194
+ // Idempotency guard for the queue-claim agent:ready event. agent:ready is the
195
+ // sole signal the mesh coordinator's tryAssignQueueTask waits on to hand a
196
+ // queued task to this worker. It is emitted in two places: the boot-time
197
+ // starting→idle one-shot, and the readySeen re-arm below. This flag makes the
198
+ // event fire AT MOST ONCE per session so a worker is never claimed twice and a
199
+ // queued task is never double-dispatched/double-injected. Whichever path fires
200
+ // first sets it; the other becomes a no-op.
201
+ private agentReadyEmitted = false;
307
202
  private generatingStartedAt: number = 0;
203
+ // FALSE-IDLE continuity epoch: monotonically bumped on EVERY entry into a busy
204
+ // phase (→generating or →waiting_approval). The completedDebouncePending snapshots
205
+ // this value at arm time (busyEpochAtArm); the flush guard requires it UNCHANGED
206
+ // — proving the session did not re-enter a busy phase (a momentary busy→idle blip
207
+ // in an inter-approval valley) between arming the debounce and flushing it. A
208
+ // single point-sample of status at flush time cannot see a generating phase that
209
+ // opened AND closed within the settle window; the epoch can. See
210
+ // flushCompletedDebounceIfFinalized.
211
+ private busyEpoch: number = 0;
212
+ // GENERATING-BOUNDARY (R4b): the per-turn taskId for which a startup-grace
213
+ // started+completed pair was already synthesized. Both fast-collapse callers
214
+ // (starting→idle transition AND the idle-stayed no-status-change poll) route
215
+ // through maybeSynthesizeStartupGraceCollapse; the idle-stayed caller re-polls
216
+ // steadily while the session sits idle, so this guard makes the synthesis fire
217
+ // AT MOST ONCE per collapsed turn.
218
+ private fastCollapseSynthesizedTaskId: string | null = null;
219
+ // GENERATING-BOUNDARY (R4c): the wall-clock moment the FSM's starting→idle
220
+ // startup-grace collapse was observed (set ONCE, on the first starting→idle
221
+ // transition this boot). The idle-stayed collapse window is anchored on THIS,
222
+ // not on instance/boot time (this.startedAt): the FSM spends the full 8s
223
+ // startup-grace sitting in 'starting' before collapsing, and a turn can be
224
+ // dispatched a few seconds AFTER the collapse — measuring the window from boot
225
+ // would have it already closed by the time that turn lands+completes (the live
226
+ // R4b miss: collapse at boot+8s, dispatch at boot+12.4s > the 12s boot window).
227
+ // Anchoring on the collapse moment makes the window cover dispatch-delay+turn.
228
+ private startupGraceCollapseAt: number | null = null;
308
229
  private settings: Record<string, any> = {};
309
230
  private monitor: StatusMonitor;
310
231
  private generatingDebounceTimer: NodeJS.Timeout | null = null;
311
232
  private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
312
- private lastApprovalEventAt = 0;
233
+ private lastApprovalEventFingerprint = '';
313
234
  private autoApproveBusy = false;
314
235
  private autoApproveBusyTimer: NodeJS.Timeout | null = null;
236
+ private lastAutoApprovalSignature = '';
237
+ // Settle gate: the approval modal's signature + the wall-clock when this
238
+ // exact signature was first observed. Auto-approve only fires once the
239
+ // SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
240
+ // still streaming into the PTY (its buttons/message changing frame to
241
+ // frame) keeps resetting the timer and is never approved half-rendered.
242
+ private pendingAutoApprovalSignature = '';
243
+ private pendingAutoApprovalSince = 0;
244
+ private autoApproveSettleTimer: NodeJS.Timeout | null = null;
245
+ // Wall-clock when auto-approve first observed status!=waiting_approval while
246
+ // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS (or,
247
+ // for a delegated-worker flap episode, AUTO_APPROVE_FLAP_CONTINUITY_MS) so a
248
+ // brief generating flip does not immediately wipe the settle clock.
249
+ private autoApproveInactiveSince = 0;
250
+ // AUTOAPPROVE-FLAP-RECUR (Fix A): wall-clock when the CURRENT waiting_approval
251
+ // episode last presented a concrete, captured modal (buttons.length > 0). The
252
+ // Claude TUI momentarily reports status=waiting_approval with activeModal=null
253
+ // / an empty button block while the button block scrolls out of the captured
254
+ // frame; the raw guard below (buttons.length===0) used to bail on that frame,
255
+ // never advancing the settle gate and leaving no re-check armed — so a modal
256
+ // that flapped modal=none ↔ N-buttons around the settle boundary never
257
+ // accumulated its 600ms. This tracks the last GOOD-modal frame so a short
258
+ // scroll-out blip is absorbed (settle keeps running against the last captured
259
+ // signature) while a genuinely closed modal — buttons empty continuously past
260
+ // the continuity window — is still recognised and resets the gate.
261
+ private autoApproveLastModalSeenAt = 0;
262
+ // STATUS-MISMATCH: wall-clock when the CURRENT auto-approve episode (waiting_approval
263
+ // + shouldAutoApprove) first began wanting to mask. Unlike pendingAutoApprovalSince it
264
+ // is NOT reset when the modal signature changes (a still-streaming/flapping prompt) and
265
+ // survives the same hysteresis blips the settle gate does, so it measures the TRUE age
266
+ // of an unresolved auto-approve. Once it exceeds AUTO_APPROVE_MASK_STALL_MS the surface
267
+ // mask is dropped so the real waiting_approval surfaces. Cleared when the episode ends
268
+ // (modal genuinely gone, manual attendance takes over, or auto-approve fires).
269
+ private autoApproveMaskSince = 0;
270
+ // NOTIF-APPROVAL-MASKED (Q1b): the autoApproveMaskSince episode value for which a
271
+ // stalled-approval coordinator nudge has already been emitted, so the nudge fires
272
+ // exactly once per stalled auto-approve episode (0 = none emitted). Reusing the
273
+ // per-episode mask-clock value as the key makes it provider-agnostic (no reliance on
274
+ // approvalEntrySeq) and self-resetting: each new episode gets a fresh
275
+ // autoApproveMaskSince timestamp, and the episode-end reset zeroes it.
276
+ private stalledApprovalNudgeEpisode = 0;
277
+ // Provider-common manual-attendance signal: while a human is actively driving
278
+ // this session from the dashboard, auto-approve holds so they can take manual
279
+ // control. Background mesh workers are never attended → delegated auto-approve
280
+ // is unaffected.
281
+ private readonly manualAttendance = new ManualAttendanceTracker();
315
282
  private controlValues: Record<string, string | number | boolean> = {};
316
283
  private summaryMetadata: unknown = undefined;
317
284
  private appliedEffectKeys = new Set<string>();
318
285
  private historyWriter: ChatHistoryWriter;
319
286
  private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
320
287
  private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
288
+ private lastAcknowledgedUserInputAt = 0;
289
+ // TASKBUBBLE-DUP: per-content last-ack timestamps so the same dispatched
290
+ // prompt acked twice in quick succession (the worker buffers the first
291
+ // send during bootstrap/busy, then a redelivery — dispatch-confirm-timeout
292
+ // requeue or a reconcile re-dispatch — fires a SECOND send_chat before the
293
+ // outbound queue drains) collapses to ONE user bubble. Keyed on the trimmed
294
+ // content; an entry older than USER_INPUT_ACK_DEDUP_WINDOW_MS is treated as
295
+ // a fresh, intentional resend and is NOT suppressed.
296
+ private recentUserInputAcks = new Map<string, number>();
321
297
  private lastNativeSourceCanonicalCheckAt = 0;
322
298
  private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
323
299
  private cachedSqliteDb: {
@@ -330,6 +306,7 @@ export class CliProviderInstance implements ProviderInstance {
330
306
  private suppressIdleHistoryReplay = false;
331
307
  private errorMessage: string | undefined = undefined;
332
308
  private errorReason: ProviderErrorReason | undefined = undefined;
309
+ private activeInteractivePrompt: InteractivePrompt | null = null;
333
310
 
334
311
  private presentationMode: 'terminal' | 'chat';
335
312
  private providerSessionId?: string;
@@ -370,7 +347,10 @@ export class CliProviderInstance implements ProviderInstance {
370
347
  this.providerSessionId = options?.providerSessionId;
371
348
  this.launchMode = options?.launchMode || 'new';
372
349
  this.onProviderSessionResolved = options?.onProviderSessionResolved;
373
- this.adapter = new ProviderCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory);
350
+ this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
351
+ if (this.providerSessionId) {
352
+ this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
353
+ }
374
354
  this.monitor = new StatusMonitor();
375
355
  this.historyWriter = new ChatHistoryWriter();
376
356
  }
@@ -389,8 +369,8 @@ export class CliProviderInstance implements ProviderInstance {
389
369
  this.adapter.updateRuntimeSettings?.(this.settings);
390
370
  this.monitor.updateConfig({
391
371
  approvalAlert: this.settings.approvalAlert !== false,
392
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
393
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
372
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
373
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
394
374
  });
395
375
 
396
376
  // Server connection
@@ -412,14 +392,14 @@ export class CliProviderInstance implements ProviderInstance {
412
392
  await this.adapter.spawn();
413
393
  await this.enforceFreshSessionLaunchIfNeeded();
414
394
  this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
415
- if (this.providerSessionId) {
395
+ if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
416
396
  this.restorePersistedHistoryFromCurrentSession();
417
397
  }
418
398
  if (this.providerSessionId && this.launchMode === 'resume') {
419
399
  const resumedAt = Date.now();
420
400
  this.historyWriter.appendSystemMarker(
421
401
  this.type,
422
- `Resumed saved session at ${this.formatMarkerTimestamp(resumedAt)}`,
402
+ `Resumed saved session at ${formatMarkerTimestamp(resumedAt)}`,
423
403
  {
424
404
  instanceId: this.instanceId,
425
405
  historySessionId: this.providerSessionId,
@@ -486,14 +466,38 @@ export class CliProviderInstance implements ProviderInstance {
486
466
  }
487
467
 
488
468
  getState(): ProviderState {
469
+ // TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
470
+ // parseSession) are currently invoked by CliScriptRunner.invoke() via direct
471
+ // function calls — the scripts run in the daemon process with full Node.js
472
+ // access and no resource limits.
473
+ //
474
+ // When Phase 5 lands, CliScriptRunner should route these calls through a
475
+ // SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
476
+ // that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
477
+ // a 32 MB memory cap. The execution path to change is:
478
+ // CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
479
+ //
480
+ // This getState() call-site is NOT where the change goes — the wiring belongs
481
+ // in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
482
+ // parseSession), with provider-loader.ts updated to store script source strings
483
+ // alongside the loaded function references for extended-legacy providers.
489
484
  const adapterStatus = this.adapter.getStatus();
485
+ if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
486
+ this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
487
+ }
490
488
  let parsedStatus: any = null;
491
489
  let parseErrorMessage: string | undefined;
492
490
  if (typeof this.adapter.getScriptParsedStatus === 'function') {
493
491
  try {
494
492
  parsedStatus = this.adapter.getScriptParsedStatus() || null;
495
- this.errorMessage = undefined;
496
- this.errorReason = undefined;
493
+ const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
494
+ ? parsedStatus.errorMessage.trim()
495
+ : undefined;
496
+ const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
497
+ ? parsedStatus.errorReason.trim() as ProviderErrorReason
498
+ : undefined;
499
+ this.errorMessage = parsedErrorMessage;
500
+ this.errorReason = parsedErrorReason;
497
501
  } catch (error: any) {
498
502
  parseErrorMessage = error?.message || String(error);
499
503
  this.errorMessage = parseErrorMessage;
@@ -503,22 +507,59 @@ export class CliProviderInstance implements ProviderInstance {
503
507
  this.errorMessage = undefined;
504
508
  this.errorReason = undefined;
505
509
  }
506
- const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
507
- const visibleStatus = parseErrorMessage
508
- ? 'error'
509
- : (autoApproveActive ? 'generating' : adapterStatus.status);
510
- const parsedProviderSessionId = normalizeProviderSessionId(
510
+ const adapterProviderSessionId = normalizeProviderSessionId(
511
511
  this.provider,
512
- typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
512
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
513
513
  );
514
- if (parsedProviderSessionId) {
515
- this.promoteProviderSessionId(parsedProviderSessionId);
514
+ const nowMs = Date.now();
515
+ // STATUS-MISMATCH: maybeAutoApproveStatus still runs for its side effects (settle gate,
516
+ // resolveModal fire), but the SURFACE mask is dropped once the episode has stalled past
517
+ // AUTO_APPROVE_MASK_STALL_MS — otherwise a never-settling auto-approve hides the worker's
518
+ // waiting_approval + modal from read_chat/mesh_status/dashboard forever.
519
+ const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, nowMs)
520
+ && !this.autoApproveMaskStalled(nowMs);
521
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
522
+ let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
523
+ ? 'error'
524
+ : (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
525
+ // getState() must agree with the status the FSM-driven detectStatusTransition()
526
+ // already committed to lastStatus. The adapter's own status is authoritative; we do
527
+ // not second-guess it with native-transcript shape. Only reconcile a generating-like
528
+ // read down to idle when our own lastStatus has already flipped idle (avoids a
529
+ // perpetual dashboard spinner during the brief window before the next getStatus()).
530
+ if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
531
+ visibleStatus = 'idle';
516
532
  }
517
533
  const runtime = this.adapter.getRuntimeMetadata();
518
534
  this.maybeAppendRuntimeRecoveryMessage(runtime);
519
535
  let parsedMessages = Array.isArray(parsedStatus?.messages)
520
536
  ? parsedStatus.messages
521
537
  : [];
538
+ const parsedProviderSessionId = normalizeProviderSessionId(
539
+ this.provider,
540
+ typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
541
+ );
542
+ const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
543
+ parsedMessages,
544
+ parsedStatus,
545
+ adapterStatus,
546
+ parsedProviderSessionId,
547
+ );
548
+ if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
549
+ this.promoteProviderSessionId(adapterProviderSessionId);
550
+ }
551
+ if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
552
+ this.promoteProviderSessionId(parsedProviderSessionId);
553
+ }
554
+ if (suppressFreshLaunchStartupReplay) {
555
+ parsedMessages = [];
556
+ }
557
+ // Adapter runtime metadata is transport-owned and is not guaranteed to
558
+ // identify this conversation. Spec adapters historically exposed the
559
+ // provider spec id (for example "codex-cli") as runtimeId, which made
560
+ // concurrent sessions share one activeChat identity until their native
561
+ // provider session ids were discovered.
562
+ const activeChatId = this.providerSessionId || this.instanceId;
522
563
  const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
523
564
  ? Math.max(0, Number(parsedStatus.historyMessageCount))
524
565
  : null;
@@ -527,10 +568,21 @@ export class CliProviderInstance implements ProviderInstance {
527
568
  ? parsedMessages.slice(-historyMessageCount)
528
569
  : [];
529
570
  }
530
- const mergedMessages = this.mergeConversationMessages(parsedMessages);
531
- const canonicalBackedHistory = this.syncCanonicalSavedHistoryIfNeeded();
571
+ const mergedMessages = mergeConversationMessages(this.runtimeMessages, parsedMessages);
572
+ const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
573
+ ? this.syncCanonicalSavedHistoryIfNeeded()
574
+ : false;
575
+ const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
576
+ ? this.lastPersistedHistoryMessages.map((message) => ({
577
+ role: message.role,
578
+ content: message.content,
579
+ kind: message.kind,
580
+ senderName: message.senderName,
581
+ receivedAt: message.receivedAt,
582
+ }))
583
+ : mergedMessages;
532
584
 
533
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
585
+ const dirName = workingDirBasename(this.workingDir);
534
586
  const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
535
587
  ? parsedStatus.status.trim()
536
588
  : undefined;
@@ -542,7 +594,7 @@ export class CliProviderInstance implements ProviderInstance {
542
594
  && adapterStatus.status === 'idle'
543
595
  && parsedStatus?.status === 'idle';
544
596
  let messagesToSave = parsedMessages;
545
- if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'long_generating')) {
597
+ if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'no_progress' || parsedChatStatus === 'long_generating')) {
546
598
  const lastIdx = messagesToSave.length - 1;
547
599
  if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === 'assistant') {
548
600
  messagesToSave = messagesToSave.slice(0, lastIdx);
@@ -572,33 +624,48 @@ export class CliProviderInstance implements ProviderInstance {
572
624
  }
573
625
  }
574
626
 
575
- this.applyProviderResponse(parsedStatus, { phase: 'immediate' });
627
+ this.applyProviderResponse(
628
+ suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
629
+ ? { ...parsedStatus, providerSessionId: undefined }
630
+ : parsedStatus,
631
+ { phase: 'immediate' },
632
+ );
576
633
  const surface = resolveProviderStateSurface({
577
634
  summaryMetadata: this.summaryMetadata as any,
578
635
  controlValues: this.controlValues,
579
636
  });
580
637
  const activeChatStatus = parseErrorMessage
581
638
  ? 'error'
582
- : autoApproveActive && parsedStatus?.status === 'waiting_approval'
639
+ : (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
583
640
  ? 'generating'
584
641
  : (adapterStatus.status !== 'idle'
585
642
  ? visibleStatus
586
643
  : (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
587
644
 
645
+ // If an AskUserQuestion prompt is awaiting user input, overlay status as
646
+ // waiting_choice. This is distinct from waiting_approval (tool-use consent)
647
+ // — the engine's isWaitingForResponse state is unchanged, so completion
648
+ // tracking continues normally once the user responds.
649
+ const hasInteractivePrompt = !!this.activeInteractivePrompt;
650
+ const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
651
+ const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
652
+
588
653
  return {
589
654
  type: this.type,
590
655
  name: this.provider.name,
591
656
  category: 'cli',
592
- status: visibleStatus,
657
+ status: finalStatus,
593
658
  mode: this.presentationMode,
594
659
  activeChat: {
595
- id: `${this.type}_${this.workingDir}`,
660
+ id: activeChatId,
596
661
  title: parsedStatus?.title || dirName,
597
- status: activeChatStatus,
598
- messages: mergedMessages,
599
- activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
662
+ status: finalChatStatus,
663
+ messages: statusMessages,
664
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
665
+ activeInteractivePrompt: this.activeInteractivePrompt,
600
666
  inputContent: '',
601
667
  },
668
+ activeInteractivePrompt: this.activeInteractivePrompt,
602
669
  workspace: this.workingDir,
603
670
  instanceId: this.instanceId,
604
671
  providerSessionId: this.providerSessionId,
@@ -638,8 +705,12 @@ export class CliProviderInstance implements ProviderInstance {
638
705
 
639
706
  getHotChatSessionState(): HotChatSessionState {
640
707
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
641
- const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
642
- const visibleStatus = autoApproveActive ? 'generating' : adapterStatus.status;
708
+ const nowMs = Date.now();
709
+ // STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
710
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
711
+ && !this.autoApproveMaskStalled(nowMs);
712
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
713
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
643
714
  const runtime = this.adapter.getRuntimeMetadata();
644
715
  return {
645
716
  id: this.instanceId,
@@ -651,36 +722,274 @@ export class CliProviderInstance implements ProviderInstance {
651
722
  };
652
723
  }
653
724
 
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';
725
+ getSessionModalState(sessionId?: string): SessionModalState {
726
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
727
+ const nowMs = Date.now();
728
+ // STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
729
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
730
+ && !this.autoApproveMaskStalled(nowMs);
731
+ const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
732
+ const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
733
+ const dirName = workingDirBasename(this.workingDir);
659
734
  return {
660
- id: this.instanceId,
735
+ // Honor the caller-supplied sessionId — InstanceMgr rejects the
736
+ // projection when projected.id !== requested sessionId, and
737
+ // this.instanceId is the manager's internal key, not the public
738
+ // sessionId the dashboard subscribes by.
739
+ id: sessionId ?? this.instanceId,
661
740
  status: visibleStatus,
662
741
  title: dirName,
663
- activeModal: autoApproveActive ? null : adapterStatus.activeModal,
742
+ activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
664
743
  };
665
744
  }
666
745
 
667
746
  updateSettings(newSettings: Record<string, any>): void {
668
- this.settings = { ...newSettings };
747
+ // Merge semantics: a key omitted from newSettings preserves its existing
748
+ // value, a key present in newSettings (even as false) overrides it.
749
+ //
750
+ // This is required because updateSettings has two callers with opposite
751
+ // intent:
752
+ // 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
753
+ // → getSettings → updateInstanceSettings) sends the COMPLETE settings
754
+ // object, so an explicit autoApprove:false must win.
755
+ // 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
756
+ // buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
757
+ // meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
758
+ // re-dispatch. It carries no autoApprove, so a full replacement would
759
+ // wipe the launch-time autoApprove:true the worker was started with,
760
+ // silently dropping every later approval to a manual gate until the
761
+ // machine-page toggle re-injected the full settings.
762
+ //
763
+ // A plain merge satisfies both: undefined keys fall through to the existing
764
+ // value (preserving launch-stamp settings like autoApprove + the mesh routing
765
+ // keys), explicit keys override. This subsumes the previous mesh-key preserve
766
+ // list, which only protected the routing keys and not autoApprove.
767
+ this.settings = { ...this.settings, ...newSettings };
669
768
  this.adapter.updateRuntimeSettings?.(this.settings);
670
769
  this.monitor.updateConfig({
671
770
  approvalAlert: this.settings.approvalAlert !== false,
672
- longGeneratingAlert: this.settings.longGeneratingAlert !== false,
673
- longGeneratingThresholdSec: this.settings.longGeneratingThresholdSec || 180,
771
+ noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
772
+ noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
674
773
  });
675
774
  }
676
775
 
776
+ /**
777
+ * Stamp a direct-dispatch mesh assignment on this instance.
778
+ * setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
779
+ * route generating_completed back to the originating coordinator. Without
780
+ * this stamp, mesh_send_task --direct targets a plain CLI session whose
781
+ * completion events silently drop because the forwarder has nothing to
782
+ * match against.
783
+ */
784
+ attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string; coordinatorSessionId?: string }): void {
785
+ if (!assignment?.meshId) return;
786
+ this.settings = {
787
+ ...this.settings,
788
+ meshNodeFor: assignment.meshId,
789
+ // WTCLAIM (A): track the bound node id under BOTH the active marker
790
+ // (meshNodeId, cleared on detach) and a sticky marker (meshLastNodeId,
791
+ // preserved across detach). The sticky marker lets a detached but still
792
+ // coordinator-owned session be re-picked ONLY for the SAME node it served
793
+ // — never auto-adopted for a sibling node (e.g. a cloned worktree) that
794
+ // shares this daemon. See isMeshOwnedDelegateSession's post-detach gate.
795
+ ...(assignment.nodeId ? { meshNodeId: assignment.nodeId, meshLastNodeId: assignment.nodeId } : {}),
796
+ ...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
797
+ ...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
798
+ // Session-level routing anchor: the originating coordinator session, so this
799
+ // worker's completion events route back to the exact session that dispatched it.
800
+ ...(assignment.coordinatorSessionId ? { meshCoordinatorSessionId: assignment.coordinatorSessionId } : {}),
801
+ };
802
+ this.adapter.updateRuntimeSettings?.(this.settings);
803
+ }
804
+
805
+ /**
806
+ * Clear a previously-attached mesh assignment after the task reaches a
807
+ * terminal state. Leaving meshNodeFor pinned would route this session's
808
+ * subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
809
+ * coordinator as if they were task completions.
810
+ *
811
+ * MESHID-DROP-ON-DETACH (Fix C): a coordinator-LAUNCHED worker session
812
+ * (launchedByCoordinator) holds its mesh membership (meshNodeFor / meshNodeId /
813
+ * meshCoordinatorDaemonId) at the SESSION level — set once at launch
814
+ * (mesh_launch_session / queue auto-launch), independent of any single task.
815
+ * The original detach wiped meshNodeFor + meshNodeId together with the
816
+ * task-level meshActiveTaskId, so the FIRST task completion stripped the
817
+ * membership and EVERY subsequent completion forwarded with meshId absent —
818
+ * resolveWorkerDelegateRouting fell to mesh_unresolved and the coordinator
819
+ * rejected the forward "meshId required". For a launched member we therefore
820
+ * clear ONLY the task-level marker (meshActiveTaskId) and preserve the
821
+ * session-level membership so its next task's completion still resolves.
822
+ * A task-less ad-hoc turn on a preserved-membership session is NOT misrouted:
823
+ * its completion carries no taskId and the session holds no active assignment,
824
+ * so the forwarder's WARMUPGAP guard skips the dispatch-row flip (it only
825
+ * injects a benign task-less notification). A NON-launched session (a plain CLI
826
+ * session adopted by mesh_send_task --direct, launchedByCoordinator falsy)
827
+ * keeps the original full clear so an ad-hoc session is never left pinned.
828
+ */
829
+ detachMeshAssignment(): void {
830
+ if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
831
+ // Session-level member: keep membership, drop only the task-level marker.
832
+ if (this.settings.launchedByCoordinator === true) {
833
+ if (!this.settings.meshActiveTaskId) return;
834
+ const { meshActiveTaskId, ...rest } = this.settings;
835
+ void meshActiveTaskId;
836
+ this.settings = rest;
837
+ this.adapter.updateRuntimeSettings?.(this.settings);
838
+ return;
839
+ }
840
+ const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
841
+ void meshNodeFor; void meshActiveTaskId;
842
+ // WTCLAIM (A): clear the active binding but PRESERVE the last bound node id
843
+ // (meshLastNodeId) so a later sessionless dispatch can re-adopt this idle
844
+ // session ONLY for the node it last served. Carry the id being cleared, or
845
+ // keep an already-present sticky marker if meshNodeId was absent.
846
+ const lastNodeId = (typeof meshNodeId === 'string' && meshNodeId.trim())
847
+ ? meshNodeId.trim()
848
+ : (typeof rest.meshLastNodeId === 'string' && rest.meshLastNodeId.trim() ? rest.meshLastNodeId.trim() : undefined);
849
+ this.settings = lastNodeId ? { ...rest, meshLastNodeId: lastNodeId } : rest;
850
+ this.adapter.updateRuntimeSettings?.(this.settings);
851
+ }
852
+
853
+ /**
854
+ * The resolved modal-park status of this session, or null when it is not
855
+ * parked on a modal awaiting a human answer. Mirrors the overlay logic in
856
+ * getState(): an active AskUserQuestion interactive prompt resolves to
857
+ * waiting_choice; otherwise the adapter's waiting_approval (tool consent)
858
+ * counts — UNLESS auto-approve will dismiss it, in which case the session is
859
+ * effectively generating and is NOT modal-parked. This is the single signal
860
+ * the mesh force-inject guard consults, and the same status string the
861
+ * reconcile loop reads off get_status_metadata. Lowercase literals only —
862
+ * the SessionStatus enum is forked across modules and waiting_choice is
863
+ * absent from some of them.
864
+ */
865
+ resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
866
+ if (this.activeInteractivePrompt) return 'waiting_choice';
867
+ let adapterStatus: { status?: string };
868
+ try {
869
+ adapterStatus = this.adapter.getStatus({ allowParse: false });
870
+ } catch {
871
+ return null;
872
+ }
873
+ // A session whose auto-approve is held by manual attendance IS parked on a
874
+ // modal awaiting the human — autoApproveEffectivelyActive folds that in, so
875
+ // the mesh force-inject guard correctly treats it as modal-parked. STATUS-MISMATCH:
876
+ // a STALLED auto-approve (never resolving) is likewise effectively parked — treat it
877
+ // as modal-parked so its events are held/surfaced rather than masked behind generating.
878
+ if (adapterStatus.status === 'waiting_approval'
879
+ && (!this.autoApproveEffectivelyActive(adapterStatus.status) || this.autoApproveMaskStalled())) {
880
+ // NOTIF-HELD-DRAIN (Fix 1): an autonomous mesh session (coordinator or worker)
881
+ // that is actively progressing a turn — a tool call is in flight
882
+ // (hasAdapterPendingResponse) and NO human is attending it by hand — surfaces a
883
+ // routine tool-consent `waiting_approval` on EVERY tool call when auto-approve is
884
+ // off. That transient consent is part of the turn the harness/operator drives to
885
+ // completion, NOT a session genuinely wedged awaiting a human's modal answer.
886
+ // Classifying it modal-parked makes findLiveCoordinators hold the mesh's pending
887
+ // completion events under `modal_parked` across a busy coordinator's whole work
888
+ // batch, which is the multi-minute notification stall. Treat such a transient
889
+ // consent as NOT modal-parked so it is held as ordinary "generating" (released on
890
+ // the next idle) instead. A manually-attended session, a stalled auto-approve, or a
891
+ // non-progressing session (no turn in flight) still parks — those are the genuine
892
+ // human-await cases the guard must keep holding.
893
+ if (this.isTransientToolConsent()) {
894
+ return null;
895
+ }
896
+ return 'waiting_approval';
897
+ }
898
+ return null;
899
+ }
900
+
901
+ /**
902
+ * NOTIF-HELD-DRAIN: true when this `waiting_approval` is a routine, transient tool-consent
903
+ * of an autonomously-progressing mesh session rather than a genuine human-await modal —
904
+ * i.e. it is a mesh coordinator/worker session, a turn is actively in flight
905
+ * (hasAdapterPendingResponse), and no human is attending it by hand. Such a consent is
906
+ * driven to resolution by the harness/operator as part of the in-flight turn, so holding
907
+ * the mesh's completion events behind it (modal_parked) is the false-positive that stalls
908
+ * delivery. Narrow by design: manual attendance or a non-progressing session falls through
909
+ * to the genuine-modal classification.
910
+ */
911
+ private isTransientToolConsent(now = Date.now()): boolean {
912
+ return this.isAutonomousMeshSession()
913
+ && this.hasAdapterPendingResponse()
914
+ && !this.manualAttendance.isAttended(now);
915
+ }
916
+
917
+ /** True when this session is parked on a modal awaiting a human answer. */
918
+ isModalParked(): boolean {
919
+ return this.resolveModalParkStatus() !== null;
920
+ }
921
+
922
+ /**
923
+ * PTY-OVERTRUST-DRAIN (Defect B). The deliverability/drain status the mesh
924
+ * reconcile loop must consult — the RAW adapter turn-state, with the
925
+ * auto-approve "hold-idle" visual mask STRIPPED.
926
+ *
927
+ * getState().status overlays `autoApproveHoldIdle`/`autoApproveActive` to paint a
928
+ * genuinely-idle adapter as `generating` (a UI-flicker suppression while an
929
+ * auto-approve key-press settles — see getState() ~:800). That mask is correct
930
+ * for the dashboard, but the reconcile loop trusts it as "the coordinator is
931
+ * busy" and therefore HOLDS a worker's completion under
932
+ * `generating_no_idle_coordinator` even though the coordinator's PTY is at a real
933
+ * turn end and would accept the inject as a turn — the completion is stranded.
934
+ *
935
+ * This accessor reports the drain truth instead:
936
+ * - 'modal_parked' — a GENUINE human-await modal (AskUserQuestion / a non-
937
+ * transient tool-consent). Still excluded from drain (a force-inject here
938
+ * writes raw keystrokes the modal eats → data corruption). Mirrors
939
+ * isModalParked(), evaluated first so a parked session never reads idle.
940
+ * - 'idle' — the RAW adapter is at a turn end (adapter.getStatus(allowParse:false)
941
+ * === 'idle') and the session is not modal-parked. Drain-eligible REGARDLESS
942
+ * of the auto-approve mask. This is the case the mask used to hide.
943
+ * - 'generating' — the raw adapter is genuinely mid-turn. Held (a raw PTY write
944
+ * into a generating claude-cli is not consumed as a turn → data loss). The
945
+ * intentional removal of force-inject-into-generating is preserved.
946
+ * - 'other' — any other raw status (error / starting / waiting_choice handled by
947
+ * modal-park above). Not a drain target.
948
+ *
949
+ * Uses allowParse:false (engine.activeModal only, side-effect-free) so it never
950
+ * mutates the very auto-approve mask state the diagnostics read.
951
+ */
952
+ getDrainStatus(): 'idle' | 'generating' | 'modal_parked' | 'other' {
953
+ if (this.isModalParked()) return 'modal_parked';
954
+ let rawStatus: string;
955
+ try {
956
+ const raw = this.adapter.getStatus({ allowParse: false })?.status;
957
+ rawStatus = typeof raw === 'string' ? raw.trim() : '';
958
+ } catch {
959
+ return 'other';
960
+ }
961
+ if (rawStatus === 'idle') return 'idle';
962
+ if (isCliGeneratingLikeStatus(rawStatus)) return 'generating';
963
+ return 'other';
964
+ }
965
+
677
966
  onEvent(event: string, data?: any): void {
678
967
  if (event === 'send_message') {
679
968
  const input = normalizeInputEnvelope(data);
680
969
  assertProviderSupportsDeclaredInput(this.provider, input);
681
970
  const promptText = buildCliStructuredInputPrompt(input);
682
971
  if (promptText) {
683
- void this.adapter.sendMessage(promptText).catch((e: any) => {
972
+ // force:true bypasses the busy/generating send guard so terminal mesh
973
+ // events (completion/failure/bootstrap) land in a coordinator session that
974
+ // is itself parked in `generating` while awaiting that very event.
975
+ // Without it the message is queued and only flushed on the coordinator's
976
+ // own idle transition — which never happens until it receives the message.
977
+ const force = data?.force === true;
978
+ // Modal guard: a force-inject still writes raw keystrokes into the PTY,
979
+ // bypassing the busy send-guard. If the coordinator is parked on a
980
+ // harness modal (claude-cli AskUserQuestion → waiting_choice, or a
981
+ // tool-consent waiting_approval), those keystrokes are consumed by the
982
+ // modal's key handler and silently select a choice the user never made
983
+ // (data corruption). Hold the force-inject in that narrow window —
984
+ // the event stays queued and the reconcile loop redelivers it on the
985
+ // next tick once the modal is resolved. We ONLY hold for the two modal
986
+ // states; generating is still force-injected (that is the deadlock the
987
+ // force path exists to break — see mesh-events-coordinator).
988
+ if (force && this.isModalParked()) {
989
+ LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
990
+ return;
991
+ }
992
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
684
993
  LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
685
994
  });
686
995
  }
@@ -690,14 +999,118 @@ export class CliProviderInstance implements ProviderInstance {
690
999
  void this.adapter.resolveAction(data).catch((e: any) => {
691
1000
  LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
692
1001
  });
1002
+ } else if (event === 'interactive_prompt' && data) {
1003
+ const prompt = normalizeInteractivePrompt(data);
1004
+ if (prompt) {
1005
+ this.activeInteractivePrompt = prompt;
1006
+ this.events.push({
1007
+ event: 'interactive_prompt',
1008
+ timestamp: Date.now(),
1009
+ promptId: prompt.promptId,
1010
+ });
1011
+ }
1012
+ } else if (event === 'interactive_prompt_response' && data) {
1013
+ try {
1014
+ const response = normalizeInteractivePromptResponse(data);
1015
+ if (this.activeInteractivePrompt?.promptId === response.promptId) {
1016
+ this.activeInteractivePrompt = null;
1017
+ }
1018
+ if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
1019
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
1020
+ return;
1021
+ }
1022
+ void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
1023
+ LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
1024
+ });
1025
+ } catch (e: any) {
1026
+ LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
1027
+ }
693
1028
  } else if (event === 'provider_state_patch' && data && typeof data === 'object') {
694
1029
  this.applyProviderResponse(data, { phase: 'immediate' });
695
1030
  }
696
1031
  }
697
1032
 
1033
+ recordAcknowledgedUserInput(input: InputEnvelope | string): void {
1034
+ const content = typeof input === 'string'
1035
+ ? input.trim()
1036
+ : buildCliStructuredInputPrompt(input).trim();
1037
+ if (!content) return;
1038
+
1039
+ const receivedAt = Date.now();
1040
+
1041
+ // TASKBUBBLE-DUP: collapse a redelivered dispatch to one bubble. A single
1042
+ // mesh_send_task can reach this instance as TWO send_chat calls when the
1043
+ // first injection is buffered during bootstrap/busy and a retry (dispatch-
1044
+ // confirm-timeout requeue, or a reconcile re-dispatch) fires before the
1045
+ // outbound queue drains. The previous dedupKey hashed receivedAt, so the
1046
+ // two acks produced different keys and BOTH bubbled. Suppress an identical
1047
+ // content ack seen within USER_INPUT_ACK_DEDUP_WINDOW_MS; a later resend of
1048
+ // the same text (beyond the window) is a genuine new turn and still shows.
1049
+ const ackContentKey = shortHash(`${this.instanceId}:${content}`, 24);
1050
+ const lastAckAt = this.recentUserInputAcks.get(ackContentKey);
1051
+ if (lastAckAt !== undefined && receivedAt - lastAckAt <= USER_INPUT_ACK_DEDUP_WINDOW_MS) {
1052
+ // Refresh the timestamp so a steady stream of redeliveries keeps
1053
+ // collapsing, and prune stale entries to bound the map size.
1054
+ this.recentUserInputAcks.set(ackContentKey, receivedAt);
1055
+ this.pruneRecentUserInputAcks(receivedAt);
1056
+ return;
1057
+ }
1058
+ this.recentUserInputAcks.set(ackContentKey, receivedAt);
1059
+ this.pruneRecentUserInputAcks(receivedAt);
1060
+
1061
+ this.lastAcknowledgedUserInputAt = receivedAt;
1062
+ // The runtimeMessages dedupKey stays per-call unique (includes receivedAt)
1063
+ // so a genuine resend of the same text after the window appends a fresh
1064
+ // bubble; redelivery within the window is already suppressed above.
1065
+ const dedupKey = `user_input_ack:${shortHash(`${this.instanceId}:${content}:${receivedAt}`, 24)}`;
1066
+ this.appendRuntimeMessage(buildChatMessage({
1067
+ role: 'user',
1068
+ senderName: 'User',
1069
+ kind: 'standard',
1070
+ content,
1071
+ receivedAt,
1072
+ timestamp: receivedAt,
1073
+ source: 'runtime_input_ack',
1074
+ meta: {
1075
+ runtimeInputAck: true,
1076
+ provider: this.type,
1077
+ workspace: this.workingDir,
1078
+ },
1079
+ } as ChatMessage), dedupKey);
1080
+ }
1081
+
1082
+ /** Drop user-input ack entries older than the dedup window so the map can't grow unbounded. */
1083
+ private pruneRecentUserInputAcks(now: number): void {
1084
+ if (this.recentUserInputAcks.size <= 1) return;
1085
+ for (const [key, at] of this.recentUserInputAcks) {
1086
+ if (now - at > USER_INPUT_ACK_DEDUP_WINDOW_MS) this.recentUserInputAcks.delete(key);
1087
+ }
1088
+ }
1089
+
1090
+ /**
1091
+ * Owner token for this session in the antigravity conversation-claim
1092
+ * registry. Derived identically to the dispatcher's read-side token
1093
+ * (workspace + spawn time) so the claims the dispatcher records under this
1094
+ * session are the ones dispose() releases.
1095
+ */
1096
+ private antigravityClaimOwner(): string {
1097
+ return antigravityOwnerToken(this.workingDir, this.startedAt);
1098
+ }
1099
+
698
1100
  dispose(): void {
1101
+ // Release this session's antigravity conversation claims so the store
1102
+ // becomes available again (e.g. a later resume) and the registry doesn't
1103
+ // leak entries for dead sessions.
1104
+ if (this.type === 'antigravity-cli') {
1105
+ const owner = this.antigravityClaimOwner();
1106
+ if (owner) releaseAntigravityOwner(owner);
1107
+ }
699
1108
  this.adapter.shutdown();
700
1109
  this.monitor.reset();
1110
+ // Cancel any armed auto-approve timers so a pending settle re-check
1111
+ // can't fire resolveModal/detectStatusTransition against a dead adapter.
1112
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
1113
+ if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
701
1114
  this.appliedEffectKeys.clear();
702
1115
  try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
703
1116
  this.cachedSqliteDb = null;
@@ -706,6 +1119,7 @@ export class CliProviderInstance implements ProviderInstance {
706
1119
 
707
1120
  private completedDebounceTimer: NodeJS.Timeout | null = null;
708
1121
  private completedDebouncePending: CompletedDebouncePending | null = null;
1122
+ private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
709
1123
 
710
1124
  private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
711
1125
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
@@ -734,13 +1148,233 @@ export class CliProviderInstance implements ProviderInstance {
734
1148
  this.applyProviderResponse(parsed.payload, { phase: 'immediate' });
735
1149
  }
736
1150
 
737
- private completionHasFinalAssistantMessage(messages: unknown): boolean {
1151
+ private completionHasFinalAssistantMessage(messages: unknown, turnStartedAt?: number): boolean {
738
1152
  const visibleMessages = (Array.isArray(messages) ? messages : [])
739
1153
  .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
740
1154
  const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
741
1155
  const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
742
1156
  const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
743
- return role === 'assistant' && !!content;
1157
+ if (role !== 'assistant' || !content) return false;
1158
+ // Guard: if the last assistant message looks like an active approval/input prompt,
1159
+ // it is not a real completion — the session is still awaiting user input.
1160
+ if (looksLikeActiveApprovalPromptText(content)) return false;
1161
+ // FALSE-IDLE turn-boundary evidence (Defect 1b): when a producing-turn start is
1162
+ // known, the final assistant bubble must POST-DATE it. A STALE mid-turn assistant
1163
+ // (predating this turn's start — e.g. the last bubble of a prior sub-turn observed
1164
+ // during an inter-approval valley) must NOT satisfy the finalization gate, or a
1165
+ // false-idle blip emits a completion carrying that stale summary. A bubble with no
1166
+ // parseable timestamp cannot be proven stale, so it is kept (fails open — behaviour
1167
+ // identical to before for providers/paths that carry no timestamps).
1168
+ if (typeof turnStartedAt === 'number' && Number.isFinite(turnStartedAt) && turnStartedAt > 0) {
1169
+ // readChatMessageTimestampMs mirrors the summary turn-scoping reader
1170
+ // (extractFinalSummaryFromMessagesAfter) — same seconds-vs-ms heuristic and
1171
+ // field precedence — so the present-check and the summary-scope agree on which
1172
+ // bubbles predate the turn.
1173
+ const ts = readChatMessageTimestampMs(lastVisible);
1174
+ if (typeof ts === 'number' && ts < turnStartedAt) return false;
1175
+ }
1176
+ return true;
1177
+ }
1178
+
1179
+ private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
1180
+ const probe = this.lastExternalCompletionProbe;
1181
+ if (!probe) return null;
1182
+ const history = pending.transcriptProbeHistory || [];
1183
+ const last = history[history.length - 1];
1184
+ if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
1185
+ history.push(probe);
1186
+ pending.transcriptProbeHistory = history.slice(-5);
1187
+ }
1188
+ return probe;
1189
+ }
1190
+
1191
+ /**
1192
+ * The spawned CLI's env overrides (e.g. the mesh coordinator points hermes
1193
+ * at a per-coordinator HERMES_HOME so its state.db lives in a tmpdir instead
1194
+ * of ~/.hermes). The native-history executor expands `${HERMES_HOME:-~/.hermes}`
1195
+ * from this map, so the completion gate MUST pass it through — otherwise the
1196
+ * gate reads ~/.hermes, finds no coordinator-session transcript, and
1197
+ * false-fires missing_final_assistant on every coordinator turn.
1198
+ */
1199
+ private spawnedEnvOverrides(): Record<string, string> | undefined {
1200
+ const meta = typeof (this.adapter as any)?.getRuntimeMetadata === 'function'
1201
+ ? (this.adapter as any).getRuntimeMetadata()
1202
+ : undefined;
1203
+ const env = meta && typeof meta === 'object' ? (meta as Record<string, unknown>).spawnedEnv : undefined;
1204
+ return env && typeof env === 'object' ? env as Record<string, string> : undefined;
1205
+ }
1206
+
1207
+ private readExternalCompletionMessages(): unknown[] | null {
1208
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1209
+ if (!adapterOwnsMessagesElsewhere) return null;
1210
+ if (!this.providerSessionId) return null;
1211
+ if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
1212
+
1213
+ if (this.lastExternalCompletionProbe?.sourcePath) {
1214
+ try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
1215
+ }
1216
+ const restoredHistory = readProviderChatHistory(this.type, {
1217
+ canonicalHistory: this.provider.nativeHistory,
1218
+ historySessionId: this.providerSessionId,
1219
+ workspace: this.workingDir,
1220
+ offset: 0,
1221
+ limit: Number.MAX_SAFE_INTEGER,
1222
+ historyBehavior: this.provider.historyBehavior,
1223
+ scripts: this.provider.scripts as any,
1224
+ sessionStartedAtMs: this.startedAt,
1225
+ envOverrides: this.spawnedEnvOverrides(),
1226
+ forceRefresh: true,
1227
+ });
1228
+ if (restoredHistory.source !== 'provider-native') {
1229
+ this.lastExternalCompletionProbe = null;
1230
+ return null;
1231
+ }
1232
+ this.lastExternalCompletionProbe = buildExternalTranscriptProbe(
1233
+ restoredHistory.messages,
1234
+ restoredHistory.sourcePath,
1235
+ restoredHistory.sourceMtimeMs,
1236
+ );
1237
+ return restoredHistory.messages;
1238
+ }
1239
+
1240
+ private completionFinalAssistantEvidence(parsedMessages: unknown, turnStartedAt?: number): CompletionFinalAssistantEvidence {
1241
+ // (FALSEIDLE FixB) UPPER-BOUND turn-end evidence. completionHasFinalAssistantMessage is a
1242
+ // pure message-content check ("does the last visible bubble read as a finalized assistant
1243
+ // reply, post-dating the turn start?"). That LOWER bound alone treated the FIRST assistant
1244
+ // bubble of a turn that is STILL running — a tool call in flight between two assistant
1245
+ // bubbles — as proof the turn ended (RCA cases a & b). Require in ADDITION that the turn is
1246
+ // genuinely OVER: hasAdapterPendingResponse() folds the three upper-bound discriminators
1247
+ // into one — currentTurnScope closed, no in-flight tool (isProcessing false), and no partial
1248
+ // response buffer. So a mid-turn point-sample (short-gen / fast-collapse inline paths that
1249
+ // do NOT route through getCompletedFinalizationBlock) yields present=false and is held/settled
1250
+ // rather than fired. A genuinely-finished turn (adapter idle, no pending) is unaffected — the
1251
+ // gate stays open and the completion fires exactly as before. This mirrors the established
1252
+ // `completionHasFinalAssistantMessage(...) && !hasAdapterPendingResponse()` pairing already
1253
+ // used by the no-progress monitor reconcile path.
1254
+ const turnClosed = !this.hasAdapterPendingResponse();
1255
+ if (this.completionHasFinalAssistantMessage(parsedMessages, turnStartedAt)) {
1256
+ return {
1257
+ present: turnClosed,
1258
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1259
+ source: 'parsed',
1260
+ };
1261
+ }
1262
+
1263
+ const externalMessages = this.readExternalCompletionMessages();
1264
+ if (externalMessages) {
1265
+ return {
1266
+ present: turnClosed && this.completionHasFinalAssistantMessage(externalMessages, turnStartedAt),
1267
+ messages: externalMessages,
1268
+ source: 'external-native',
1269
+ };
1270
+ }
1271
+
1272
+ return {
1273
+ present: false,
1274
+ messages: Array.isArray(parsedMessages) ? parsedMessages : [],
1275
+ source: 'unavailable',
1276
+ };
1277
+ }
1278
+
1279
+ private completionFinalSummary(parsedMessages: unknown, turnStartedAt?: number): string | undefined {
1280
+ // For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
1281
+ // screen parse is NOT the source of truth for the final summary — the terminal
1282
+ // wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
1283
+ // prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
1284
+ // the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
1285
+ // to the parsed screen only when the transcript is unavailable. This is the real cause
1286
+ // of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
1287
+ // any short, fast-completing task where screen parse wins the race).
1288
+ //
1289
+ // NOTIF Defect-B: `turnStartedAt` (the producing turn's start, snapshotted on the
1290
+ // completedDebouncePending record) turn-scopes the NATIVE transcript read. The native
1291
+ // transcript holds the WHOLE session filtered only by session start, so a debounce that
1292
+ // flushes before the producing turn's final assistant bubble has landed would otherwise
1293
+ // return the PRIOR task's last bubble (event taskId=B but summary=A). Filtering to bubbles
1294
+ // at/after turnStartedAt yields '' in that race instead of the stale tail; the weak/empty
1295
+ // summary is later upgraded by the mesh reconcile loop once the real bubble is written.
1296
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1297
+ // FALSE-IDLE Defect 1b: turn-scope the PARSED screen fallback too. Without this a stale
1298
+ // mid-turn assistant (predating turnStartedAt) that the turn-boundary gate already
1299
+ // rejected as evidence could still leak into the finalSummary via this parsed fallback
1300
+ // when the external transcript's turn-scoped read is empty — freezing the very stale text
1301
+ // the gate rejected. extractFinalSummaryFromMessagesAfter drops bubbles before the turn
1302
+ // start; with no boundary known (turnStartedAt falsy) it is identical to the unscoped read.
1303
+ const parsedSummary = extractFinalSummaryFromMessagesAfter(
1304
+ (this.completionHasFinalAssistantMessage(parsedMessages, turnStartedAt)
1305
+ ? (Array.isArray(parsedMessages) ? parsedMessages : [])
1306
+ : []) as any,
1307
+ turnStartedAt,
1308
+ );
1309
+ if (adapterOwnsMessagesElsewhere) {
1310
+ const externalMessages = this.readExternalCompletionMessages();
1311
+ // Turn-scope the external transcript: never return a bubble produced before this
1312
+ // turn started. With no boundary known (turnStartedAt falsy) behaviour is unchanged.
1313
+ const externalSummary = externalMessages
1314
+ ? extractFinalSummaryFromMessagesAfter(externalMessages as any, turnStartedAt)
1315
+ : '';
1316
+ // The transcript is authoritative for native-source providers. Use it unless it is
1317
+ // empty (not yet written, or no in-turn bubble) — only then fall back to the screen
1318
+ // parse, which reflects the LIVE screen (this turn's output), not the stale tail.
1319
+ if (externalSummary) return externalSummary;
1320
+ return parsedSummary || undefined;
1321
+ }
1322
+ return parsedSummary || undefined;
1323
+ }
1324
+
1325
+ private buildCompletedFinalizationDiagnostic(args: {
1326
+ blockReason: string;
1327
+ latestStatus?: any;
1328
+ latestVisibleStatus: string;
1329
+ waitedMs: number;
1330
+ pending: CompletedDebouncePending;
1331
+ emittedAfterFinalizationTimeout: boolean;
1332
+ }): Record<string, unknown> {
1333
+ let parsed: any = null;
1334
+ let parseError: string | undefined;
1335
+ try {
1336
+ parsed = this.adapter.getScriptParsedStatus();
1337
+ } catch (error: any) {
1338
+ parseError = error?.message || String(error);
1339
+ }
1340
+
1341
+ const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
1342
+ if (evidence.source === 'external-native') {
1343
+ this.recordPendingTranscriptProbe(args.pending);
1344
+ }
1345
+ const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
1346
+ .filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
1347
+ const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
1348
+ const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
1349
+ const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
1350
+ const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
1351
+
1352
+ return {
1353
+ providerType: this.type,
1354
+ sessionId: this.instanceId,
1355
+ providerSessionId: this.providerSessionId || null,
1356
+ workspace: this.workingDir,
1357
+ blockReason: args.blockReason,
1358
+ emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
1359
+ waitedMs: args.waitedMs,
1360
+ maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
1361
+ adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
1362
+ latestVisibleStatus: args.latestVisibleStatus,
1363
+ parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
1364
+ parseError: parseError || undefined,
1365
+ finalAssistantPresent: evidence.present,
1366
+ finalAssistantEvidenceSource: evidence.source,
1367
+ visibleMessageCount: visibleMessages.length,
1368
+ lastVisibleRole,
1369
+ lastVisibleKind,
1370
+ lastVisibleContentLength,
1371
+ pendingStartedAt: this.generatingStartedAt || null,
1372
+ pendingFirstObservedAt: args.pending.firstObservedAt,
1373
+ pendingTimestamp: args.pending.timestamp,
1374
+ pendingDurationSec: args.pending.duration,
1375
+ previousBlockReason: args.pending.loggedBlockReason || null,
1376
+ transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
1377
+ };
744
1378
  }
745
1379
 
746
1380
  private hasAdapterPendingResponse(): boolean {
@@ -765,41 +1399,310 @@ export class CliProviderInstance implements ProviderInstance {
765
1399
  if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
766
1400
  if (adapterRawStatus !== 'idle') return false;
767
1401
  if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
768
- return !this.hasAdapterPendingResponse();
1402
+ if (this.hasAdapterPendingResponse()) return false;
1403
+ // Do not suppress when the adapter's raw response buffer is still non-empty.
1404
+ // This catches the case where isWaitingForResponse has already flipped to false
1405
+ // (so getPartialResponse() returns '') but the provider's native parser still
1406
+ // reports generating because it's parsing buffered content. Suppressing the
1407
+ // finalization block here would emit a false completion event while the provider
1408
+ // session is still actively processing its response stream.
1409
+ const adapterAny = this.adapter as any;
1410
+ if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
1411
+ return true;
769
1412
  }
770
1413
 
771
- private getCompletedFinalizationBlockReason(latestVisibleStatus: string): string | null {
772
- if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}`;
1414
+ private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1415
+ if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
773
1416
 
774
1417
  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';
1418
+ const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
1419
+ // (FALSEIDLE-a FixA) The adapter pending-response checks run UNCONDITIONALLY.
1420
+ // Previously they were SKIPPED when approvalResolvedIdle, on the assumption that
1421
+ // a waiting_approval→idle transition proved the approval's turn was over. But
1422
+ // auto-approve RESOLVES the modal and the agent RESUMES the same turn — currentTurnScope
1423
+ // / isWaitingForResponse stay set, or a tool runs — so skipping the guard let the FIRST
1424
+ // assistant bubble of the still-running turn be mistaken for the last and fired an early
1425
+ // completion the coordinator could never correct (RCA case a). Keep the guard live for the
1426
+ // approval path too: when the resumed turn genuinely ends these clear and the completion
1427
+ // fires. Approval-resolved holds are NON-terminal (bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS)
1428
+ // so a provider that never closes its turn-scope still force-fires a weak completion rather
1429
+ // than wedging; the non-approval path keeps its terminal hold (a genuinely-busy adapter must
1430
+ // never force a completion out).
1431
+ if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: !approvalResolvedIdle };
1432
+ if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: !approvalResolvedIdle };
1433
+ if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: !approvalResolvedIdle };
777
1434
 
778
1435
  const partial = typeof this.adapter.getPartialResponse === 'function'
779
1436
  ? this.adapter.getPartialResponse()
780
1437
  : '';
781
- if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
1438
+ if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
782
1439
 
783
1440
  let parsed: any;
784
1441
  try {
785
1442
  parsed = this.adapter.getScriptParsedStatus();
786
1443
  } catch (error: any) {
787
- return `parse_error:${error?.message || String(error)}`;
1444
+ return { reason: `parse_error:${error?.message || String(error)}` };
788
1445
  }
789
1446
 
790
1447
  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';
1448
+ if (parsedStatus !== 'idle') {
1449
+ const adapterStatus = this.adapter.getStatus({ allowParse: false });
1450
+ if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
1451
+ return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
1452
+ }
1453
+ if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
1454
+ const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
1455
+ // FALSE-IDLE turn-boundary evidence (Defect 1b): turn-scope the present-check so a
1456
+ // STALE mid-turn assistant (predating pending.turnStartedAt) cannot satisfy the
1457
+ // finalization gate. Only the confirming final-assistant bubble that POST-DATES this
1458
+ // turn's start counts as evidence the turn genuinely ended.
1459
+ const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages, pending.turnStartedAt);
1460
+ const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1461
+ LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
1462
+ if (!finalAssistantEvidence.present) {
1463
+ if (adapterOwnsMessagesElsewhere) {
1464
+ if (finalAssistantEvidence.source === 'external-native') {
1465
+ const probe = this.recordPendingTranscriptProbe(pending);
1466
+ if (probe && !pending.loggedTranscriptProbe) {
1467
+ 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`);
1468
+ pending.loggedTranscriptProbe = true;
1469
+ }
1470
+ LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
1471
+ if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
1472
+ return null;
1473
+ }
1474
+ if (this.type === 'antigravity-cli') {
1475
+ return null;
1476
+ }
1477
+ // (SETTLE-VALLEY) The inter-approval idle valley: a native-history mesh worker
1478
+ // that resolved an approval and fell briefly idle (waiting_approval→idle) BEFORE
1479
+ // the next approval turn resumes. The live valley (~3s) is mostly covered by the
1480
+ // 4000ms NATIVE_HISTORY_MESH_IDLE_SETTLE_MS settle window, but a longer valley can
1481
+ // still let the flush run while the transcript's final assistant turn is not yet
1482
+ // written (source still the screen parse → finalAssistantPresent=false,
1483
+ // workerResult.source='default'). CANON-C would emit immediately here, freezing a
1484
+ // truncated preamble summary as evidenceLevel=insufficient. Instead HOLD: this
1485
+ // waiting_approval hold complements the settle window. Retry until the transcript finalizes
1486
+ // (block clears → genuine emit) or the worker resumes (resume guard cancels),
1487
+ // bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS. Scoped to the approval-resolved
1488
+ // idle so a genuinely-finished background-child turn keeps the CANON-C immediate
1489
+ // emit (its transcript trails by a write, not by a whole resume).
1490
+ if (allowMissingAssistantTimeout && pending.previousStatus === 'waiting_approval') {
1491
+ return { reason: 'missing_final_assistant', terminal: false, holdForTranscript: true };
1492
+ }
1493
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1494
+ }
1495
+ if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
1496
+ return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
1497
+ }
1498
+ } else {
1499
+ LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
1500
+ return {
1501
+ reason: 'missing_final_assistant',
1502
+ terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
1503
+ allowTimeout: allowMissingAssistantTimeout,
1504
+ };
1505
+ }
1506
+ }
1507
+
1508
+ // (FALSEIDLE-a) Structural approval-resolution gate. Runs BEFORE the brittle
1509
+ // screen-text heuristic below so it also catches modals whose text does not match
1510
+ // looksLikeActiveApprovalPromptText (e.g. claude-cli's cd / "untrusted hooks" prompt).
1511
+ const approvalResolutionBlock = this.approvalResolutionFinalizationBlock(pending);
1512
+ if (approvalResolutionBlock) return approvalResolutionBlock;
1513
+
1514
+ // Guard: if the screen still shows an approval/choice prompt as the last visible text,
1515
+ // the turn is not complete even if the parsed status says idle and there is an assistant
1516
+ // message. This catches the case where waiting_approval→idle transitions occur before
1517
+ // the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
1518
+ try {
1519
+ const screenText = typeof (this.adapter as any).getScreenText === 'function'
1520
+ ? String((this.adapter as any).getScreenText() || '')
1521
+ : '';
1522
+ if (screenText) {
1523
+ const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
1524
+ if (looksLikeActiveApprovalPromptText(tailLines)) {
1525
+ return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
1526
+ }
1527
+ }
1528
+ } catch { /* defensive: screen text read is best-effort */ }
794
1529
 
795
1530
  return null;
796
1531
  }
797
1532
 
1533
+ // (FALSEIDLE-a) Positive, structural proof that the latest approval entry was resolved
1534
+ // through ADHDev. resolveModal() — driven by auto-approve, dashboard/mesh_approve, and
1535
+ // dev-cli-debug alike — advances the engine's lastResolvedEntrySeq to the current
1536
+ // approvalEntrySeq. So `lastResolvedEntrySeq >= approvalEntrySeq` (with a real entry,
1537
+ // approvalEntrySeq > 0) means the modal we last saw was actually answered. Absence of this
1538
+ // evidence after a waiting_approval→idle transition means the idle is suspect: the spec's
1539
+ // text-based approval→idle rule false-tripped while the modal is still unresolved.
1540
+ // Fails OPEN (returns true) when the seq fields are unavailable, so the gate can never wedge
1541
+ // a session on a provider/adapter that does not surface the counters.
1542
+ private hasApprovalResolutionEvidence(): boolean {
1543
+ try {
1544
+ const status = this.adapter.getStatus({ allowParse: false }) as any;
1545
+ const entrySeq = typeof status?.approvalEntrySeq === 'number' ? status.approvalEntrySeq : 0;
1546
+ if (entrySeq <= 0) return true;
1547
+ const resolvedSeq = typeof status?.lastResolvedEntrySeq === 'number' ? status.lastResolvedEntrySeq : undefined;
1548
+ if (resolvedSeq === undefined) return true;
1549
+ return resolvedSeq >= entrySeq;
1550
+ } catch {
1551
+ return true;
1552
+ }
1553
+ }
1554
+
1555
+ // (FALSEIDLE-a) Hold a completion that is the anomalous DIRECT waiting_approval→idle
1556
+ // transition with no positive resolution evidence. A genuinely resolved approval routes
1557
+ // through resolveModal → setStatus('generating'), so its completion's previousStatus is
1558
+ // 'generating' (not 'waiting_approval') and this gate never fires for it. Scoped to
1559
+ // delegated mesh/coordinator sessions — whose only modal-resolution path is auto-approve /
1560
+ // mesh_approve (both advance lastResolvedEntrySeq) — so an interactive local session, where
1561
+ // a human may answer the PTY prompt directly and leave no resolveModal record, is untouched.
1562
+ // Non-terminal: the hold is bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS (30s), giving a
1563
+ // settling auto-approve time to fire and advance the seq, and guaranteeing no permanent wedge
1564
+ // if resolution ever happens via a path that does not record evidence.
1565
+ private approvalResolutionFinalizationBlock(pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
1566
+ if (pending.previousStatus !== 'waiting_approval') return null;
1567
+ const meshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
1568
+ if (!meshContext) return null;
1569
+ if (this.hasApprovalResolutionEvidence()) return null;
1570
+ return { reason: 'approval_resolution_unconfirmed', terminal: false };
1571
+ }
1572
+
798
1573
  private scheduleCompletedDebounceFlush(delayMs: number): void {
799
1574
  if (this.completedDebounceTimer) clearTimeout(this.completedDebounceTimer);
800
1575
  this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
801
1576
  }
802
1577
 
1578
+ // EVTTRACE (observation-only): is this a mesh worker session whose completion
1579
+ // events must route to a coordinator? Used purely to gate trace logging so a
1580
+ // non-mesh CLI session's completions don't add EvtTrace noise. No decision logic.
1581
+ private isMeshWorkerSession(): boolean {
1582
+ return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId
1583
+ || this.settings.meshNodeId || this.settings.launchedByCoordinator);
1584
+ }
1585
+
1586
+ /**
1587
+ * AUTOAPPROVE-FLAP-RECUR (Fix A+B): how long a busy blip / modal scroll-out may
1588
+ * persist before the in-progress settle gate is torn down. For a delegated
1589
+ * worker whose auto-approve episode is genuinely still cycling (mask clock
1590
+ * alive), the FSM's full waiting_approval → busy → waiting_approval flap runs
1591
+ * on a multi-second period, so the settle continuity window is extended to
1592
+ * AUTO_APPROVE_FLAP_CONTINUITY_MS to bridge it (still bounded, and still capped
1593
+ * by AUTO_APPROVE_MASK_STALL_MS). Every other case — foreground/attended
1594
+ * session, or no active mask episode — keeps the tight default hysteresis so a
1595
+ * genuine resolution frees the gate promptly.
1596
+ */
1597
+ private autoApproveContinuityWindowMs(): number {
1598
+ return this.autoApproveMaskSince > 0 && this.isMeshWorkerSession()
1599
+ ? CliProviderInstance.AUTO_APPROVE_FLAP_CONTINUITY_MS
1600
+ : CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS;
1601
+ }
1602
+
1603
+ /**
1604
+ * The settle-gate identity signature for a raw activeModal, or null when the
1605
+ * modal is NOT a concrete auto-approvable consent prompt (no captured buttons,
1606
+ * a picker/confirm kind, or no reliable affirmative+decline anchor). Mirrors the
1607
+ * gates the auto-approve fire path applies before computing modalSignature, so
1608
+ * the mask-stall nudge can ask the SAME question the settle gate is tracking —
1609
+ * "is THIS frame's modal the identity the settle clock is accruing against?" —
1610
+ * without duplicating the button-pick logic. The signature is message +
1611
+ * normalized affirmative label only (no volatile counters/button set), matching
1612
+ * the fire path exactly (AUTOAPPROVE-SETTLE-FLAP).
1613
+ */
1614
+ private approvableModalSignature(modal: any): string | null {
1615
+ const buttons = Array.isArray(modal?.buttons)
1616
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
1617
+ : [];
1618
+ if (!modal || buttons.length === 0) return null;
1619
+ const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
1620
+ if (modalKind !== 'approval') return null;
1621
+ const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
1622
+ const hasReliableConsentAnchor = hasNegativeApprovalOption(buttons)
1623
+ || hasReliableApprovalAffirmative(buttons);
1624
+ if (buttonIndex < 0 || !hasReliableConsentAnchor) return null;
1625
+ return approvalModalSignature(modal?.message, normalizeApprovalLabel(buttonLabel));
1626
+ }
1627
+
1628
+ // FALSE-IDLE (self-coordinator settle): an autonomously-progressing mesh session
1629
+ // is either a delegated worker (isMeshWorkerSession) OR the coordinator's OWN
1630
+ // claude-cli session (meshCoordinatorFor). Both run auto-approved tool turns whose
1631
+ // inter-approval valley (busy→idle blip→generating re-entry ~0.5s later) must be
1632
+ // absorbed by the completedDebounce settle window, not flushed on the first idle
1633
+ // sample. The worker branch already gets NATIVE_HISTORY_MESH_IDLE_SETTLE_MS; the
1634
+ // self-coordinator session (worker markers absent, meshCoordinatorFor present) was
1635
+ // taking flushDelay=0 — no settle window — so its busyEpoch/lastOutputAt continuity
1636
+ // guard had no window to observe the valley and fired mid-turn "next-step" previews
1637
+ // as a finalSummary. Mirrors the isAutonomousMeshSession notion in isTransientToolConsent.
1638
+ private isAutonomousMeshSession(): boolean {
1639
+ return this.isMeshWorkerSession() || !!this.settings.meshCoordinatorFor;
1640
+ }
1641
+
1642
+ /**
1643
+ * ARCH-REFACTOR R1: the taskId to attribute the CURRENTLY-completing turn to.
1644
+ * Prefers the per-turn binding (engine.currentTurnTaskId, set when the turn was
1645
+ * submitted and surviving until the next turn starts) over the last-write-wins
1646
+ * session scalar (settings.meshActiveTaskId). The scalar is retained only as a
1647
+ * backward-compat alias for the "current/last assignment" and is the source of the
1648
+ * NOTIF-MISDELIVER / TASK-MSG-MISROUTE race: a second task attaching before this
1649
+ * turn completes overwrites it. Returns undefined for a non-task ad-hoc turn.
1650
+ */
1651
+ private completingTurnTaskId(): string | undefined {
1652
+ const turnTaskId = this.adapter?.currentTurnTaskId;
1653
+ if (typeof turnTaskId === 'string' && turnTaskId.trim()) return turnTaskId;
1654
+ const scalar = this.settings.meshActiveTaskId;
1655
+ return typeof scalar === 'string' && scalar.trim() ? scalar : undefined;
1656
+ }
1657
+
1658
+ // EVTTRACE correlation context for this session's completion lifecycle. taskId is
1659
+ // the primary grep anchor; instanceId is the session fallback.
1660
+ private meshTraceCtx(event = 'agent:generating_completed'): Record<string, unknown> {
1661
+ return {
1662
+ // ARCH-REFACTOR R1: trace the per-turn taskId (falling back to the scalar) so
1663
+ // EvtTrace anchors on the same id the completion event actually carries.
1664
+ taskId: this.completingTurnTaskId(),
1665
+ sessionId: this.instanceId,
1666
+ nodeId: this.settings.meshNodeId,
1667
+ meshId: this.settings.meshNodeFor,
1668
+ event,
1669
+ };
1670
+ }
1671
+
1672
+ // COMPLETION-EARLYNOTIFY instrumentation. A session-keyed FSM-transition +
1673
+ // completion-gate snapshot recorded into the shared debug-trace ring buffer
1674
+ // (secret-safe, length/role/pattern-name only — never screen or bubble text).
1675
+ // Retrieved via getRecentDebugTrace (chat_debug_bundle). Both categories are a
1676
+ // no-op unless collectDebugTrace is on AND the category is selected, so the
1677
+ // hot-path guards below (completionTraceOn / fsmTraceOn) keep production cost
1678
+ // at a single boolean check.
1679
+ private completionTraceOn(): boolean {
1680
+ return shouldCollectTraceCategory('completion-gate');
1681
+ }
1682
+ private fsmTraceOn(): boolean {
1683
+ return shouldCollectTraceCategory('fsm-transition');
1684
+ }
1685
+ private recordCompletionGateTrace(stage: string, payload: Record<string, unknown>): void {
1686
+ recordDebugTrace({
1687
+ category: 'completion-gate',
1688
+ stage,
1689
+ level: 'debug',
1690
+ sessionId: this.instanceId,
1691
+ providerType: this.type,
1692
+ payload,
1693
+ });
1694
+ }
1695
+ private recordFsmTransitionTrace(payload: Record<string, unknown>): void {
1696
+ recordDebugTrace({
1697
+ category: 'fsm-transition',
1698
+ stage: 'transition',
1699
+ level: 'debug',
1700
+ sessionId: this.instanceId,
1701
+ providerType: this.type,
1702
+ payload,
1703
+ });
1704
+ }
1705
+
803
1706
  private flushCompletedDebounceIfFinalized(): void {
804
1707
  const pending = this.completedDebouncePending;
805
1708
  if (!pending) {
@@ -809,97 +1712,750 @@ export class CliProviderInstance implements ProviderInstance {
809
1712
 
810
1713
  const latestStatus = this.adapter.getStatus({ allowParse: false });
811
1714
  const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
812
- const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
1715
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
1716
+ 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
1717
  if (latestVisibleStatus !== 'idle') {
814
1718
  LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
1719
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('cancel', {
1720
+ blockReason: 'resumed_status',
1721
+ latestVisibleStatus,
1722
+ previousStatus: pending.previousStatus,
1723
+ busyEpochAtArm: pending.busyEpochAtArm,
1724
+ busyEpoch: this.busyEpoch,
1725
+ });
1726
+ this.completedDebouncePending = null;
1727
+ this.completedDebounceTimer = null;
1728
+ return;
1729
+ }
1730
+
1731
+ // FALSE-IDLE continuity guard (Defect 1a): the point-sample above only proves the
1732
+ // session is idle at THIS instant. A momentary busy→idle blip inside an inter-approval
1733
+ // valley (auto-approved tool turns) opens AND closes a generating phase entirely within
1734
+ // the settle window — so the single sample reads 'idle' even though the turn is still in
1735
+ // flight (it re-enters generating ~0.5s later). Require instead that the session stayed
1736
+ // CONTINUOUSLY idle since the debounce was armed: (1) no entry into a busy phase
1737
+ // (busyEpoch unchanged), and (2) no new raw PTY output (lastOutputAt did not advance).
1738
+ // Either signal ⇒ the idle was not continuous ⇒ cancel; the still-live turn re-arms its
1739
+ // own completion when it genuinely finishes. This only ever cancels (never emits more),
1740
+ // so shared behaviour for claude/codex/antigravity is strictly stricter, never looser.
1741
+ if (typeof pending.busyEpochAtArm === 'number' && this.busyEpoch !== pending.busyEpochAtArm) {
1742
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (busy re-entry during settle: epoch ${pending.busyEpochAtArm}→${this.busyEpoch})`);
1743
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('cancel', {
1744
+ blockReason: 'busy_reentry',
1745
+ latestVisibleStatus,
1746
+ previousStatus: pending.previousStatus,
1747
+ busyEpochAtArm: pending.busyEpochAtArm,
1748
+ busyEpoch: this.busyEpoch,
1749
+ busyEpochDelta: this.busyEpoch - pending.busyEpochAtArm,
1750
+ });
1751
+ this.completedDebouncePending = null;
1752
+ this.completedDebounceTimer = null;
1753
+ return;
1754
+ }
1755
+ const latestOutputAt = typeof (latestStatus as any)?.lastOutputAt === 'number' ? (latestStatus as any).lastOutputAt as number : undefined;
1756
+ if (typeof pending.lastOutputAtArm === 'number'
1757
+ && typeof latestOutputAt === 'number'
1758
+ && latestOutputAt > pending.lastOutputAtArm) {
1759
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (new PTY output during settle: ${pending.lastOutputAtArm}→${latestOutputAt})`);
1760
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('cancel', {
1761
+ blockReason: 'new_pty_output',
1762
+ latestVisibleStatus,
1763
+ previousStatus: pending.previousStatus,
1764
+ lastOutputAtArm: pending.lastOutputAtArm,
1765
+ lastOutputAt: latestOutputAt,
1766
+ lastOutputAtDelta: latestOutputAt - pending.lastOutputAtArm,
1767
+ });
815
1768
  this.completedDebouncePending = null;
816
1769
  this.completedDebounceTimer = null;
817
1770
  return;
818
1771
  }
819
1772
 
820
- const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
821
- if (blockReason) {
1773
+ const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
1774
+ if (block) {
1775
+ const blockReason = block.reason;
822
1776
  const waitedMs = Date.now() - pending.firstObservedAt;
823
- if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
1777
+ // CANON-C (completion-gate decouple): a block carrying `allowTimeout` is the
1778
+ // transcript-evidence gate — the worker FSM has ALREADY reached idle and the only
1779
+ // thing missing is the append-only transcript's final assistant turn (a native-source
1780
+ // race: claude-cli owns its history externally and the file write trails the idle
1781
+ // transition). `allowTimeout` is set ONLY on the missing_final_assistant block, and
1782
+ // ONLY for mesh worker sessions (meshNodeFor / meshActiveTaskId / launchedByCoordinator).
1783
+ // The coordinator's sole path to learn this session is idle is agent:generating_completed,
1784
+ // so holding it up to COMPLETED_FINALIZATION_MAX_WAIT_MS (30s) leaves the coordinator
1785
+ // false-generating while the worker is done. Decouple the idle NOTIFICATION from the
1786
+ // transcript evidence: emit the completion immediately, marked weak
1787
+ // (completionDiagnostic.blockReason=missing_final_assistant, finalAssistantPresent=false).
1788
+ // The finalSummary is enriched on a SEPARATE path — the mesh reconcile loop reads the
1789
+ // transcript once written and re-emits a GENUINE completion (CANON-B weak→genuine
1790
+ // upgrade; buildPendingEventFingerprint keeps weak and genuine distinct so the enriched
1791
+ // one still surfaces, and isFalseIdleCompletion keeps the direct dispatch active until
1792
+ // then). All OTHER blocks (genuinely-busy adapter/partial/parsed states, transient
1793
+ // parse_error) keep the existing terminal-hold / 30s-retry behavior unchanged.
1794
+ //
1795
+ // (SETTLE-VALLEY) Exception: a `holdForTranscript` block is the inter-approval idle
1796
+ // valley of a native-history mesh worker (waiting_approval→idle that will resume into
1797
+ // the next approval). It deliberately does NOT carry allowTimeout, so it falls into the
1798
+ // hold-and-retry path below (terminal:false) rather than the CANON-C immediate emit —
1799
+ // the retry loop re-runs the resume guard each cycle, so when the worker resumes the
1800
+ // pending completion is cancelled, and when the transcript's final assistant arrives the
1801
+ // block clears for a GENUINE emit. This blocks the truncated weak (insufficient) summary
1802
+ // from ever being emitted during the valley, without depending on the valley's length.
1803
+ const isTranscriptEvidenceGate = block.allowTimeout === true;
1804
+ LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} allowTimeout=${isTranscriptEvidenceGate} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
1805
+ if (!isTranscriptEvidenceGate && (block.terminal || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS)) {
824
1806
  if (pending.loggedBlockReason !== blockReason) {
825
1807
  LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
1808
+ // EVTTRACE: completion held by the finalization gate (CANON-C). Observation
1809
+ // only — does not change the hold decision above.
1810
+ if (this.isMeshWorkerSession()) {
1811
+ traceMeshEventDrop('completion_gate_hold', this.meshTraceCtx(), `${blockReason} waited=${waitedMs}ms`);
1812
+ }
1813
+ // COMPLETION-EARLYNOTIFY: a hold is the CORRECT outcome when the turn is not
1814
+ // yet proven done (the FixA/FixB gates route here); trace it so an early-notify
1815
+ // investigation can see the gate holding rather than firing.
1816
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('hold', {
1817
+ blockReason,
1818
+ latestVisibleStatus,
1819
+ terminal: block.terminal === true,
1820
+ holdForTranscript: block.holdForTranscript === true,
1821
+ approvalResolvedIdle: pending.previousStatus === 'waiting_approval',
1822
+ waitedMs,
1823
+ });
826
1824
  pending.loggedBlockReason = blockReason;
827
1825
  }
828
1826
  this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
829
1827
  return;
830
1828
  }
831
- LOG.warn('CLI', `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
1829
+ const emittedAfterFinalizationTimeout = waitedMs >= COMPLETED_FINALIZATION_MAX_WAIT_MS;
1830
+ const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
1831
+ blockReason,
1832
+ latestStatus,
1833
+ latestVisibleStatus,
1834
+ waitedMs,
1835
+ pending,
1836
+ emittedAfterFinalizationTimeout,
1837
+ });
1838
+ // Surface the CANON-C immediate-emit path distinctly so a delegated worker's idle
1839
+ // notification (transcript still pending) is not mistaken for a 30s-timeout fallback.
1840
+ (completionDiagnostic as Record<string, unknown>).decoupledImmediateEmit = isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout;
1841
+ LOG.warn('CLI', `[${this.type}] emitting completed event (${isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'CANON-C decoupled-immediate, transcript pending' : `after ${waitedMs}ms`}) without finalized assistant turn (${blockReason})`);
1842
+ // EVTTRACE: completion fired (forced past the finalization timeout / CANON-C decoupled-immediate).
1843
+ if (this.isMeshWorkerSession()) {
1844
+ traceMeshEventStage('fired', this.meshTraceCtx(), `forced after ${waitedMs}ms (${blockReason})`);
1845
+ }
1846
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('fire', {
1847
+ path: isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'canon_c_decoupled' : 'forced_timeout',
1848
+ blockReason,
1849
+ latestVisibleStatus,
1850
+ approvalResolvedIdle: pending.previousStatus === 'waiting_approval',
1851
+ finalAssistantPresent: (completionDiagnostic as any).finalAssistantPresent === true,
1852
+ evidenceSource: (completionDiagnostic as any).finalAssistantEvidenceSource ?? null,
1853
+ lastVisibleRole: (completionDiagnostic as any).lastVisibleRole ?? null,
1854
+ lastVisibleContentLen: (completionDiagnostic as any).lastVisibleContentLength ?? null,
1855
+ emittedAfterFinalizationTimeout,
1856
+ waitedMs,
1857
+ busyEpoch: this.busyEpoch,
1858
+ });
1859
+ this.emitGeneratingCompleted({
1860
+ chatTitle: pending.chatTitle,
1861
+ duration: pending.duration,
1862
+ timestamp: pending.timestamp,
1863
+ taskId: pending.taskId,
1864
+ // When finalization is forced past the timeout on a `parsed_status:` block
1865
+ // (the parser never confirmed a final assistant turn) we previously rode an
1866
+ // empty `finalSummary` unconditionally. That empty value propagates to the
1867
+ // mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
1868
+ // delegated session's inbox preview blank — or, for a LOCAL worktree session,
1869
+ // stuck on the dispatched user task. If the parser DID surface assistant text,
1870
+ // prefer it; only fall back to '' when no assistant summary can be derived.
1871
+ finalSummary: blockReason.startsWith('parsed_status:')
1872
+ ? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages, pending.turnStartedAt) ?? '')
1873
+ : this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages, pending.turnStartedAt),
1874
+ completionDiagnostic,
1875
+ });
832
1876
  this.completedDebouncePending = null;
833
1877
  this.completedDebounceTimer = null;
834
1878
  this.generatingStartedAt = 0;
1879
+ this.lastApprovalEventFingerprint = '';
835
1880
  return;
836
1881
  }
837
1882
 
838
1883
  LOG.info('CLI', `[${this.type}] completed in ${pending.duration}s`);
839
- this.pushEvent({
840
- event: 'agent:generating_completed',
1884
+ // EVTTRACE: completion fired (transcript finalized cleanly).
1885
+ if (this.isMeshWorkerSession()) {
1886
+ traceMeshEventStage('fired', this.meshTraceCtx(), `duration=${pending.duration}s`);
1887
+ }
1888
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('fire', {
1889
+ path: 'clean',
1890
+ latestVisibleStatus,
1891
+ approvalResolvedIdle: pending.previousStatus === 'waiting_approval',
1892
+ finalAssistantPresent: true,
1893
+ duration: pending.duration,
1894
+ busyEpoch: this.busyEpoch,
1895
+ });
1896
+ this.emitGeneratingCompleted({
841
1897
  chatTitle: pending.chatTitle,
842
1898
  duration: pending.duration,
843
1899
  timestamp: pending.timestamp,
844
- finalSummary: extractFinalSummaryFromMessages(this.adapter?.getScriptParsedStatus()?.messages),
1900
+ taskId: pending.taskId,
1901
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages, pending.turnStartedAt),
845
1902
  });
846
1903
  this.completedDebouncePending = null;
847
1904
  this.completedDebounceTimer = null;
848
1905
  this.generatingStartedAt = 0;
1906
+ this.lastApprovalEventFingerprint = '';
1907
+ }
1908
+
1909
+ /**
1910
+ * A-3 (CLI 완료판정 통합): single authoritative emit for a CLI turn's
1911
+ * `agent:generating_completed` event. The completion JUDGMENT — WHETHER and
1912
+ * WHEN a turn is done (settle windows, continuity guards, the finalization
1913
+ * gate, the short-gen / startup-grace / no-progress-monitor discriminators) —
1914
+ * stays at each call site, where it is legitimately path-specific. What used
1915
+ * to be duplicated across all five completion paths was the EVENT-SHAPE
1916
+ * assembly: the `event` name, the conditional `taskId` spread, and the
1917
+ * optional `finalSummary` / `evidenceLevel` / `completionDiagnostic` fields.
1918
+ * Folding that assembly here removes the divergence (e.g. one site spreading
1919
+ * taskId, others omitting it) without touching any judgment. Callers pass the
1920
+ * values they have already computed; omitted optionals are simply absent from
1921
+ * the emitted event, exactly as each inline builder produced before.
1922
+ */
1923
+ private emitGeneratingCompleted(opts: {
1924
+ chatTitle: string;
1925
+ duration: number | undefined;
1926
+ timestamp: number;
1927
+ taskId?: string;
1928
+ finalSummary?: string;
1929
+ evidenceLevel?: string;
1930
+ completionDiagnostic?: Record<string, unknown>;
1931
+ }): void {
1932
+ this.pushEvent({
1933
+ event: 'agent:generating_completed',
1934
+ chatTitle: opts.chatTitle,
1935
+ duration: opts.duration,
1936
+ timestamp: opts.timestamp,
1937
+ // ARCH-REFACTOR R1: attribute to the turn captured at idle-transition.
1938
+ ...(opts.taskId ? { taskId: opts.taskId } : {}),
1939
+ // finalSummary is always carried (value may be undefined) — every prior
1940
+ // inline builder included the key, so downstream consumers see the same shape.
1941
+ finalSummary: opts.finalSummary,
1942
+ ...(opts.evidenceLevel !== undefined ? { evidenceLevel: opts.evidenceLevel } : {}),
1943
+ ...(opts.completionDiagnostic !== undefined ? { completionDiagnostic: opts.completionDiagnostic } : {}),
1944
+ });
849
1945
  }
850
1946
 
851
1947
  private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
1948
+ // Manual-attendance suppression (provider-common): when a human is
1949
+ // Manual-attendance suppression (provider-common): when a human is
1950
+ // actively driving this session from the dashboard, hold auto-approve so
1951
+ // the modal stays visible and they can pick a button / use the controlbar
1952
+ // themselves. Return false (NOT auto-approving) so getState keeps the
1953
+ // modal surfaced. Clear any in-progress settle gate — a genuine fire
1954
+ // after the window lapses must re-settle from scratch — and arm a
1955
+ // re-check for the lapse moment, because the PTY may have gone silent and
1956
+ // would otherwise never re-drive this decision. Background mesh workers
1957
+ // are never attended, so their delegated auto-approve is untouched.
1958
+ if (adapterStatus?.status === 'waiting_approval'
1959
+ && this.shouldAutoApprove()
1960
+ && this.manualAttendance.isAttended(now)) {
1961
+ this.lastAutoApprovalSignature = '';
1962
+ this.pendingAutoApprovalSignature = '';
1963
+ this.pendingAutoApprovalSince = 0;
1964
+ this.autoApproveInactiveSince = 0;
1965
+ // Manual attendance takes over — the modal stays surfaced (maybeAutoApproveStatus
1966
+ // returns false), so end the mask episode.
1967
+ this.autoApproveMaskSince = 0;
1968
+ this.stalledApprovalNudgeEpisode = 0;
1969
+ this.autoApproveLastModalSeenAt = 0;
1970
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
1971
+ this.autoApproveSettleTimer = setTimeout(() => {
1972
+ this.autoApproveSettleTimer = null;
1973
+ this.recheckAutoApproveSettled();
1974
+ }, this.manualAttendance.remainingMs(now) + 20);
1975
+ return false;
1976
+ }
852
1977
  const autoApproveActive = adapterStatus?.status === 'waiting_approval' && this.shouldAutoApprove();
853
1978
  // Guard re-entry: onStatusChange/getState can observe the same modal multiple
854
1979
  // times while the PTY absorbs the approval key. Without this flag, repeated
855
1980
  // 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);
1981
+ // However, Claude Code can present a second approval immediately after the
1982
+ // first. Resolve a changed modal signature even while the previous write is
1983
+ // still inside the short busy window.
1984
+ if (!autoApproveActive) {
1985
+ this.lastAutoApprovalSignature = '';
1986
+ // Hysteresis: if a settle gate is mid-progress, a momentary
1987
+ // status!=waiting_approval blip (a generating flip while the same
1988
+ // modal's button block is still on screen) must NOT wipe the settle
1989
+ // clock otherwise the modal→generating→modal flap restarts the
1990
+ // 600ms window every time and auto-approve never fires. Keep the
1991
+ // gate warm for AUTO_APPROVE_GATE_HYSTERESIS_MS; re-arm a timer so
1992
+ // that if the modal does NOT come back the gate is cleared on the
1993
+ // re-check (a genuine resolution → idle frees the gate normally).
1994
+ if (this.pendingAutoApprovalSince) {
1995
+ if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
1996
+ const goneForMs = now - this.autoApproveInactiveSince;
1997
+ // AUTOAPPROVE-FLAP-RECUR (Fix B): a delegated-worker flap cycles the
1998
+ // FULL waiting_approval → busy → waiting_approval state on a
1999
+ // multi-second period, outrunning the tight default hysteresis and
2000
+ // wiping the settle clock before 600ms ever accumulates. For an
2001
+ // active worker mask episode the continuity window is widened (still
2002
+ // capped by AUTO_APPROVE_MASK_STALL_MS) so the settle clock survives
2003
+ // the busy phase and the returning approval keeps accruing settle time.
2004
+ const continuityMs = this.autoApproveContinuityWindowMs();
2005
+ if (goneForMs < continuityMs) {
2006
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
2007
+ this.autoApproveSettleTimer = setTimeout(() => {
2008
+ this.autoApproveSettleTimer = null;
2009
+ this.recheckAutoApproveSettled();
2010
+ }, continuityMs - goneForMs + 20);
2011
+ return autoApproveActive;
2012
+ }
2013
+ }
2014
+ // Clear the settle gate so the next approval starts its own quiet
2015
+ // window from scratch (a stale timestamp would let it fire instantly).
2016
+ this.pendingAutoApprovalSignature = '';
2017
+ this.pendingAutoApprovalSince = 0;
2018
+ this.autoApproveInactiveSince = 0;
2019
+ // Modal has genuinely been gone past the hysteresis window → the episode ended;
2020
+ // end the mask episode too (a later approval starts a fresh stall clock).
2021
+ this.autoApproveMaskSince = 0;
2022
+ this.stalledApprovalNudgeEpisode = 0;
2023
+ this.autoApproveLastModalSeenAt = 0;
2024
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
2025
+ return autoApproveActive;
869
2026
  }
2027
+ // Active approval observed — reset the inactivity tracker so a later
2028
+ // blip starts its hysteresis window fresh.
2029
+ this.autoApproveInactiveSince = 0;
2030
+ // STATUS-MISMATCH: start (or keep) the mask-stall clock for this episode. Set ONLY
2031
+ // when zero so it survives modal-signature changes and hysteresis blips — it measures
2032
+ // the true age of the unresolved auto-approve, not the per-signature settle window.
2033
+ if (!this.autoApproveMaskSince) this.autoApproveMaskSince = now;
2034
+ // NOTIF-APPROVAL-MASKED (Q1b): once this episode has stalled past the mask threshold,
2035
+ // surface the raw waiting_approval to the mesh coordinator (decoupled from the dashboard
2036
+ // mask). Placed on the active-approval path here — the single choke point that owns the
2037
+ // mask-stall clock and is re-driven throughout a silent stall (getState heartbeat,
2038
+ // detectStatusTransition, recheckAutoApproveSettled). No-op until the stall threshold trips.
2039
+ this.maybeEmitStalledApprovalNudge(adapterStatus, now);
2040
+ const modal = adapterStatus.activeModal;
2041
+ // (fix) Do not auto-approve when no concrete modal/buttons are present.
2042
+ // Claude TUI flaps between paints; without this guard adapterStatus
2043
+ // could report status=waiting_approval with activeModal=null (or with
2044
+ // an empty buttons array briefly) and we'd still call
2045
+ // resolveModal(-1) — which used to type "1" into the prompt
2046
+ // repeatedly. Skip until a real modal is captured.
2047
+ const buttons = Array.isArray(modal?.buttons)
2048
+ ? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
2049
+ : [];
2050
+ if (!modal || buttons.length === 0) {
2051
+ // AUTOAPPROVE-FLAP-RECUR (Fix A): the button block momentarily scrolled
2052
+ // out of the captured frame (status is still waiting_approval — we are
2053
+ // on the active path). Do NOT tear the settle gate down on this frame:
2054
+ // if a concrete modal was captured within the continuity window and a
2055
+ // settle gate is in progress, this is a short scroll-out blip — keep the
2056
+ // gate warm against the last-captured signature and arm a re-check so a
2057
+ // silent PTY still re-drives the decision when the buttons repaint. Only
2058
+ // once the modal has stayed empty PAST the continuity window is it a
2059
+ // genuine close, and the gate is cleared here so a later approval
2060
+ // re-settles from scratch (never fires on a stale timestamp).
2061
+ const blipForMs = this.autoApproveLastModalSeenAt ? now - this.autoApproveLastModalSeenAt : Infinity;
2062
+ if (this.pendingAutoApprovalSince && blipForMs < this.autoApproveContinuityWindowMs()) {
2063
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
2064
+ this.autoApproveSettleTimer = setTimeout(() => {
2065
+ this.autoApproveSettleTimer = null;
2066
+ this.recheckAutoApproveSettled();
2067
+ }, this.autoApproveContinuityWindowMs() - blipForMs + 20);
2068
+ return autoApproveActive;
2069
+ }
2070
+ if (blipForMs >= this.autoApproveContinuityWindowMs()) {
2071
+ // Buttons empty continuously past the window → the modal genuinely
2072
+ // closed (or never captured). Reset the per-signature settle gate so
2073
+ // a later approval re-settles cleanly. The mask-stall clock keeps
2074
+ // running underneath so a never-captured worker modal still surfaces
2075
+ // to the coordinator within AUTO_APPROVE_MASK_STALL_MS.
2076
+ this.pendingAutoApprovalSignature = '';
2077
+ this.pendingAutoApprovalSince = 0;
2078
+ }
2079
+ return autoApproveActive;
2080
+ }
2081
+ // Concrete modal captured this frame — mark the last-good-modal timestamp so
2082
+ // a subsequent scroll-out blip (buttons.length===0) can be told apart from a
2083
+ // genuine close by how long it persists (Fix A above).
2084
+ this.autoApproveLastModalSeenAt = now;
2085
+ // Picker/confirm exclusion (provider-common). A /model or /mode picker is
2086
+ // surfaced with status=waiting_approval so the dashboard shows it, but it
2087
+ // has no "correct" answer to auto-pick — blindly selecting the first
2088
+ // option silently switches the model (the "always Opus, before I even
2089
+ // choose" bug). Two independent gates, BOTH must pass to fire:
2090
+ //
2091
+ // (1) modal_kind — the spec/FSM tells us this is an 'approval' modal,
2092
+ // not a 'picker'/'confirm'. A modal whose kind is unknown (legacy
2093
+ // adapter, or a spec that predates modal_kind) reads as 'approval'
2094
+ // so genuine approvals keep auto-approving; only an explicit
2095
+ // 'picker'/'confirm' is excluded here.
2096
+ // (2) structural anchor — a real approval offers an affirmative AND a
2097
+ // decline option (pickApprovalButton finds a positive that isn't a
2098
+ // decline, and hasNegativeApprovalOption confirms a No/Cancel/Deny
2099
+ // is present). A model picker ("1. Default 2. Opus 3. Sonnet")
2100
+ // has no decline, so even an un-migrated picker is caught here.
2101
+ //
2102
+ // Mirrors the SDK v1 detect-status approval heuristic (detect-status.ts).
2103
+ const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
2104
+ if (modalKind !== 'approval') {
2105
+ // Picker/confirm — leave it for the user; keep the modal surfaced.
2106
+ return autoApproveActive;
2107
+ }
2108
+ const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
2109
+ // Structural decline anchor. A real approval offers BOTH an affirmative
2110
+ // and a decline — but on a TALL Write/Edit diff the trailing "3. No"
2111
+ // scrolls off the captured frame, leaving only "1. Yes" + "2. Yes, allow
2112
+ // … this session" so hasNegativeApprovalOption reads false (#137). A
2113
+ // scoped grant-affirmative ("Yes, allow … during this session" / "…don't
2114
+ // ask again") ONLY appears in a genuine consent modal (never a picker),
2115
+ // so it stands in for the off-frame decline as a reliable second anchor.
2116
+ // Conservative by construction: a picker without a grant-scope option
2117
+ // still bails here, and the fire below still picks the plain allow-once
2118
+ // "Yes" via pickApprovalButton, not the broader grant.
2119
+ const hasReliableConsentAnchor = hasNegativeApprovalOption(buttons)
2120
+ || hasReliableApprovalAffirmative(buttons);
2121
+ if (buttonIndex < 0 || !hasReliableConsentAnchor) {
2122
+ // No affirmative matched, or no decline / reliable grant option present
2123
+ // (→ not a real consent prompt, e.g. a picker that slipped past the
2124
+ // kind gate). Surface the modal so the user decides; never pick blindly.
2125
+ return autoApproveActive;
2126
+ }
2127
+ // Modal *identity* signature — the question plus the STABLE affirmative
2128
+ // anchor only, NO volatile counters and NO raw button set. This is what
2129
+ // the settle gate tracks: the FSM bumps approvalEntrySeq on every fresh
2130
+ // waiting_approval entry, and a modal→generating→modal flap (the question
2131
+ // line scrolled out of the captured frame while the button block stays)
2132
+ // re-enters and bumps it again. Folding that seq into the settle signature
2133
+ // made the 600ms settle clock restart on every flap, so the modal never
2134
+ // stayed stable long enough to fire — the gate was never satisfied.
2135
+ // Identity excludes the seq so seq flap of the SAME modal keeps one clock.
2136
+ //
2137
+ // The raw button set is also excluded: on a TALL Write/Edit diff claude's
2138
+ // TUI repaints the button block 3↔5↔none between frames (buttons scroll in
2139
+ // and out of the captured region), which flipped both buttons.join('|') and
2140
+ // the positional buttonIndex every frame → signature flap → the settle
2141
+ // clock reset 4–9s and only mask-stalled episodes leaked to the coordinator
2142
+ // (AUTOAPPROVE-SETTLE-FLAP). The affirmative the auto-approve will actually
2143
+ // press is the invariant across those repaints, so we anchor on its
2144
+ // NORMALIZED label (numbers/bullets/punctuation stripped, so "1. Yes" and
2145
+ // "3. Yes" collapse to "yes"). Message + affirmative label uniquely
2146
+ // identifies the consent question without tracking the volatile button
2147
+ // positions.
2148
+ const affirmativeAnchor = normalizeApprovalLabel(buttonLabel);
2149
+ const modalSignature = approvalModalSignature(modal?.message, affirmativeAnchor);
2150
+ // Busy-window re-entry guard still needs the seq: two DISTINCT
2151
+ // back-to-back approvals can carry identical message/buttons (common
2152
+ // with claude-cli). Without the seq their busy signatures collide and
2153
+ // the 5s busy-window guard below would swallow the second auto-approve,
2154
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
2155
+ // waiting_approval entry, so a new approval always yields a new busy
2156
+ // signature and fires through.
2157
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
2158
+ ? adapterStatus.approvalEntrySeq
2159
+ : 0;
2160
+ const busySignature = `${approvalEntrySeq}::${modalSignature}`;
2161
+ // Already fired for this exact modal entry and still inside the busy
2162
+ // window — nothing to do (re-entry guard for repeated snapshots of one
2163
+ // modal).
2164
+ if (this.autoApproveBusy && busySignature === this.lastAutoApprovalSignature) {
2165
+ return autoApproveActive;
2166
+ }
2167
+
2168
+ // Settle gate: only fire once this modal identity has been stable for
2169
+ // AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
2170
+ // message/buttons each frame → new identity → clock restarts, so we
2171
+ // never approve a half-rendered prompt (the "resolves too fast" bug).
2172
+ if (modalSignature !== this.pendingAutoApprovalSignature) {
2173
+ this.pendingAutoApprovalSignature = modalSignature;
2174
+ this.pendingAutoApprovalSince = now;
2175
+ }
2176
+ const settledForMs = now - this.pendingAutoApprovalSince;
2177
+ if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
2178
+ // Not yet settled. Arm a timer to re-check after the remaining quiet
2179
+ // window — the PTY may go silent once the prompt finishes painting,
2180
+ // so there is no guaranteed status-change frame to re-drive us.
2181
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
2182
+ this.autoApproveSettleTimer = setTimeout(() => {
2183
+ this.autoApproveSettleTimer = null;
2184
+ this.recheckAutoApproveSettled();
2185
+ }, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
2186
+ return autoApproveActive;
2187
+ }
2188
+
2189
+ // Settled — fire the approve key.
2190
+ if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
2191
+ this.autoApproveBusy = true;
2192
+ this.lastAutoApprovalSignature = busySignature;
2193
+ this.pendingAutoApprovalSignature = '';
2194
+ this.pendingAutoApprovalSince = 0;
2195
+ this.autoApproveInactiveSince = 0;
2196
+ // Fired (resolveModal in flight) — the episode resolved; end the mask-stall clock.
2197
+ this.autoApproveMaskSince = 0;
2198
+ this.stalledApprovalNudgeEpisode = 0;
2199
+ this.autoApproveLastModalSeenAt = 0;
2200
+ if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
2201
+ this.autoApproveBusyTimer = setTimeout(() => {
2202
+ this.autoApproveBusy = false;
2203
+ this.autoApproveBusyTimer = null;
2204
+ this.lastAutoApprovalSignature = '';
2205
+ }, 5000);
2206
+ this.recordAutoApproval(modal?.message, buttonLabel, now);
2207
+ setTimeout(() => {
2208
+ this.adapter.resolveModal(buttonIndex);
2209
+ }, 0);
870
2210
  return autoApproveActive;
871
2211
  }
872
2212
 
2213
+ /**
2214
+ * Re-drive the auto-approve check after the settle quiet window elapses.
2215
+ * The PTY may have gone silent once the approval prompt finished painting,
2216
+ * so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
2217
+ * — this timer-driven re-check picks up the now-settled modal and fires.
2218
+ * Deliberately lighter than detectStatusTransition(): it only re-evaluates
2219
+ * the approval decision; the next real PTY frame refreshes visible status.
2220
+ */
2221
+ private recheckAutoApproveSettled(): void {
2222
+ try {
2223
+ // APPROVAL Defect-C (auto-approve gap): re-probe with a LIVE parse, not the cached
2224
+ // engine snapshot. This timer is the ONLY re-drive when the PTY goes silent after the
2225
+ // approval prompt finishes painting (its whole reason to exist) — but with
2226
+ // allowParse:false it read only engine.activeModal, which the engine's per-frame settle
2227
+ // pass can leave null/stale when the modal arrived between writes. The re-check then saw
2228
+ // no modal and never fired, so the delegated worker's transient/quiet approval was missed
2229
+ // and the coordinator had to step in with a manual mesh_approve. allowParse:true makes
2230
+ // getStatus re-run runDetectStatus/runParseApproval on the current screen buffer (the same
2231
+ // live re-probe the coordinator's resolveAction path uses), recovering the modal so
2232
+ // auto-approve fires on its own. The half-rendered-frame guard (buttons.length===0) and
2233
+ // the settle gate in maybeAutoApproveStatus still protect against firing on a partial modal.
2234
+ const adapterStatus = this.adapter.getStatus({ allowParse: true });
2235
+ this.maybeAutoApproveStatus(adapterStatus, Date.now());
2236
+ } catch { /* adapter gone / transient — next frame retries */ }
2237
+ }
2238
+
2239
+ /**
2240
+ * Emit the queue-claim agent:ready event at most once per session. Both the
2241
+ * boot-time starting→idle one-shot and the fsmReadySeen re-arm call this; the
2242
+ * agentReadyEmitted guard ensures the second caller is a no-op so a worker is
2243
+ * never claimed twice and a queued task is never double-dispatched.
2244
+ */
2245
+ private emitAgentReadyOnce(chatTitle: string, now: number): void {
2246
+ if (this.agentReadyEmitted) return;
2247
+ this.agentReadyEmitted = true;
2248
+ this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
2249
+ }
2250
+
2251
+ /**
2252
+ * GENERATING-BOUNDARY synthetic emit for a first turn that started AND finished
2253
+ * inside the startup-grace window without the FSM ever observing a 'generating'
2254
+ * frame (an unobservably-fast turn). Synthesizes the agent:generating_started +
2255
+ * agent:generating_completed pair so the mesh coordinator learns the worker went
2256
+ * idle. Returns true iff it synthesized.
2257
+ *
2258
+ * Two callers share this defense line:
2259
+ * - 'startup_grace_fast_collapse' — the starting→idle transition (the FSM whose
2260
+ * spec lacks/hadn't-synced the starting→busy edge collapses starting→idle
2261
+ * directly, with no intervening 'generating' frame).
2262
+ * - 'startup_grace_idle_turn_collapse' — the idle→idle no-status-change poll
2263
+ * (the launch settle already drained starting→idle BEFORE the first turn, so
2264
+ * the turn runs+completes while status stays 'idle' the whole time and
2265
+ * detectStatusTransition never re-enters its change block — the live rc.403
2266
+ * Probe1 miss).
2267
+ *
2268
+ * False-positive safety (must NOT fire on a benign boot): currentTurnTaskId is
2269
+ * set ONLY by onTurnStarted (a real turn STARTED this boot) and persists past
2270
+ * completion, so it excludes a true idle boot (null) and a queued-pending first
2271
+ * turn that only runs after grace (onTurnStarted not yet called → null).
2272
+ * !hasAdapterPendingResponse() excludes a turn still mid-flight. generating
2273
+ * never armed (generatingStartedAt===0 && !generatingDebouncePending) means the
2274
+ * whole idle→busy→idle never happened for this turn. The once-per-turn guard
2275
+ * (fastCollapseSynthesizedTaskId) keeps the re-polled idle-stayed caller from
2276
+ * re-emitting every poll.
2277
+ */
2278
+ private maybeSynthesizeStartupGraceCollapse(
2279
+ chatTitle: string,
2280
+ now: number,
2281
+ reason: 'startup_grace_fast_collapse' | 'startup_grace_idle_turn_collapse',
2282
+ ): boolean {
2283
+ const startedTurnTaskId = typeof (this.adapter as any)?.currentTurnTaskId === 'string'
2284
+ && (this.adapter as any).currentTurnTaskId.trim()
2285
+ ? (this.adapter as any).currentTurnTaskId as string
2286
+ : undefined;
2287
+ const fastCollapsed = !!startedTurnTaskId
2288
+ && !this.hasAdapterPendingResponse()
2289
+ && !this.generatingStartedAt
2290
+ && !this.generatingDebouncePending;
2291
+ if (!fastCollapsed) return false;
2292
+ // Once-per-turn: the idle-stayed caller re-polls steadily while the session
2293
+ // sits idle; without this guard it would re-emit the pair every poll.
2294
+ if (this.fastCollapseSynthesizedTaskId === startedTurnTaskId) return false;
2295
+
2296
+ let fcFinalSummary: string | undefined;
2297
+ let fcEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
2298
+ try {
2299
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
2300
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
2301
+ fcEvidenceSource = evidence.source;
2302
+ fcFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
2303
+ } catch { /* best-effort */ }
2304
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || fcEvidenceSource === 'external-native') && !fcFinalSummary;
2305
+ // Mirror the short-generating idle path's suppression: a provider that
2306
+ // requires a final assistant (or external-native history) with NO confirmed
2307
+ // summary and NO mesh context emits nothing — the session is idle with no
2308
+ // confirmed turn, matching startup-blip semantics. With mesh context we still
2309
+ // emit so the coordinator can apply its own timeout/retry logic. Left UNMARKED
2310
+ // so a later poll can retry once the transcript's final assistant lands.
2311
+ const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
2312
+ if (missingEvidence && !hasMeshContext) {
2313
+ LOG.info('CLI', `[${this.type}] ${reason} suppressed: missing final assistant evidence, no mesh context (source=${fcEvidenceSource})`);
2314
+ return false;
2315
+ }
2316
+ // Mark BEFORE emitting so a re-entrant poll cannot double-fire.
2317
+ this.fastCollapseSynthesizedTaskId = startedTurnTaskId;
2318
+ LOG.info('CLI', `[${this.type}] ${reason}: synthesizing started+completed (taskId=${startedTurnTaskId} source=${fcEvidenceSource} hadFinalSummary=${!!fcFinalSummary})`);
2319
+ // Retroactive started so the started→completed pair (and the chat bubble) is
2320
+ // well-formed; pushEvent stamps the per-turn taskId for CANON-B ack.
2321
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now });
2322
+ if (this.isMeshWorkerSession()) {
2323
+ traceMeshEventStage('fired', this.meshTraceCtx(), `${reason} (source=${fcEvidenceSource})`);
2324
+ }
2325
+ // EARLYNOTIFY-GATEBYPASS (c): a startup-grace fast-collapse never OBSERVED the turn's
2326
+ // generating phase — its evidence is a plain transcript tail, never a self-attributing
2327
+ // final_summary_json — so this synth is TENTATIVE by default. Mark it WEAK
2328
+ // (evidenceLevel:'weak') so buildPendingEventFingerprint keys it `…::weak` and any later
2329
+ // genuine agent:generating_completed for the same task can still surface (CANON-B). The
2330
+ // stronger missing_final_assistant marker is preserved when there is also no summary.
2331
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('synth-fire', {
2332
+ path: 'startup_grace_fast_collapse',
2333
+ reason,
2334
+ evidenceSource: fcEvidenceSource,
2335
+ hadFinalSummary: !!fcFinalSummary,
2336
+ missingEvidence,
2337
+ evidenceLevel: 'weak',
2338
+ });
2339
+ this.emitGeneratingCompleted({
2340
+ chatTitle,
2341
+ duration: 0,
2342
+ timestamp: now,
2343
+ finalSummary: fcFinalSummary,
2344
+ evidenceLevel: 'weak',
2345
+ completionDiagnostic: {
2346
+ reason,
2347
+ finalAssistantEvidenceSource: fcEvidenceSource,
2348
+ ...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
2349
+ },
2350
+ });
2351
+ return true;
2352
+ }
2353
+
873
2354
  private detectStatusTransition(): void {
874
2355
  const now = Date.now();
875
2356
  // Status-change handling is a hot path: PTY output can fire it many times
876
2357
  // during long-running CLI sessions. Keep this path on adapter-owned light
877
2358
  // state only; rich provider parsing is reserved for getState/read_chat.
878
2359
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
2360
+ const adapterProviderSessionId = normalizeProviderSessionId(
2361
+ this.provider,
2362
+ typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
2363
+ );
2364
+ if (adapterProviderSessionId) {
2365
+ this.promoteProviderSessionId(adapterProviderSessionId);
2366
+ }
879
2367
  const parsedStatus = null;
880
2368
  const rawStatus = adapterStatus.status;
881
2369
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
882
- const newStatus = autoApproveActive ? 'generating' : rawStatus;
883
- const dirName = this.workingDir.split('/').filter(Boolean).pop() || 'session';
2370
+ // During the autoApproveBusy window (2s after firing approval key), the PTY
2371
+ // can briefly report 'idle' before the next generating phase starts. Treat that
2372
+ // transient idle as 'generating' to suppress a spurious agent:generating_completed
2373
+ // push notification. The adapter's status is otherwise authoritative — native
2374
+ // transcript shape does NOT override the FSM's busy/idle decision.
2375
+ const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
2376
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
2377
+ const dirName = workingDirBasename(this.workingDir);
884
2378
  const chatTitle = `${this.provider.name} · ${dirName}`;
885
2379
  const partial = this.adapter.getPartialResponse();
2380
+ // Liveness fingerprint for the no-progress watchdog. The parsed
2381
+ // assistant buffer (`partial`) alone goes static while a tool/build runs
2382
+ // — the assistant emits no tokens even though the PTY is actively
2383
+ // printing tool output — which made the watchdog false-fire a "stuck"
2384
+ // alert mid-turn. Fold in the adapter's raw-activity timestamps so any
2385
+ // visible terminal progress (lastScreenChangeAt) or raw PTY byte
2386
+ // (lastOutputAt) keeps the fingerprint moving. The watchdog then only
2387
+ // survives a genuine stall where nothing at all is happening.
886
2388
  const progressFingerprint = newStatus === 'generating'
887
- ? `${partial || ''}`.slice(-2000)
2389
+ ? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
888
2390
  : undefined;
889
2391
 
890
2392
  const previousStatus = this.lastStatus;
891
2393
  if (newStatus !== this.lastStatus) {
892
2394
  LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
893
- if (this.lastStatus === 'idle' && newStatus === 'generating') {
2395
+ // COMPLETION-EARLYNOTIFY: snapshot every FSM status transition (the arm/fire/cancel
2396
+ // decisions downstream all hang off these edges). Guarded so production pays only a
2397
+ // boolean check; payload carries the visibility/auto-approve flags and the continuity
2398
+ // clocks (busyEpoch / lastOutputAt / lastScreenChangeAt) that the completion gate reads.
2399
+ if (this.fsmTraceOn()) this.recordFsmTransitionTrace({
2400
+ from: this.lastStatus,
2401
+ to: newStatus,
2402
+ rawStatus,
2403
+ autoApproveActive,
2404
+ autoApproveHoldIdle,
2405
+ autoApproveBusy: this.autoApproveBusy,
2406
+ hasPending: this.hasAdapterPendingResponse(),
2407
+ busyEpoch: this.busyEpoch,
2408
+ lastOutputAt: typeof adapterStatus?.lastOutputAt === 'number' ? adapterStatus.lastOutputAt : null,
2409
+ lastScreenChangeAt: typeof adapterStatus?.lastScreenChangeAt === 'number' ? adapterStatus.lastScreenChangeAt : null,
2410
+ });
2411
+ // GENERATING-MISSING (win32 fresh-worktree first-turn): a freshly-launched session
2412
+ // is in 'starting' until its startup-grace settles to idle. When the FIRST inject
2413
+ // lands inside that grace window, the adapter can report status DIRECTLY
2414
+ // starting → generating without an intervening 'idle' frame for
2415
+ // detectStatusTransition() to observe. Previously only the idle→generating arm
2416
+ // armed the bookkeeping, so a starting→generating frame fell straight through to the
2417
+ // bare `this.lastStatus = newStatus` update: generatingStartedAt stayed 0 and no
2418
+ // generating_started was queued. The fast turn's generating→idle completion was then
2419
+ // suppressed by the startup-blip guard below (generatingStartedAt===0 &&
2420
+ // !generatingDebouncePending) — so NO generating_started AND NO generating_completed
2421
+ // ever fired and the mesh coordinator never learned the worker went idle.
2422
+ //
2423
+ // We extend the idle→generating arm to also fire on starting→generating, BUT ONLY
2424
+ // when a real turn is in flight. The adapter script can also report 'generating' from
2425
+ // pure startup PTY noise (no task dispatched) — antigravity/codex/hermes-cli all
2426
+ // exercise that benign starting→generating→idle blip, which must NOT emit a
2427
+ // completion (see "startup-phase spurious completion suppression" tests).
2428
+ // hasAdapterPendingResponse() is the discriminator: a genuine inject sets the
2429
+ // adapter's isWaitingForResponse / currentTurnScope (or leaves a partial response),
2430
+ // whereas startup repaint noise leaves all of them empty. So an armed
2431
+ // starting→generating means "the worker actually started its first turn", and a
2432
+ // bare one stays a suppressed blip via the existing fall-through.
2433
+ const startingToGeneratingWithActiveTurn = this.lastStatus === 'starting'
2434
+ && newStatus === 'generating'
2435
+ && this.hasAdapterPendingResponse();
2436
+ if (((this.lastStatus === 'idle' && newStatus === 'generating') || startingToGeneratingWithActiveTurn)) {
2437
+ // If a completion event is already pending and the turn has ended
2438
+ // (generatingStartedAt===0), the PTY is painting its prompt area
2439
+ // after completing. Ignore this blip — do not cancel the pending
2440
+ // completion and do not advance lastStatus to generating. (On a true
2441
+ // starting→generating the session is fresh: completedDebouncePending is
2442
+ // null, so this blip guard is a no-op and we arm normally below.)
2443
+ if (this.completedDebouncePending && this.generatingStartedAt === 0) {
2444
+ LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
2445
+ return;
2446
+ }
894
2447
  this.suppressIdleHistoryReplay = false;
895
2448
  // Cancel any pending completed event (multi-step: idle→generating resume)
896
2449
  if (this.completedDebouncePending) {
897
- LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
2450
+ LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
898
2451
  if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
899
2452
  this.completedDebouncePending = null;
900
2453
  }
901
2454
 
902
2455
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
2456
+ // FALSE-IDLE continuity: entering a busy phase invalidates any
2457
+ // completedDebouncePending armed earlier in this settle window.
2458
+ this.busyEpoch++;
903
2459
  // Defer the generating_started event — if idle comes back within 3s,
904
2460
  // the whole started→completed pair was a false positive from PTY noise
905
2461
  if (this.generatingDebounceTimer) clearTimeout(this.generatingDebounceTimer);
@@ -924,14 +2480,38 @@ export class CliProviderInstance implements ProviderInstance {
924
2480
  this.completedDebouncePending = null;
925
2481
 
926
2482
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
2483
+ // FALSE-IDLE continuity: waiting_approval is a busy phase (the agent
2484
+ // resumes into it), so bump the epoch too — the completedDebouncePending
2485
+ // cancel above covers the currently-armed pending, and the epoch covers
2486
+ // a pending that re-arms and flushes across this same valley.
2487
+ this.busyEpoch++;
927
2488
  const modal = adapterStatus.activeModal;
928
2489
  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;
2490
+ // Include the FSM's approval entry seq, mirroring the auto-approve
2491
+ // path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
2492
+ // guard. Two distinct back-to-back approvals can carry identical
2493
+ // message/buttons (very common with claude-cli's "Allow Bash
2494
+ // command?"). Without the seq their fingerprints collide and the dedup
2495
+ // below silently drops the second waiting_approval event — it is never
2496
+ // emitted, so it cannot even land in the pending inbox for a later
2497
+ // read_chat reconcile to recover. The seq is bumped by the FSM on every
2498
+ // fresh waiting_approval entry, so a new approval always yields a new
2499
+ // fingerprint and emits.
2500
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
2501
+ ? adapterStatus.approvalEntrySeq
2502
+ : 0;
2503
+ const approvalFingerprint = JSON.stringify({
2504
+ message: typeof modal?.message === 'string' ? modal.message.trim() : '',
2505
+ buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
2506
+ seq: approvalEntrySeq,
2507
+ });
2508
+ // PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
2509
+ // Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
2510
+ // (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
2511
+ if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
2512
+ this.lastApprovalEventFingerprint = approvalFingerprint;
933
2513
  this.appendRuntimeSystemMessage(
934
- this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
2514
+ formatApprovalRequestMessage(modal?.message, modal?.buttons),
935
2515
  `approval_request:${now}`,
936
2516
  now,
937
2517
  );
@@ -941,22 +2521,286 @@ export class CliProviderInstance implements ProviderInstance {
941
2521
  modalButtons: modal?.buttons,
942
2522
  });
943
2523
  }
2524
+ } else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
2525
+ // Approval resolved and the agent resumed work. Defense-in-depth:
2526
+ // clear the approval emit fingerprint here too (not only on
2527
+ // completion at scheduleCompletedDebounceFlush). A subsequent
2528
+ // waiting_approval with the same modal content as the one just
2529
+ // resolved would otherwise collide with the stale fingerprint and be
2530
+ // dropped. The seq in the fingerprint already separates entries; this
2531
+ // reset is a belt-and-suspenders guard for the re-entry case.
2532
+ this.lastApprovalEventFingerprint = '';
944
2533
  } else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
945
2534
  const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
946
- // If debounce still pending (generating lasted < 1s), cancel both events
2535
+ // Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
2536
+ // was entered from 'starting' state (startup PTY noise), not from a real idle→generating
2537
+ // task dispatch. The idle→generating handler is the only code path that sets
2538
+ // generatingStartedAt and generatingDebouncePending, so both being absent means no
2539
+ // task was ever dispatched. Suppress the spurious completion event and fall through
2540
+ // to a simple lastStatus update.
2541
+ if (!this.generatingStartedAt && !this.generatingDebouncePending) {
2542
+ LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
2543
+ } else
2544
+ // If debounce still pending (generating lasted < 1s), cancel both UI events.
2545
+ // Still emit agent:generating_completed so mesh orchestration can record
2546
+ // task_completed for direct dispatches that complete faster than the debounce.
947
2547
  if (this.generatingDebouncePending) {
948
- LOG.info('CLI', `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
2548
+ // NOTIF Defect-2a: shortDurationMs is the REPORTED turn duration, so it must be
2549
+ // measured from the IMMUTABLE turn start — not generatingStartedAt, which is
2550
+ // reset to 0 on every mid-turn waiting_approval/idle blip (see :1864/1885/2397/
2551
+ // 2503/2521) and re-armed on the next →generating, so a long turn that blipped
2552
+ // would measure only the final 1.5-2.5s sliver. engine.currentTurnStartedAt is
2553
+ // stamped once at onTurnStarted and persists past mid-turn blips until the next
2554
+ // turn starts, so it captures the true turn length. generatingStartedAt remains
2555
+ // the fallback (and the debounce itself stays a pure UI-suppression signal,
2556
+ // decoupled from the reported duration).
2557
+ const { durationMs: shortDurationMs, anchor: durationAnchor } = computeTurnAnchoredDurationMs(
2558
+ (this.adapter as any)?.currentTurnStartedAt,
2559
+ this.generatingStartedAt,
2560
+ now,
2561
+ );
2562
+ LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms, anchor=${durationAnchor})`);
949
2563
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
2564
+ // Emit completion for mesh task association even though the UI generating
2565
+ // started/completed pair is suppressed (too short for visible UI update).
2566
+ let shortFinalSummary: string | undefined;
2567
+ let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
2568
+ try {
2569
+ const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
2570
+ const evidence = this.completionFinalAssistantEvidence(parsedMessages);
2571
+ shortEvidenceSource = evidence.source;
2572
+ shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
2573
+ } catch { /* best-effort */ }
2574
+ // If a real response is confirmed, retroactively emit started so the chat
2575
+ // bubble appears even though the debounce suppressed the original event.
2576
+ if (shortFinalSummary) {
2577
+ this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
2578
+ }
2579
+ // FALSE-IDLE short-gen settle: snapshot the producing turn's start + taskId NOW,
2580
+ // before `generatingStartedAt` is reset below — the settle-arm path (mesh sessions,
2581
+ // see the mesh branch further down) needs the same turn anchor the normal
2582
+ // completedDebounce branch captures, and generatingStartedAt is the fallback for it.
2583
+ const shortEngineTurnStart = typeof (this.adapter as any)?.currentTurnStartedAt === 'number'
2584
+ && Number.isFinite((this.adapter as any).currentTurnStartedAt)
2585
+ ? (this.adapter as any).currentTurnStartedAt as number
2586
+ : 0;
2587
+ const shortTurnStartedAt = shortEngineTurnStart || this.generatingStartedAt || 0;
2588
+ const shortTaskId = this.completingTurnTaskId();
950
2589
  this.generatingDebouncePending = null;
951
2590
  this.generatingStartedAt = 0;
2591
+ // FALSE-IDLE short-gen: a short-generating completion with NO transcript
2592
+ // backing at all (shortEvidenceSource === 'unavailable': both the screen parse
2593
+ // AND the external-native transcript failed to yield a final assistant) is just
2594
+ // as unproven as an 'external-native' source that returned no final assistant.
2595
+ // Fold 'unavailable' into the missing-evidence predicate so a zero-evidence dip
2596
+ // (the mid-turn point-sample that triggered this whole false-idle bug) is treated
2597
+ // as weak/held, not fired as a genuine completion. A real shortFinalSummary being
2598
+ // present still clears the gate (the !shortFinalSummary guard is unchanged).
2599
+ const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true
2600
+ || shortEvidenceSource === 'external-native'
2601
+ || shortEvidenceSource === 'unavailable') && !shortFinalSummary;
2602
+ if (missingEvidence) {
2603
+ LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
2604
+ }
2605
+ if (this.isAutonomousMeshSession()) {
2606
+ // FALSE-IDLE short-gen settle (the core fix): for an autonomously-progressing
2607
+ // mesh session (delegated worker OR self-coordinator), the short-generating
2608
+ // branch was a POINT-SAMPLE — a single idle read from getStatus({allowParse:false})
2609
+ // that fires the completion INLINE with zero continuity backing. When the worker
2610
+ // is merely mid-turn (a sub-3s dip between two tool calls), this synchronously
2611
+ // emitted a false agent:generating_completed the coordinator can never correct.
2612
+ //
2613
+ // Route it through the SAME settle + continuity machinery as the normal
2614
+ // completedDebounce branch: arm completedDebouncePending capturing busyEpochAtArm
2615
+ // and lastOutputAtArm, then scheduleCompletedDebounceFlush(NATIVE_HISTORY_MESH_IDLE_SETTLE_MS)
2616
+ // so flushCompletedDebounceIfFinalized() re-verifies CONTINUOUS idle before emitting.
2617
+ // A busy re-entry (busyEpoch bump) or new PTY output within the settle window —
2618
+ // exactly what happens when the worker resumes its next tool call — CANCELS the
2619
+ // false completion. Genuine completions (real final assistant) still emit at the
2620
+ // end of the (short, 4s) settle window; missingEvidence flows through the
2621
+ // finalization block (missing_final_assistant → CANON-C weak/held) rather than
2622
+ // being frozen as a genuine inline fire.
2623
+ this.completedDebouncePending = {
2624
+ chatTitle,
2625
+ duration: Math.round(shortDurationMs / 1000),
2626
+ timestamp: now,
2627
+ firstObservedAt: now,
2628
+ // Short-gen enters from generating→idle (or waiting_approval→idle); the
2629
+ // completedDebounce finalization gate treats previousStatus for its
2630
+ // approval-resolution / inter-approval-valley handling. lastStatus is the
2631
+ // status we transitioned FROM here.
2632
+ previousStatus: this.lastStatus,
2633
+ ...(shortTaskId ? { taskId: shortTaskId } : {}),
2634
+ ...(shortTurnStartedAt ? { turnStartedAt: shortTurnStartedAt } : {}),
2635
+ // FALSE-IDLE continuity: same arm-time snapshots as the normal branch so the
2636
+ // flush guard can prove continuous idle across the settle window.
2637
+ busyEpochAtArm: this.busyEpoch,
2638
+ ...(typeof adapterStatus?.lastOutputAt === 'number' && Number.isFinite(adapterStatus.lastOutputAt)
2639
+ ? { lastOutputAtArm: adapterStatus.lastOutputAt as number }
2640
+ : {}),
2641
+ };
2642
+ LOG.info('CLI', `[${this.type}] short-generating routed through settle window (${shortDurationMs}ms, source=${shortEvidenceSource}, missingEvidence=${missingEvidence}) — arming completedDebouncePending instead of inline fire`);
2643
+ // EVTTRACE: now traces the settle ARM (not an inline fire) for mesh sessions,
2644
+ // so logs show the short-gen path deferring to continuity re-check.
2645
+ if (this.isMeshWorkerSession()) {
2646
+ traceMeshEventStage('arm', this.meshTraceCtx(), `short-generating settle-arm (source=${shortEvidenceSource}, missingEvidence=${missingEvidence})`);
2647
+ }
2648
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('arm', {
2649
+ branch: 'short_generating',
2650
+ previousStatus: this.lastStatus,
2651
+ turnStartedAt: shortTurnStartedAt || null,
2652
+ busyEpochAtArm: this.busyEpoch,
2653
+ lastOutputAtArm: typeof adapterStatus?.lastOutputAt === 'number' ? adapterStatus.lastOutputAt : null,
2654
+ flushDelay: NATIVE_HISTORY_MESH_IDLE_SETTLE_MS,
2655
+ evidenceSource: shortEvidenceSource,
2656
+ missingEvidence,
2657
+ hasFinalSummary: !!shortFinalSummary,
2658
+ });
2659
+ this.scheduleCompletedDebounceFlush(NATIVE_HISTORY_MESH_IDLE_SETTLE_MS);
2660
+ } else if (missingEvidence) {
2661
+ // NON-MESH, missing evidence: suppress the completion event entirely (the
2662
+ // original !hasMeshContext suppression). A genuinely non-mesh session has no
2663
+ // coordinator to notify, and firing a completion with no confirmed final
2664
+ // assistant would just surface an empty/unconfirmed turn. Leave
2665
+ // completedDebouncePending null — the session is now idle with no confirmed
2666
+ // turn, matching the startup-blip suppression semantics. (No EvtTrace: not a
2667
+ // mesh session, so nothing routes to a coordinator.)
2668
+ LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, non-mesh session (source=${shortEvidenceSource})`);
2669
+ } else {
2670
+ // NON-MESH interactive fast-path with a CONFIRMED summary: keep the existing
2671
+ // inline fire. The dashboard UX reason for the short path (a fast turn should
2672
+ // surface its completion promptly without a 4s settle) still holds, and a
2673
+ // non-mesh session has no coordinator to be falsely notified — the false-idle
2674
+ // bug being fixed is specifically the mesh worker/coordinator misfire above.
2675
+ this.emitGeneratingCompleted({
2676
+ chatTitle,
2677
+ duration: 0,
2678
+ timestamp: now,
2679
+ finalSummary: shortFinalSummary,
2680
+ completionDiagnostic: {
2681
+ reason: 'short_generating_suppressed',
2682
+ shortDurationMs,
2683
+ finalAssistantEvidenceSource: shortEvidenceSource,
2684
+ },
2685
+ });
2686
+ }
952
2687
  } else {
953
2688
  // Debounce completed, then require the rich transcript path that read_chat
954
2689
  // 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);
2690
+ this.completedDebouncePending = {
2691
+ chatTitle,
2692
+ duration,
2693
+ timestamp: now,
2694
+ firstObservedAt: now,
2695
+ previousStatus: this.lastStatus,
2696
+ // ARCH-REFACTOR R1: snapshot the completing turn's taskId NOW (sync),
2697
+ // before any follow-up task's flush can start a new turn and move
2698
+ // engine.currentTurnTaskId.
2699
+ ...(this.completingTurnTaskId() ? { taskId: this.completingTurnTaskId() } : {}),
2700
+ // NOTIF Defect-B: snapshot the producing turn's START instant NOW, for the
2701
+ // same reason as taskId — a follow-up turn moves engine.currentTurnStartedAt.
2702
+ // Prefer the engine's per-turn start (set at onTurnStarted, earliest reliable
2703
+ // anchor) and fall back to generatingStartedAt (when generating was observed).
2704
+ ...((() => {
2705
+ const engineTurnStart = typeof (this.adapter as any)?.currentTurnStartedAt === 'number'
2706
+ && Number.isFinite((this.adapter as any).currentTurnStartedAt)
2707
+ ? (this.adapter as any).currentTurnStartedAt as number
2708
+ : 0;
2709
+ const turnStartedAt = engineTurnStart || this.generatingStartedAt || 0;
2710
+ return turnStartedAt ? { turnStartedAt } : {};
2711
+ })()),
2712
+ // FALSE-IDLE continuity: snapshot the busy epoch + raw PTY output
2713
+ // clock at arm time so the flush guard can prove the session stayed
2714
+ // continuously idle (no busy re-entry, no new PTY output) through the
2715
+ // settle window rather than merely reading 'idle' once at flush.
2716
+ busyEpochAtArm: this.busyEpoch,
2717
+ ...(typeof adapterStatus?.lastOutputAt === 'number' && Number.isFinite(adapterStatus.lastOutputAt)
2718
+ ? { lastOutputAtArm: adapterStatus.lastOutputAt as number }
2719
+ : {}),
2720
+ };
2721
+ const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
2722
+ // (FALSEIDLE-BGCHILD-a) Native-history providers flush immediately (the
2723
+ // transcript is authoritative). For autonomously-progressing mesh sessions,
2724
+ // give the generating→idle transition a short settle window so a background-child
2725
+ // false idle (quiet after a backgrounded test/command while the parent turn
2726
+ // continues) or an inter-approval auto-approve valley gets caught by the resume
2727
+ // guard in flushCompletedDebounceIfFinalized instead of firing an early completion
2728
+ // the coordinator can never correct.
2729
+ //
2730
+ // (FALSE-IDLE self-coordinator settle) The settle window now covers BOTH mesh
2731
+ // worker sessions AND the coordinator's own claude-cli session (meshCoordinatorFor):
2732
+ // isAutonomousMeshSession(). Previously only isMeshWorkerSession() qualified, so a
2733
+ // self-coordinating daemon (worker + coordinator on the same daemon) ran the
2734
+ // coordinator's own turn at flushDelay=0 — no settle window at all — and the
2735
+ // busyEpoch/lastOutputAt continuity guard, being a flush-time point-check, had no
2736
+ // window in which to observe the ~0.5s auto-approve valley. Its mid-turn
2737
+ // "next-step" sentence was flushed as finalSummary. A genuinely non-mesh session
2738
+ // (neither worker nor self-coordinator) still flushes immediately (delay=0), so
2739
+ // no non-mesh behaviour changes; this only ADDS a settle window (strictly
2740
+ // stricter — the guard can only ever CANCEL a pending flush, never emit more).
2741
+ const meshSettleSession = this.isAutonomousMeshSession();
2742
+ const flushDelay = ownsExternalHistory
2743
+ ? (meshSettleSession ? NATIVE_HISTORY_MESH_IDLE_SETTLE_MS : 0)
2744
+ : 3000;
2745
+ LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} meshSettle=${meshSettleSession} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
2746
+ if (this.completionTraceOn()) this.recordCompletionGateTrace('arm', {
2747
+ branch: 'normal',
2748
+ previousStatus: this.completedDebouncePending.previousStatus,
2749
+ turnStartedAt: this.completedDebouncePending.turnStartedAt ?? null,
2750
+ busyEpochAtArm: this.completedDebouncePending.busyEpochAtArm ?? null,
2751
+ lastOutputAtArm: this.completedDebouncePending.lastOutputAtArm ?? null,
2752
+ flushDelay,
2753
+ ownsExternalHistory,
2754
+ meshSettle: meshSettleSession,
2755
+ });
2756
+ this.scheduleCompletedDebounceFlush(flushDelay);
957
2757
  }
958
2758
  } else if (newStatus === 'idle' && this.lastStatus === 'starting') {
959
- this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
2759
+ this.emitAgentReadyOnce(chatTitle, now);
2760
+ // GENERATING-BOUNDARY (R4c): stamp the collapse moment ONCE so the
2761
+ // idle-stayed window below is anchored on the startup-grace collapse,
2762
+ // not on boot. Set only the first time so a later starting re-entry
2763
+ // cannot slide the window forward.
2764
+ if (this.startupGraceCollapseAt === null) this.startupGraceCollapseAt = now;
2765
+ // GENERATING-BOUNDARY fast-collapse (R4, win32 startup-grace first turn):
2766
+ // a turn dispatched into the startup-grace window can START and FINISH while
2767
+ // the FSM is still in 'starting'. On a daemon whose claude-cli spec has NOT yet
2768
+ // synced the starting→busy edge (the primary cure lives in the spec's
2769
+ // idle→busy.from), the FSM never reaches 'busy'/generating, so
2770
+ // detectStatusTransition observes starting→idle DIRECTLY with no intervening
2771
+ // 'generating' frame. The idle→generating arm — the only path that sets
2772
+ // generatingStartedAt and arms the completion — never fired, so the completing
2773
+ // turn's agent:generating_completed is never emitted and the mesh coordinator
2774
+ // never learns the worker went idle. Synthesize the started+completed pair here.
2775
+ //
2776
+ // Discriminator (false-positive safe — must NOT fire on a benign boot):
2777
+ // adapter.currentTurnTaskId is set ONLY by onTurnStarted (a real turn STARTED
2778
+ // this boot) and persists past completion, so it cleanly separates the three
2779
+ // non-firing cases — a true idle boot (no turn → null), a queued-pending
2780
+ // first turn that only runs AFTER startup-grace drains the composer (onTurnStarted
2781
+ // not yet called → null; it completes normally later via idle→busy→idle), and a
2782
+ // turn STILL running at the 8s mark (hasAdapterPendingResponse() still true →
2783
+ // excluded so we don't fire a premature mid-turn completion; idle→busy self-
2784
+ // corrects once the FSM reaches idle). We fire only when a turn started AND has
2785
+ // already finished: started-this-boot && !still-in-flight.
2786
+ this.maybeSynthesizeStartupGraceCollapse(chatTitle, now, 'startup_grace_fast_collapse');
2787
+ } else if (newStatus === 'error') {
2788
+ if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
2789
+ this.generatingDebouncePending = null;
2790
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2791
+ this.completedDebouncePending = null;
2792
+ this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
2793
+ this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
2794
+ this.pushEvent({
2795
+ event: 'agent:stopped',
2796
+ chatTitle,
2797
+ timestamp: now,
2798
+ finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
2799
+ completionDiagnostic: {
2800
+ reason: adapterStatus.errorReason || 'provider_error',
2801
+ errorMessage: adapterStatus.errorMessage || undefined,
2802
+ },
2803
+ });
960
2804
  } else if (newStatus === 'stopped') {
961
2805
  // Cancel any pending debounce
962
2806
  if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
@@ -968,6 +2812,79 @@ export class CliProviderInstance implements ProviderInstance {
968
2812
  this.lastStatus = newStatus;
969
2813
  }
970
2814
 
2815
+ // GENERATING-BOUNDARY idle-stayed collapse (R4b): the starting→idle
2816
+ // fast-collapse arm above only fires when the FIRST turn itself drives the
2817
+ // starting→idle transition. When the launch settle already drained
2818
+ // starting→idle BEFORE the first turn arrives, the session is already 'idle'
2819
+ // and a turn that runs+completes inside the startup-grace window — too fast
2820
+ // for any poll to observe a 'generating' frame — produces NO status change
2821
+ // at all (idle→idle). detectStatusTransition's change block above is skipped
2822
+ // entirely, so neither the idle→generating arm nor the starting→idle
2823
+ // fast-collapse arm ever runs, and the mesh coordinator never learns the
2824
+ // worker went idle (the live rc.403 Probe1 miss). Catch it here: an
2825
+ // already-idle poll (no status change), still inside the startup-grace
2826
+ // window, where a turn started this boot and has already finished without
2827
+ // ever arming generating. The same false-positive-safe discriminators apply
2828
+ // (currentTurnTaskId set && !pending && generating never armed), plus a
2829
+ // once-per-turn guard since this branch is re-polled while the session sits
2830
+ // idle. Normal turns that DO reach 'busy' set generatingStartedAt and are
2831
+ // excluded; a queued-pending first turn that only runs after grace falls
2832
+ // outside the window and completes normally via idle→busy→idle.
2833
+ //
2834
+ // R4d (the live rc.405 Probe2 miss): R4c anchored the window on the collapse
2835
+ // moment but still measured its END against `now` (the poll/completion time). The
2836
+ // helper only fires once the turn has FINISHED (!hasAdapterPendingResponse()), so
2837
+ // the first eligible poll happens at completion. When the first turn is dispatched
2838
+ // a few seconds after the collapse AND runs for a non-trivial duration, that
2839
+ // completion lands PAST the 12s now-anchored window even though the turn was a
2840
+ // genuine startup-grace first turn (live: collapse→dispatch +5.2s, turn ~11s →
2841
+ // completion at collapse+16.2s > 12s). Anchor the window on when the first turn
2842
+ // STARTED (engine.currentTurnStartedAt, set by onTurnStarted) instead: a turn that
2843
+ // STARTED within the collapse window is a startup-grace first turn no matter how
2844
+ // long it then ran. The now-anchored check is retained as a union so a fast turn
2845
+ // (dispatched+completed quickly within 12s of collapse) keeps firing too; both
2846
+ // close for a much-later turn, preserving the "don't mislabel a late fast turn"
2847
+ // honesty the window exists for.
2848
+ const firstTurnStartedAt = typeof (this.adapter as any)?.currentTurnStartedAt === 'number'
2849
+ ? (this.adapter as any).currentTurnStartedAt as number
2850
+ : 0;
2851
+ const collapsedAt = this.startupGraceCollapseAt;
2852
+ const turnStartedWithinCollapseWindow = collapsedAt !== null
2853
+ && firstTurnStartedAt > 0
2854
+ && firstTurnStartedAt >= collapsedAt
2855
+ && (firstTurnStartedAt - collapsedAt) < STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS;
2856
+ const nowWithinCollapseWindow = collapsedAt !== null
2857
+ && (now - collapsedAt) < STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS;
2858
+ if (
2859
+ newStatus === 'idle'
2860
+ && previousStatus === 'idle'
2861
+ && (turnStartedWithinCollapseWindow || nowWithinCollapseWindow)
2862
+ ) {
2863
+ this.maybeSynthesizeStartupGraceCollapse(chatTitle, now, 'startup_grace_idle_turn_collapse');
2864
+ }
2865
+
2866
+ // Re-arm the queue-claim agent:ready on the FSM's first GENUINE ready.
2867
+ //
2868
+ // The boot-time starting→idle one-shot above is the historical claim
2869
+ // trigger, but it is consumed too early for FSM-spec providers whose
2870
+ // INITIAL state already reports status 'idle' (e.g. antigravity-cli): the
2871
+ // adapter reports idle before maybeMarkReady has fired, so lastStatus
2872
+ // advances starting→idle while the prompt is not yet drawn and the worker
2873
+ // cannot yet claim. Subsequent state-driven idle frames are idle→idle (no
2874
+ // status change), so the one-shot never re-fires and the worker strands its
2875
+ // queued task — the coordinator then relaunch-loops every ~90s.
2876
+ //
2877
+ // The adapter surfaces fsmReadySeen=true exactly when the FSM reaches its
2878
+ // first non-initial idle (the prompt is genuinely up). On that signal we
2879
+ // emit agent:ready once more. emitAgentReadyOnce is idempotent (guarded by
2880
+ // agentReadyEmitted), so providers whose boot one-shot already landed on a
2881
+ // real ready (claude-cli / codex-cli / hermes-cli, which use a startup
2882
+ // grace and whose initial state is not idle) treat this as a no-op — no
2883
+ // double claim, no double task injection.
2884
+ if (newStatus === 'idle' && adapterStatus.fsmReadySeen === true && !this.agentReadyEmitted) {
2885
+ this.emitAgentReadyOnce(chatTitle, now);
2886
+ }
2887
+
971
2888
  this.applyProviderResponse(parsedStatus, {
972
2889
  phase: (newStatus === 'idle' && (previousStatus === 'generating' || previousStatus === 'waiting_approval'))
973
2890
  ? 'turn_completed'
@@ -976,8 +2893,42 @@ export class CliProviderInstance implements ProviderInstance {
976
2893
 
977
2894
  // Monitor check (cooldown based notification, IDE/CLI common)
978
2895
  const agentKey = `${this.type}:cli`;
979
- const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint);
2896
+ // Approval pending is detected from the raw adapter status, not `newStatus`:
2897
+ // auto-approve synthesizes `waiting_approval` → 'generating', which would
2898
+ // otherwise let the no-progress watchdog accumulate the approval wait.
2899
+ const approvalPending = rawStatus === 'waiting_approval';
2900
+ const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
2901
+ const monitorParsedStatus: any = parsedStatus;
980
2902
  for (const me of monitorEvents) {
2903
+ if (
2904
+ me.type === 'monitor:no_progress'
2905
+ && this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
2906
+ && !this.hasAdapterPendingResponse()
2907
+ && !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
2908
+ ) {
2909
+ // EVTTRACE: completion fired (no-progress monitor reconciled to completion).
2910
+ if (this.isMeshWorkerSession()) {
2911
+ traceMeshEventStage('fired', this.meshTraceCtx(), 'no_progress_monitor_final_summary');
2912
+ }
2913
+ this.emitGeneratingCompleted({
2914
+ chatTitle,
2915
+ duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
2916
+ timestamp: me.timestamp,
2917
+ finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
2918
+ completionDiagnostic: {
2919
+ providerType: this.type,
2920
+ sessionId: this.instanceId,
2921
+ providerSessionId: this.providerSessionId || null,
2922
+ reconciliationReason: 'no_progress_monitor_final_summary',
2923
+ finalAssistantPresent: true,
2924
+ },
2925
+ });
2926
+ this.generatingStartedAt = 0;
2927
+ // Cancel any pending debounce flush — monitor already fired completion.
2928
+ if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
2929
+ this.completedDebouncePending = null;
2930
+ continue;
2931
+ }
981
2932
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
982
2933
  }
983
2934
  }
@@ -997,15 +2948,61 @@ export class CliProviderInstance implements ProviderInstance {
997
2948
  workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
998
2949
  ? event.workspaceName
999
2950
  : this.workingDir,
2951
+ // Carry the workspace under BOTH `workspace` and `workspaceName` so the
2952
+ // downstream mesh forward/merge path — which reads `workspace` — can
2953
+ // propagate it to the coordinator snapshot. Without `workspace` the live
2954
+ // event path delivers an empty workspace and the dashboard falls back to
2955
+ // the generic "Terminal (Mesh Node)" title.
2956
+ workspace: typeof event.workspace === 'string' && event.workspace.trim()
2957
+ ? event.workspace
2958
+ : this.workingDir,
1000
2959
  providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
1001
2960
  ? event.providerSessionId
1002
2961
  : this.providerSessionId,
1003
2962
  };
2963
+ // TASKIDLESS: stamp the mesh task primary key on lifecycle events emitted by
2964
+ // a mesh worker session. The consumer (updateDirectDispatchStatus) was switched
2965
+ // to key on task_id (CANON-B), but the producer never carried it — so every
2966
+ // forwarded metadataEvent.taskId arrived undefined and the coordinator fell back
2967
+ // to a session_id match, which can flip a sibling dispatch row. Surface it here so
2968
+ // updateDirectDispatchStatus hits the exact PK row and the session_id fallback is
2969
+ // never exercised. Non-mesh sessions get no taskId (regression guard) —
2970
+ // isMeshWorkerSession() gates the injection.
2971
+ //
2972
+ // ARCH-REFACTOR R1 (per-turn identity): resolution order is
2973
+ // (1) an explicit taskId already on the event — the debounce-flush completion
2974
+ // path stamps the taskId captured at the generating→idle transition (the
2975
+ // turn that actually produced this completion);
2976
+ // (2) the per-turn binding (engine.currentTurnTaskId) for synchronously-emitted
2977
+ // events whose turn is still the current one;
2978
+ // (3) the legacy session scalar (settings.meshActiveTaskId) as a last-resort
2979
+ // backward-compat alias.
2980
+ // The scalar is last because it is last-write-wins: a second task attaching while
2981
+ // this turn was still running overwrites it, which is the exact NOTIF-MISDELIVER /
2982
+ // TASK-MSG-MISROUTE race this refactor removes.
2983
+ if (this.isMeshWorkerSession()) {
2984
+ const existingTaskId = typeof enrichedEvent.taskId === 'string' && enrichedEvent.taskId.trim()
2985
+ ? enrichedEvent.taskId
2986
+ : undefined;
2987
+ if (!existingTaskId) {
2988
+ const resolved = this.completingTurnTaskId();
2989
+ if (resolved) enrichedEvent.taskId = resolved;
2990
+ }
2991
+ }
1004
2992
  if (this.context?.emitProviderEvent) {
1005
2993
  this.context.emitProviderEvent(enrichedEvent);
1006
- return;
2994
+ } else {
2995
+ this.events.push(enrichedEvent);
2996
+ }
2997
+ // Auto-detach a direct-dispatch mesh assignment once the dispatched
2998
+ // task reaches a terminal state. Leaving meshNodeFor pinned would
2999
+ // route this session's next unrelated turn (a dashboard chat) into
3000
+ // the coordinator as if it were the completion of another task.
3001
+ // We schedule after the emit so the originating coordinator still
3002
+ // observes the completion event with its routing marker intact.
3003
+ if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
3004
+ try { this.detachMeshAssignment(); } catch { /* best-effort */ }
1007
3005
  }
1008
- this.events.push(enrichedEvent);
1009
3006
  }
1010
3007
 
1011
3008
  private flushEvents(): ProviderEvent[] {
@@ -1022,7 +3019,13 @@ export class CliProviderInstance implements ProviderInstance {
1022
3019
  typeof data.providerSessionId === 'string' ? data.providerSessionId : '',
1023
3020
  );
1024
3021
  if (patchedProviderSessionId) {
1025
- this.promoteProviderSessionId(patchedProviderSessionId);
3022
+ // A provider-response id is authoritative when it carries an
3023
+ // explicit `new_session` marker (the CLI genuinely started a new
3024
+ // conversation). Without that marker it's just an observed id and
3025
+ // must not hijack an existing binding (see promoteProviderSessionId).
3026
+ this.promoteProviderSessionId(patchedProviderSessionId, {
3027
+ authoritative: data.sessionEvent === 'new_session',
3028
+ });
1026
3029
  }
1027
3030
 
1028
3031
  if (data.sessionEvent === 'new_session') {
@@ -1047,7 +3050,7 @@ export class CliProviderInstance implements ProviderInstance {
1047
3050
  if (effectWhen === 'turn_completed' && options.phase !== 'turn_completed') continue;
1048
3051
  if (effectWhen === 'immediate' && options.phase === 'turn_completed') continue;
1049
3052
 
1050
- const effectKey = this.getEffectDedupKey(effect);
3053
+ const effectKey = getEffectDedupKey(effect);
1051
3054
  if (this.appliedEffectKeys.has(effectKey)) continue;
1052
3055
  this.appliedEffectKeys.add(effectKey);
1053
3056
 
@@ -1097,40 +3100,6 @@ export class CliProviderInstance implements ProviderInstance {
1097
3100
  this.appliedEffectKeys = new Set(Array.from(this.appliedEffectKeys).slice(-100));
1098
3101
  }
1099
3102
  }
1100
-
1101
- private getEffectDedupKey(effect: { id?: string; type: string; message?: { content?: unknown }; toast?: { message?: string }; notification?: { title?: string; body?: string } }): string {
1102
- if (effect.id) return `provider_effect:${effect.id}`;
1103
- if (effect.type === 'message') {
1104
- const content = typeof effect.message?.content === 'string'
1105
- ? effect.message.content
1106
- : JSON.stringify(effect.message?.content || '');
1107
- return `provider_effect:message:${content}`;
1108
- }
1109
- if (effect.type === 'notification') {
1110
- return `provider_effect:notification:${effect.notification?.title || ''}:${effect.notification?.body || ''}`;
1111
- }
1112
- return `provider_effect:toast:${effect.toast?.message || ''}`;
1113
- }
1114
-
1115
- private getPersistedEffectContent(effect: { type: string; message?: { content?: unknown }; toast?: { message?: string }; notification?: { title?: string; body?: string; bubbleContent?: unknown } }): string | null {
1116
- if (effect.type === 'message') {
1117
- return typeof effect.message?.content === 'string'
1118
- ? effect.message.content
1119
- : JSON.stringify(effect.message?.content || '');
1120
- }
1121
- if (effect.type === 'toast') {
1122
- return effect.toast?.message || null;
1123
- }
1124
- if (effect.type === 'notification') {
1125
- if (typeof effect.notification?.bubbleContent === 'string') return effect.notification.bubbleContent;
1126
- if (typeof effect.notification?.title === 'string' && effect.notification.title.trim()) {
1127
- return `${effect.notification.title}\n${effect.notification.body || ''}`.trim();
1128
- }
1129
- return effect.notification?.body || null;
1130
- }
1131
- return null;
1132
- }
1133
-
1134
3103
  // ─── Adapter access (backward compat) ──────────────────
1135
3104
 
1136
3105
  getAdapter(): ProviderCliAdapter {
@@ -1151,6 +3120,118 @@ export class CliProviderInstance implements ProviderInstance {
1151
3120
  return false;
1152
3121
  }
1153
3122
 
3123
+ /** @see ProviderInstance.noteManualInteraction */
3124
+ noteManualInteraction(now = Date.now(), opts?: { passive?: boolean }): void {
3125
+ // P1b (#137 secondary): a DELEGATED worker session must not treat a
3126
+ // passive dashboard view (foreground tab selection / panel open) as
3127
+ // manual attendance. A coordinator merely peeking at a worker's panel
3128
+ // would otherwise suppress that worker's delegated auto-approve for the
3129
+ // whole 60s window. Only explicit input/intervention (controlbar,
3130
+ // resolve_action, pty_input) attends a worker. Non-worker (foreground)
3131
+ // sessions keep noting on passive views so a user foregrounding their own
3132
+ // session still holds auto-approve to act on the modal themselves.
3133
+ if (opts?.passive && this.isMeshWorkerSession()) return;
3134
+ this.manualAttendance.note(now);
3135
+ }
3136
+
3137
+ /**
3138
+ * Whether auto-approve should be treated as active *right now* for display
3139
+ * and firing decisions: the configured intent AND the user is not currently
3140
+ * attending this session by hand. When a human is attending, auto-approve is
3141
+ * held so the modal stays visible and they can drive it via the controlbar.
3142
+ * Provider-agnostic — the attendance signal is the command set, never any
3143
+ * CLI-specific modal text.
3144
+ */
3145
+ private autoApproveEffectivelyActive(status: string | undefined, now = Date.now()): boolean {
3146
+ return status === 'waiting_approval'
3147
+ && this.shouldAutoApprove()
3148
+ && !this.manualAttendance.isAttended(now);
3149
+ }
3150
+
3151
+ // STATUS-MISMATCH: true once the current auto-approve episode has been masking
3152
+ // waiting_approval behind `generating` for longer than AUTO_APPROVE_MASK_STALL_MS without
3153
+ // resolving (the settle gate never fired). When stalled, the surface mask must be dropped
3154
+ // so read_chat / mesh_status / the dashboard see the real waiting_approval + modal (and a
3155
+ // coordinator can mesh_approve it). autoApproveMaskSince is maintained by
3156
+ // maybeAutoApproveStatus (driven by getState + the recheck timer during a waiting episode);
3157
+ // this read is side-effect-free so getStatusMetadata can consult it too.
3158
+ private autoApproveMaskStalled(now = Date.now()): boolean {
3159
+ return this.autoApproveMaskSince > 0
3160
+ && now - this.autoApproveMaskSince > CliProviderInstance.AUTO_APPROVE_MASK_STALL_MS;
3161
+ }
3162
+
3163
+ /**
3164
+ * NOTIF-APPROVAL-MASKED (Q1b): surface a delegated worker's STALLED auto-approve modal
3165
+ * to the mesh COORDINATOR, decoupled from the dashboard visible-status mask.
3166
+ *
3167
+ * When auto-approve is configured but the episode never settles (modal parse miss / the
3168
+ * settle gate never satisfied), getState()/detectStatusTransition() fold the raw
3169
+ * `waiting_approval` into `generating` to suppress dashboard flicker — so
3170
+ * detectStatusTransition()'s `waiting_approval` arm never runs and NO agent:waiting_approval
3171
+ * event is emitted. The coordinator's real-time approval-nudge delivery then has no input and
3172
+ * the worker's stuck modal is never surfaced (the live ~25s stall). The dashboard mask is
3173
+ * intentional and stays; this emits the coordinator nudge exactly ONCE, gated on the SAME
3174
+ * raw-waiting_approval + mask-stalled signal resolveModalParkStatus() distinguishes, the
3175
+ * instant the mask-stall threshold trips (the same moment getState un-folds the mask).
3176
+ *
3177
+ * Only delegated worker sessions qualify: a foreground session has no coordinator to notify,
3178
+ * and its own dashboard mask already reveals the modal on stall. A normally-resolving
3179
+ * auto-approve never reaches AUTO_APPROVE_MASK_STALL_MS, so it emits nothing here; and if a
3180
+ * masked approval clears just as this fires, rc.455's isApprovalNudgeResolved stale-drop
3181
+ * discards the nudge coordinator-side without noise. Dedup is per-episode (keyed on the
3182
+ * mask-clock value) so a modal that flaps between parsed/unparsed states is announced once.
3183
+ */
3184
+ private maybeEmitStalledApprovalNudge(adapterStatus: any, now: number): void {
3185
+ if (!this.isMeshWorkerSession()) return;
3186
+ if (adapterStatus?.status !== 'waiting_approval') return;
3187
+ if (!this.autoApproveMaskStalled(now)) return;
3188
+ // AUTOAPPROVE-FLAP-RECUR (Fix C, redesigned): the mask-stall bound tripped.
3189
+ // If auto-approve is genuinely about to fire on its own, defer to that fire —
3190
+ // the nudge would race a resolveModal landing milliseconds later, producing
3191
+ // the coordinator flap this fix targets.
3192
+ //
3193
+ // The ORIGINAL guard deferred on `pendingAutoApprovalSince && buttons > 0`
3194
+ // alone. That is FALSE-POSITIVE for a FLAPPING modal: a modal whose identity
3195
+ // changes every frame (message streaming) keeps pendingAutoApprovalSince
3196
+ // nonzero (it is re-stamped to `now` on every signature change) and keeps
3197
+ // buttons present, yet its settle clock is wiped back to ~0 each frame and
3198
+ // NEVER reaches SETTLE_MS — so auto-approve can never fire and this is exactly
3199
+ // the stuck episode the coordinator MUST be paged about. The old guard
3200
+ // silenced it permanently (the live rc.466 regression).
3201
+ //
3202
+ // Discriminator: a settle is genuinely PROGRESSING only if THIS frame's modal
3203
+ // carries the SAME identity the settle clock is already accruing against
3204
+ // (pendingAutoApprovalSignature). A stable modal keeps its signature across
3205
+ // frames → the clock climbs → resolveModal is imminent → defer. A flapping
3206
+ // modal presents a DIFFERENT signature this frame (or none — a non-concrete /
3207
+ // picker / never-captured modal) → the clock is about to reset (or never
3208
+ // engaged) → do NOT defer, page the coordinator. This is evaluated for the
3209
+ // CURRENT frame (not a stale prior-frame value), so a stable modal polled only
3210
+ // twice — start, then past the stall bound — is still correctly deferred.
3211
+ const currentSignature = this.approvableModalSignature(adapterStatus.activeModal);
3212
+ const settleProgressing = !!currentSignature
3213
+ && this.pendingAutoApprovalSince > 0
3214
+ && currentSignature === this.pendingAutoApprovalSignature;
3215
+ if (settleProgressing) return;
3216
+ // Exactly once per stalled episode (autoApproveMaskSince uniquely identifies it).
3217
+ if (this.stalledApprovalNudgeEpisode === this.autoApproveMaskSince) return;
3218
+ this.stalledApprovalNudgeEpisode = this.autoApproveMaskSince;
3219
+ const modal = adapterStatus.activeModal;
3220
+ const dirName = workingDirBasename(this.workingDir);
3221
+ const chatTitle = `${this.provider.name} · ${dirName}`;
3222
+ this.appendRuntimeSystemMessage(
3223
+ formatApprovalRequestMessage(modal?.message, modal?.buttons),
3224
+ `approval_request:${now}`,
3225
+ now,
3226
+ );
3227
+ this.pushEvent({
3228
+ event: 'agent:waiting_approval', chatTitle, timestamp: now,
3229
+ modalMessage: modal?.message,
3230
+ modalButtons: modal?.buttons,
3231
+ });
3232
+ LOG.info('CLI', `[${this.type}] stalled auto-approve nudge → coordinator (masked ${Math.round((now - this.autoApproveMaskSince) / 1000)}s)`);
3233
+ }
3234
+
1154
3235
  private recordAutoApproval(modalMessage?: string, buttonLabel?: string, now = Date.now()): void {
1155
3236
  this.appendRuntimeSystemMessage(
1156
3237
  formatAutoApprovalMessage(modalMessage, buttonLabel),
@@ -1170,12 +3251,6 @@ export class CliProviderInstance implements ProviderInstance {
1170
3251
  );
1171
3252
  }
1172
3253
 
1173
- private formatMarkerTimestamp(timestamp: number): string {
1174
- const date = new Date(timestamp);
1175
- const pad = (value: number) => String(value).padStart(2, '0');
1176
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
1177
- }
1178
-
1179
3254
  private maybeAppendRuntimeRecoveryMessage(runtime: PtyRuntimeMetadata | null): void {
1180
3255
  if (!runtime?.restoredFromStorage || !runtime.runtimeId) return;
1181
3256
 
@@ -1238,7 +3313,7 @@ export class CliProviderInstance implements ProviderInstance {
1238
3313
  receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
1239
3314
  historyDedupKey: dedupKey,
1240
3315
  }],
1241
- this.adapter.getScriptParsedStatus?.()?.title || this.workingDir.split('/').filter(Boolean).pop() || 'session',
3316
+ this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
1242
3317
  this.instanceId,
1243
3318
  this.providerSessionId,
1244
3319
  );
@@ -1246,102 +3321,46 @@ export class CliProviderInstance implements ProviderInstance {
1246
3321
  }
1247
3322
 
1248
3323
  mergeRuntimeChatMessages(parsedMessages: ChatMessage[]): ChatMessage[] {
1249
- return this.mergeConversationMessages(parsedMessages);
1250
- }
1251
-
1252
- private mergeConversationMessages(parsedMessages: any[]): ChatMessage[] {
1253
- if (this.runtimeMessages.length === 0) return normalizeChatMessages(parsedMessages);
1254
-
1255
- type MergeEntry = { message: ChatMessage; index: number; source: 'parsed' | 'runtime'; runtimeKey?: string };
1256
- const parsedEntries: MergeEntry[] = parsedMessages.map((message, index) => ({
1257
- message,
1258
- index,
1259
- source: 'parsed',
1260
- }));
1261
- const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
1262
- message: entry.message,
1263
- index: parsedMessages.length + index,
1264
- source: 'runtime',
1265
- runtimeKey: entry.key,
1266
- }));
1267
- const getTime = (message: ChatMessage): number => {
1268
- const value = typeof message.receivedAt === 'number'
1269
- ? message.receivedAt
1270
- : typeof message.timestamp === 'number'
1271
- ? message.timestamp
1272
- : 0;
1273
- return Number.isFinite(value) && value > 0 ? value : 0;
1274
- };
1275
-
1276
- const getRole = (message: ChatMessage): string => typeof message.role === 'string'
1277
- ? message.role.trim().toLowerCase()
1278
- : '';
1279
- const isRuntimeOverlay = (entry: MergeEntry): boolean => {
1280
- if (entry.source !== 'runtime') return false;
1281
- const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
1282
- if (key.startsWith('auto_approval:')) return true;
1283
- return !isUserFacingChatMessage(entry.message);
1284
- };
1285
- const shouldKeepParsedBeforeUntimedRuntime = (message: ChatMessage): boolean => {
1286
- const role = getRole(message);
1287
- return role === 'user' || role === 'human';
1288
- };
1289
- const shouldKeepParsedAfterUntimedRuntime = (message: ChatMessage): boolean => {
1290
- const role = getRole(message);
1291
- if (role !== 'assistant') return false;
1292
- const kind = resolveChatMessageKind(message);
1293
- return kind === 'standard' || kind === 'terminal';
1294
- };
1295
-
1296
- return normalizeChatMessages([...parsedEntries, ...runtimeEntries]
1297
- .sort((a, b) => {
1298
- const aTime = getTime(a.message);
1299
- const bTime = getTime(b.message);
1300
- if (aTime && bTime && aTime !== bTime) return aTime - bTime;
1301
- if (a.source !== b.source && aTime !== bTime) {
1302
- const parsedEntry = a.source === 'parsed' ? a : b.source === 'parsed' ? b : null;
1303
- const runtimeEntry = a.source === 'runtime' ? a : b.source === 'runtime' ? b : null;
1304
- if (parsedEntry && runtimeEntry && isRuntimeOverlay(runtimeEntry) && getTime(parsedEntry.message) === 0 && getTime(runtimeEntry.message) > 0) {
1305
- if (shouldKeepParsedBeforeUntimedRuntime(parsedEntry.message)) {
1306
- return a.source === 'parsed' ? -1 : 1;
1307
- }
1308
- if (shouldKeepParsedAfterUntimedRuntime(parsedEntry.message)) {
1309
- return a.source === 'parsed' ? 1 : -1;
1310
- }
1311
- }
1312
- }
1313
- // Many provider-owned CLI transcripts (including Hermes CLI in debug bundles)
1314
- // do not carry timestamps on parsed messages. In that case there is no safe
1315
- // clock basis for interleaving timestamped runtime/system messages into the
1316
- // provider transcript. Keep user prompts before runtime overlays, but do not
1317
- // let timed runtime/system/tool/internal overlays become the final chat turns
1318
- // after an untimed parsed assistant transcript.
1319
- return a.index - b.index;
1320
- })
1321
- .map((entry) => entry.message));
3324
+ return mergeConversationMessages(this.runtimeMessages, parsedMessages);
1322
3325
  }
1323
3326
 
1324
- private formatApprovalRequestMessage(modalMessage?: string, buttons?: string[]): string {
1325
- const lines = ['Approval requested'];
1326
- const cleanMessage = String(modalMessage || '').trim();
1327
- if (cleanMessage) lines.push(cleanMessage);
1328
- const labels = (buttons || []).map((button) => String(button || '').trim()).filter(Boolean);
1329
- if (labels.length > 0) {
1330
- lines.push(labels.map((label) => `[${label}]`).join(' '));
1331
- }
1332
- return lines.join('\n');
1333
- }
1334
-
1335
- private promoteProviderSessionId(sessionId: string): void {
3327
+ private promoteProviderSessionId(sessionId: string, opts: { authoritative?: boolean } = {}): void {
1336
3328
  const nextSessionId = String(sessionId || '').trim();
1337
3329
  if (!nextSessionId || nextSessionId === this.providerSessionId) return;
1338
3330
 
3331
+ // Sticky binding: once this instance is bound to a provider session,
3332
+ // an *observed* id (one discovered from a status parse or the native
3333
+ // history reader) must NOT hijack the live binding. hermes ≥0.14
3334
+ // spawns a fresh `sessions` row per internal sub-session, so a
3335
+ // newest-wins native read surfaces a different id mid-turn on every
3336
+ // poll; accepting it would re-bind the instance, re-hydrate unbounded
3337
+ // history (daemon saturation) and reset completion detection so the
3338
+ // turn never finalizes. Only an *authoritative* change — the first
3339
+ // bind (no id yet) or an explicit provider `new_session`/resume — may
3340
+ // replace an existing binding. Legitimate resume/new-session paths
3341
+ // pass authoritative:true and are unaffected.
3342
+ if (this.providerSessionId && !opts.authoritative) {
3343
+ LOG.debug('CLI', `[${this.type}] ignoring non-authoritative session id ${nextSessionId} (bound to ${this.providerSessionId})`);
3344
+ return;
3345
+ }
3346
+
1339
3347
  const previousHistorySessionId = this.providerSessionId || this.instanceId;
1340
3348
  const previousProviderSessionId = this.providerSessionId;
1341
3349
  this.providerSessionId = nextSessionId;
3350
+ // Conversation-binding lock (antigravity): the moment this session is
3351
+ // authoritatively bound to a conversation uuid, claim it so a concurrent
3352
+ // sibling session's newest-on-disk discovery can never resolve to the
3353
+ // same .db (RCA: two antigravity sessions ~94ms apart shared one store
3354
+ // and cross-routed completions). Released on dispose().
3355
+ if (this.type === 'antigravity-cli') {
3356
+ const owner = this.antigravityClaimOwner();
3357
+ if (owner) claimAntigravityConversation(nextSessionId, owner);
3358
+ }
1342
3359
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
1343
3360
  this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
1344
- this.restorePersistedHistoryFromCurrentSession();
3361
+ if (this.shouldHydrateExistingProviderHistory()) {
3362
+ this.restorePersistedHistoryFromCurrentSession();
3363
+ }
1345
3364
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
1346
3365
  this.onProviderSessionResolved?.({
1347
3366
  instanceId: this.instanceId,
@@ -1354,13 +3373,39 @@ export class CliProviderInstance implements ProviderInstance {
1354
3373
  LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
1355
3374
  }
1356
3375
 
1357
- private syncCanonicalSavedHistoryIfNeeded(): boolean {
3376
+ private shouldHydrateExistingProviderHistory(): boolean {
3377
+ return this.launchMode === 'resume' || this.launchMode === 'manual';
3378
+ }
3379
+
3380
+ private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
3381
+ if (this.launchMode !== 'new') return false;
3382
+ if (this.providerSessionId) return false;
3383
+ if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
3384
+ if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
3385
+ if (parsedProviderSessionId) return true;
3386
+
3387
+ const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
3388
+
3389
+ // Untimestamped idle parser output during a fresh launch is usually the
3390
+ // provider's last workspace transcript before a new turn exists.
3391
+ return newestMessageAt === 0;
3392
+ }
3393
+
3394
+ private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
1358
3395
  if (!this.providerSessionId) return false;
1359
- const canonicalHistory = this.provider.canonicalHistory;
3396
+ const canonicalHistory = this.provider.nativeHistory;
1360
3397
  if (!canonicalHistory) return false;
1361
3398
 
3399
+ // Per-status-report hydration reads only a bounded tail (snapshot needs at
3400
+ // most the newest 60). The once-per-resume restore path passes full:true
3401
+ // because seedSessionHistory needs the COMPLETE transcript to seed dedup
3402
+ // state. The read-cache key encodes the window so the bounded and full
3403
+ // reads don't share/clobber each other's 2s cache entry.
3404
+ const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
3405
+ const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
3406
+
1362
3407
  if (isNativeSourceCanonicalHistory(canonicalHistory)) {
1363
- const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
3408
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
1364
3409
  const now = Date.now();
1365
3410
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1366
3411
  return true;
@@ -1373,7 +3418,7 @@ export class CliProviderInstance implements ProviderInstance {
1373
3418
  historySessionId: this.providerSessionId,
1374
3419
  workspace: this.workingDir,
1375
3420
  offset: 0,
1376
- limit: Number.MAX_SAFE_INTEGER,
3421
+ limit,
1377
3422
  historyBehavior: this.provider.historyBehavior,
1378
3423
  scripts: this.provider.scripts as any,
1379
3424
  });
@@ -1390,7 +3435,7 @@ export class CliProviderInstance implements ProviderInstance {
1390
3435
  }
1391
3436
 
1392
3437
  try {
1393
- const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
3438
+ const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
1394
3439
  const now = Date.now();
1395
3440
  if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
1396
3441
  return true;
@@ -1401,7 +3446,14 @@ export class CliProviderInstance implements ProviderInstance {
1401
3446
  if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
1402
3447
  return false;
1403
3448
  }
1404
- const restoredHistory = readChatHistory(this.type, 0, Number.MAX_SAFE_INTEGER, this.providerSessionId, 0, this.provider.historyBehavior);
3449
+ // Bounded by default: the per-status-report path only needs the newest
3450
+ // STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
3451
+ // activeChat.messages to the last 60 (status/normalize.ts) and loads
3452
+ // the rest lazily via read_chat on subscribe. The once-per-resume
3453
+ // restore path passes full:true so seedSessionHistory still sees the
3454
+ // COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
3455
+ // a bounded limit as an O(tail) read.
3456
+ const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
1405
3457
  this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
1406
3458
  role: message.role,
1407
3459
  content: message.content,
@@ -1417,10 +3469,13 @@ export class CliProviderInstance implements ProviderInstance {
1417
3469
 
1418
3470
  private restorePersistedHistoryFromCurrentSession(): void {
1419
3471
  if (!this.providerSessionId) return;
1420
- this.syncCanonicalSavedHistoryIfNeeded();
1421
- const restoredHistory = isNativeSourceCanonicalHistory(this.provider.canonicalHistory)
3472
+ // Restore is the once-per-resume seeding path: it needs the COMPLETE
3473
+ // transcript so seedSessionHistory can prime dedup state. Pass full so the
3474
+ // hydration read is unbounded here (and only here).
3475
+ this.syncCanonicalSavedHistoryIfNeeded({ full: true });
3476
+ const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
1422
3477
  ? readProviderChatHistory(this.type, {
1423
- canonicalHistory: this.provider.canonicalHistory,
3478
+ canonicalHistory: this.provider.nativeHistory,
1424
3479
  historySessionId: this.providerSessionId,
1425
3480
  workspace: this.workingDir,
1426
3481
  offset: 0,