@duckmind/dm-windows-x64 0.61.5 → 0.62.1

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 (285) hide show
  1. package/dm.exe +0 -0
  2. package/extensions/.dm-extensions.json +215 -71
  3. package/extensions/dm-cua/bin/browser-cua.mjs +6 -1
  4. package/extensions/dm-cua/index.js +3 -2
  5. package/extensions/dm-cua/src/browser-cua-lib.mjs +69 -13
  6. package/extensions/dm-subagents/agents/claude-code-writer.md +15 -0
  7. package/extensions/dm-subagents/agents/claude-code.md +15 -0
  8. package/extensions/dm-subagents/agents/codex-exec-writer.md +15 -0
  9. package/extensions/dm-subagents/agents/codex-exec.md +15 -0
  10. package/extensions/dm-subagents/agents/cursor-agent-writer.md +14 -0
  11. package/extensions/dm-subagents/agents/cursor-agent.md +14 -0
  12. package/extensions/dm-subagents/agents/delegate.md +3 -2
  13. package/extensions/dm-subagents/agents/oracle.md +10 -5
  14. package/extensions/dm-subagents/agents/researcher.md +2 -2
  15. package/extensions/dm-subagents/agents/reviewer.md +17 -7
  16. package/extensions/dm-subagents/agents/scout.md +5 -5
  17. package/extensions/dm-subagents/agents/worker.md +6 -2
  18. package/extensions/dm-subagents/async-retention-discovery-worker.mjs +167 -0
  19. package/extensions/dm-subagents/index.js +4 -0
  20. package/extensions/dm-subagents/inspector-runner.mjs +10 -0
  21. package/extensions/dm-subagents/install.mjs +3 -2
  22. package/extensions/dm-subagents/package.json +2 -2
  23. package/extensions/dm-subagents/prompts/council.md +60 -0
  24. package/extensions/dm-subagents/prompts/parallel-review.md +5 -1
  25. package/extensions/dm-subagents/prompts/review-loop.md +13 -7
  26. package/extensions/dm-subagents/skills/council-mode/SKILL.md +59 -0
  27. package/extensions/dm-subagents/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/extensions/dm-subagents/skills/dm-subagents/SKILL.md +96 -911
  29. package/extensions/dm-subagents/skills/dm-subagents/references/constraints-and-recipes.md +70 -0
  30. package/extensions/dm-subagents/skills/dm-subagents/references/execution-controls.md +539 -0
  31. package/extensions/dm-subagents/skills/dm-subagents/references/management-authoring-rpc.md +161 -0
  32. package/extensions/dm-subagents/skills/dm-subagents/references/multi-lane-orchestration.md +51 -0
  33. package/extensions/dm-subagents/skills/dm-subagents/references/prompting-and-roles.md +295 -0
  34. package/extensions/dm-subagents/skills/dm-subagents/references/review-and-validation.md +73 -0
  35. package/extensions/dm-subagents/src/agents/agent-management.js +716 -484
  36. package/extensions/dm-subagents/src/agents/agent-refinements.js +563 -0
  37. package/extensions/dm-subagents/src/agents/agent-serializer.js +70 -5
  38. package/extensions/dm-subagents/src/agents/agents.js +1447 -299
  39. package/extensions/dm-subagents/src/agents/builtin-names.js +15 -0
  40. package/extensions/dm-subagents/src/agents/chain-serializer.js +12 -7
  41. package/extensions/dm-subagents/src/agents/frontmatter.js +64 -14
  42. package/extensions/dm-subagents/src/agents/identity.js +1 -1
  43. package/extensions/dm-subagents/src/agents/proactive-skills.js +14 -11
  44. package/extensions/dm-subagents/src/agents/runtime-agent-events.js +49 -0
  45. package/extensions/dm-subagents/src/agents/runtime-agent-registry.js +412 -0
  46. package/extensions/dm-subagents/src/agents/skills.js +52 -35
  47. package/extensions/dm-subagents/src/api/agents.js +6 -0
  48. package/extensions/dm-subagents/src/api/background-work.js +151 -0
  49. package/extensions/dm-subagents/src/api/capability-ceiling.js +12 -0
  50. package/extensions/dm-subagents/src/api/control-channel.js +3 -0
  51. package/extensions/dm-subagents/src/api/delegation.js +5 -0
  52. package/extensions/dm-subagents/src/api/dm-args.js +3 -0
  53. package/extensions/dm-subagents/src/api/external-job-provider.js +137 -0
  54. package/extensions/dm-subagents/src/api/external-runs.js +233 -0
  55. package/extensions/dm-subagents/src/api/intercom-bridge.js +3 -0
  56. package/extensions/dm-subagents/src/api/preflight.js +322 -0
  57. package/extensions/dm-subagents/src/api/project-panes.js +11 -0
  58. package/extensions/dm-subagents/src/api/shared-types.js +4 -0
  59. package/extensions/dm-subagents/src/extension/config.js +175 -0
  60. package/extensions/dm-subagents/src/extension/control-notices.js +4 -43
  61. package/extensions/dm-subagents/src/extension/doctor.js +71 -17
  62. package/extensions/dm-subagents/src/extension/fanout-child.js +49 -32
  63. package/extensions/dm-subagents/src/extension/index.js +711 -265
  64. package/extensions/dm-subagents/src/extension/public-execution.js +114 -0
  65. package/extensions/dm-subagents/src/extension/rpc.js +427 -22
  66. package/extensions/dm-subagents/src/extension/schemas.js +158 -65
  67. package/extensions/dm-subagents/src/extension/steering-notices.js +23 -0
  68. package/extensions/dm-subagents/src/extension/subagent-guide.js +31 -0
  69. package/extensions/dm-subagents/src/extension/tool-description.js +92 -74
  70. package/extensions/dm-subagents/src/extension/tool-result.js +7 -0
  71. package/extensions/dm-subagents/src/inspectors/herdr/actions.js +218 -0
  72. package/extensions/dm-subagents/src/inspectors/herdr/client.js +123 -0
  73. package/extensions/dm-subagents/src/inspectors/herdr/focus.js +47 -0
  74. package/extensions/dm-subagents/src/inspectors/herdr/inspector-runner.js +160 -0
  75. package/extensions/dm-subagents/src/inspectors/herdr/project-panes.js +618 -0
  76. package/extensions/dm-subagents/src/inspectors/herdr/session-roots-codec.js +21 -0
  77. package/extensions/dm-subagents/src/inspectors/herdr/shell-command.js +15 -0
  78. package/extensions/dm-subagents/src/integrations/herdr-status.js +377 -0
  79. package/extensions/dm-subagents/src/intercom/intercom-bridge.js +17 -13
  80. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +371 -79
  81. package/extensions/dm-subagents/src/intercom/result-intercom.js +47 -7
  82. package/extensions/dm-subagents/src/missions/actions.js +394 -0
  83. package/extensions/dm-subagents/src/missions/goal-driver.js +149 -0
  84. package/extensions/dm-subagents/src/missions/lifecycle.js +331 -0
  85. package/extensions/dm-subagents/src/missions/store.js +548 -0
  86. package/extensions/dm-subagents/src/missions/types.js +9 -0
  87. package/extensions/dm-subagents/src/missions/workflow-state.js +245 -0
  88. package/extensions/dm-subagents/src/policy/authority.js +37 -0
  89. package/extensions/dm-subagents/src/profiles/profiles.js +36 -18
  90. package/extensions/dm-subagents/src/runs/background/active-async-capacity.js +427 -0
  91. package/extensions/dm-subagents/src/runs/background/active-run-index.js +122 -0
  92. package/extensions/dm-subagents/src/runs/background/async-execution.js +925 -137
  93. package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +515 -148
  94. package/extensions/dm-subagents/src/runs/background/async-resume.js +378 -51
  95. package/extensions/dm-subagents/src/runs/background/async-retention.js +828 -0
  96. package/extensions/dm-subagents/src/runs/background/async-status-snapshot.js +31 -0
  97. package/extensions/dm-subagents/src/runs/background/async-status.js +259 -22
  98. package/extensions/dm-subagents/src/runs/background/auto-drain.js +46 -0
  99. package/extensions/dm-subagents/src/runs/background/chain-append.js +50 -15
  100. package/extensions/dm-subagents/src/runs/background/chain-root-attachment.js +67 -12
  101. package/extensions/dm-subagents/src/runs/background/completion-batcher.js +5 -1
  102. package/extensions/dm-subagents/src/runs/background/completion-dedupe.js +3 -11
  103. package/extensions/dm-subagents/src/runs/background/completion-replay.js +245 -0
  104. package/extensions/dm-subagents/src/runs/background/control-channel.js +423 -36
  105. package/extensions/dm-subagents/src/runs/background/fleet-view.js +132 -59
  106. package/extensions/dm-subagents/src/runs/background/index-segment.js +38 -0
  107. package/extensions/dm-subagents/src/runs/background/inspect-rpc.js +373 -0
  108. package/extensions/dm-subagents/src/runs/background/notify.js +357 -57
  109. package/extensions/dm-subagents/src/runs/background/owned-process-tree.js +86 -0
  110. package/extensions/dm-subagents/src/runs/background/process-terminal.js +269 -0
  111. package/extensions/dm-subagents/src/runs/background/result-delivery-ownership.js +34 -0
  112. package/extensions/dm-subagents/src/runs/background/result-files.js +469 -0
  113. package/extensions/dm-subagents/src/runs/background/result-watcher.js +540 -75
  114. package/extensions/dm-subagents/src/runs/background/resume-guidance.js +44 -0
  115. package/extensions/dm-subagents/src/runs/background/retained-children.js +119 -0
  116. package/extensions/dm-subagents/src/runs/background/run-id-query.js +5 -0
  117. package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +93 -9
  118. package/extensions/dm-subagents/src/runs/background/run-status.js +303 -32
  119. package/extensions/dm-subagents/src/runs/background/scheduled-runs.js +784 -376
  120. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +75 -34
  121. package/extensions/dm-subagents/src/runs/background/steering.js +221 -0
  122. package/extensions/dm-subagents/src/runs/background/subagent-runner.js +3106 -844
  123. package/extensions/dm-subagents/src/runs/background/subagent-wait.js +529 -0
  124. package/extensions/dm-subagents/src/runs/background/terminal-run-index.js +106 -0
  125. package/extensions/dm-subagents/src/runs/background/top-level-async.js +1 -1
  126. package/extensions/dm-subagents/src/runs/background/wait-completions.js +155 -0
  127. package/extensions/dm-subagents/src/runs/background/wait-config.js +46 -0
  128. package/extensions/dm-subagents/src/runs/background/wait-subscriptions.js +278 -0
  129. package/extensions/dm-subagents/src/runs/background/wait-tool.js +47 -0
  130. package/extensions/dm-subagents/src/runs/foreground/async-dismiss-action.js +81 -0
  131. package/extensions/dm-subagents/src/runs/foreground/async-steering-action.js +245 -0
  132. package/extensions/dm-subagents/src/runs/foreground/async-stop-action.js +74 -0
  133. package/extensions/dm-subagents/src/runs/foreground/execution.js +1401 -342
  134. package/extensions/dm-subagents/src/runs/foreground/foreground-control.js +133 -0
  135. package/extensions/dm-subagents/src/runs/foreground/foreground-history.js +148 -0
  136. package/extensions/dm-subagents/src/runs/foreground/prompt-audit.js +139 -0
  137. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +4278 -1441
  138. package/extensions/dm-subagents/src/runs/foreground/workflow-detach-reconcile.js +278 -0
  139. package/extensions/dm-subagents/src/runs/foreground/workflow-foreground-steering.js +155 -0
  140. package/extensions/dm-subagents/src/runs/shared/abort-recovery.js +97 -0
  141. package/extensions/dm-subagents/src/runs/shared/acceptance.js +597 -148
  142. package/extensions/dm-subagents/src/runs/shared/agent-contract.js +35 -0
  143. package/extensions/dm-subagents/src/runs/shared/async-status-projection.js +472 -0
  144. package/extensions/dm-subagents/src/runs/shared/background-process-options.js +6 -0
  145. package/extensions/dm-subagents/src/runs/shared/capability-ceiling.js +175 -0
  146. package/extensions/dm-subagents/src/runs/shared/child-identity.js +32 -0
  147. package/extensions/dm-subagents/src/runs/shared/child-launch-plan.js +65 -0
  148. package/extensions/dm-subagents/src/runs/shared/child-protocol.js +447 -0
  149. package/extensions/dm-subagents/src/runs/shared/claude-code-adapter.js +120 -0
  150. package/extensions/dm-subagents/src/runs/shared/codex-exec-adapter.js +129 -0
  151. package/extensions/dm-subagents/src/runs/shared/completion-evidence.js +40 -0
  152. package/extensions/dm-subagents/src/runs/shared/completion-guard.js +140 -83
  153. package/extensions/dm-subagents/src/runs/shared/context-mode.js +38 -0
  154. package/extensions/dm-subagents/src/runs/shared/cursor-agent-adapter.js +101 -0
  155. package/extensions/dm-subagents/src/runs/shared/dm-args.js +445 -72
  156. package/extensions/dm-subagents/src/runs/shared/dm-spawn.js +27 -16
  157. package/extensions/dm-subagents/src/runs/shared/dynamic-fanout.js +19 -6
  158. package/extensions/dm-subagents/src/runs/shared/extension-bindings.js +81 -0
  159. package/extensions/dm-subagents/src/runs/shared/external-cli-contract.js +134 -0
  160. package/extensions/dm-subagents/src/runs/shared/external-cli-preflight.js +98 -0
  161. package/extensions/dm-subagents/src/runs/shared/external-cli-runner.js +419 -0
  162. package/extensions/dm-subagents/src/runs/shared/external-job-bridge.js +404 -0
  163. package/extensions/dm-subagents/src/runs/shared/external-job-runner.js +334 -0
  164. package/extensions/dm-subagents/src/runs/shared/fast-mode-extension.js +8 -0
  165. package/extensions/dm-subagents/src/runs/shared/host-step-status.js +228 -0
  166. package/extensions/dm-subagents/src/runs/shared/lane-metadata.js +104 -0
  167. package/extensions/dm-subagents/src/runs/shared/launch-cwd.js +17 -0
  168. package/extensions/dm-subagents/src/runs/shared/llm-intent-arbiter.js +190 -0
  169. package/extensions/dm-subagents/src/runs/shared/long-running-guard.js +48 -3
  170. package/extensions/dm-subagents/src/runs/shared/mcp-config-sources.js +387 -0
  171. package/extensions/dm-subagents/src/runs/shared/mcp-direct-tool-allowlist.js +212 -137
  172. package/extensions/dm-subagents/src/runs/shared/mcp-direct-tool-grant.js +131 -0
  173. package/extensions/dm-subagents/src/runs/shared/model-exclusions.js +207 -0
  174. package/extensions/dm-subagents/src/runs/shared/model-fallback.js +225 -55
  175. package/extensions/dm-subagents/src/runs/shared/model-scope.js +85 -28
  176. package/extensions/dm-subagents/src/runs/shared/mutation-evidence.js +182 -0
  177. package/extensions/dm-subagents/src/runs/shared/nested-events.js +264 -102
  178. package/extensions/dm-subagents/src/runs/shared/nested-render.js +15 -5
  179. package/extensions/dm-subagents/src/runs/shared/orca-progress-tabs.js +505 -0
  180. package/extensions/dm-subagents/src/runs/shared/parallel-handoff.js +653 -0
  181. package/extensions/dm-subagents/src/runs/shared/parallel-utils.js +29 -12
  182. package/extensions/dm-subagents/src/runs/shared/permissions.js +108 -0
  183. package/extensions/dm-subagents/src/runs/shared/process-signal.js +13 -0
  184. package/extensions/dm-subagents/src/runs/shared/run-fanout-budget.js +257 -0
  185. package/extensions/dm-subagents/src/runs/shared/run-history.js +133 -13
  186. package/extensions/dm-subagents/src/runs/shared/runtime-acknowledged-extensions.js +62 -0
  187. package/extensions/dm-subagents/src/runs/shared/session-lease.js +225 -0
  188. package/extensions/dm-subagents/src/runs/shared/single-output.js +129 -27
  189. package/extensions/dm-subagents/src/runs/shared/spawn-budget.js +95 -0
  190. package/extensions/dm-subagents/src/runs/shared/structured-output.js +129 -10
  191. package/extensions/dm-subagents/src/runs/shared/subagent-control.js +66 -11
  192. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +548 -70
  193. package/extensions/dm-subagents/src/runs/shared/subagent-startup-retry.js +50 -0
  194. package/extensions/dm-subagents/src/runs/shared/task-intent.js +130 -0
  195. package/extensions/dm-subagents/src/runs/shared/tool-availability.js +59 -0
  196. package/extensions/dm-subagents/src/runs/shared/tool-budget.js +7 -5
  197. package/extensions/dm-subagents/src/runs/shared/tool-timeout.js +64 -0
  198. package/extensions/dm-subagents/src/runs/shared/usage-budget.js +74 -0
  199. package/extensions/dm-subagents/src/runs/shared/workflow-graph.js +22 -0
  200. package/extensions/dm-subagents/src/runs/shared/worktree-cleanup-plan.js +721 -0
  201. package/extensions/dm-subagents/src/runs/shared/worktree.js +168 -19
  202. package/extensions/dm-subagents/src/shared/accessible-dir.js +35 -0
  203. package/extensions/dm-subagents/src/shared/agent-stream-options.js +3 -0
  204. package/extensions/dm-subagents/src/shared/artifacts.js +170 -11
  205. package/extensions/dm-subagents/src/shared/atomic-json.js +36 -38
  206. package/extensions/dm-subagents/src/shared/capacity-resilient-json.js +77 -0
  207. package/extensions/dm-subagents/src/shared/child-session-name.js +15 -0
  208. package/extensions/dm-subagents/src/shared/child-transcript.js +57 -2
  209. package/extensions/dm-subagents/src/shared/completion-owner.js +7 -0
  210. package/extensions/dm-subagents/src/shared/display-text.js +142 -0
  211. package/extensions/dm-subagents/src/shared/extension-context.js +17 -0
  212. package/extensions/dm-subagents/src/shared/file-coalescer.js +9 -0
  213. package/extensions/dm-subagents/src/shared/file-system-retry.js +56 -0
  214. package/extensions/dm-subagents/src/shared/fork-context.js +96 -33
  215. package/extensions/dm-subagents/src/shared/formatters.js +21 -7
  216. package/extensions/dm-subagents/src/shared/launch-contract.js +94 -0
  217. package/extensions/dm-subagents/src/shared/model-info.js +10 -5
  218. package/extensions/dm-subagents/src/shared/node-executable.js +19 -0
  219. package/extensions/dm-subagents/src/shared/prompt-resources.js +10 -0
  220. package/extensions/dm-subagents/src/shared/pruned-fork.js +427 -0
  221. package/extensions/dm-subagents/src/shared/session-file-trust.js +19 -0
  222. package/extensions/dm-subagents/src/shared/session-tokens.js +14 -3
  223. package/extensions/dm-subagents/src/shared/settings.js +39 -47
  224. package/extensions/dm-subagents/src/shared/shortcuts.js +16 -0
  225. package/extensions/dm-subagents/src/shared/status-format.js +9 -2
  226. package/extensions/dm-subagents/src/shared/thinking-ceiling.js +41 -0
  227. package/extensions/dm-subagents/src/shared/types.js +47 -7
  228. package/extensions/dm-subagents/src/shared/utf8.js +12 -0
  229. package/extensions/dm-subagents/src/shared/utils.js +151 -131
  230. package/extensions/dm-subagents/src/shared/watch-strategy.js +3 -0
  231. package/extensions/dm-subagents/src/shared/workflow-child-permit.js +84 -0
  232. package/extensions/dm-subagents/src/slash/delegation-adapters.js +274 -0
  233. package/extensions/dm-subagents/src/slash/delegation-json.js +113 -0
  234. package/extensions/dm-subagents/src/slash/delegation-request.js +152 -0
  235. package/extensions/dm-subagents/src/slash/prompt-template-bridge.js +294 -243
  236. package/extensions/dm-subagents/src/slash/prompt-workflows.js +35 -73
  237. package/extensions/dm-subagents/src/slash/selector.js +101 -0
  238. package/extensions/dm-subagents/src/slash/slash-bridge.js +17 -1
  239. package/extensions/dm-subagents/src/slash/slash-commands.js +722 -732
  240. package/extensions/dm-subagents/src/slash/slash-live-state.js +37 -19
  241. package/extensions/dm-subagents/src/slash/subagents-admin.js +410 -0
  242. package/extensions/dm-subagents/src/tui/fleet-status.js +824 -0
  243. package/extensions/dm-subagents/src/tui/fleet-transcript.js +479 -0
  244. package/extensions/dm-subagents/src/tui/fleet.js +1326 -0
  245. package/extensions/dm-subagents/src/tui/render-helpers.js +22 -0
  246. package/extensions/dm-subagents/src/tui/render.js +1511 -261
  247. package/extensions/dm-subagents/src/watchdog/change-signature.js +220 -0
  248. package/extensions/dm-subagents/src/watchdog/child-status.js +151 -0
  249. package/extensions/dm-subagents/src/watchdog/emission-guard.js +90 -0
  250. package/extensions/dm-subagents/src/watchdog/lsp-diagnostics.js +484 -0
  251. package/extensions/dm-subagents/src/watchdog/model-selection.js +154 -0
  252. package/extensions/dm-subagents/src/watchdog/permission-arbiter.js +138 -0
  253. package/extensions/dm-subagents/src/watchdog/register-child.js +112 -0
  254. package/extensions/dm-subagents/src/watchdog/register-main.js +419 -0
  255. package/extensions/dm-subagents/src/watchdog/render.js +54 -0
  256. package/extensions/dm-subagents/src/watchdog/review.js +251 -0
  257. package/extensions/dm-subagents/src/watchdog/runtime.js +803 -0
  258. package/extensions/dm-subagents/src/watchdog/scope.js +56 -0
  259. package/extensions/dm-subagents/src/watchdog/settings.js +515 -0
  260. package/extensions/dm-subagents/src/watchdog/tool-actions.js +151 -0
  261. package/extensions/dm-subagents/src/watchdog/turn-delta.js +169 -0
  262. package/extensions/dm-subagents/src/watchdog/types.js +29 -0
  263. package/extensions/dm-subagents/src/watchdog/warning-format.js +58 -0
  264. package/extensions/dm-subagents/src/workflows/chat-progress.js +116 -0
  265. package/extensions/dm-subagents/src/workflows/host-command.js +227 -0
  266. package/extensions/dm-subagents/src/workflows/scripted-workflow.js +2011 -0
  267. package/extensions/dm-subagents/src/workflows/workflow-child-summary.js +116 -0
  268. package/extensions/dm-subagents/src/workflows/workflow-preflight.js +243 -0
  269. package/extensions/dm-subagents/src/workflows/workflow-receipt.js +387 -0
  270. package/extensions/dm-subagents/src/workflows/workflow-settlement.js +189 -0
  271. package/extensions/greedysearch-dm/bin/cdp.mjs +28 -3
  272. package/extensions/greedysearch-dm/bin/launch.mjs +2 -3
  273. package/extensions/greedysearch-dm/src/search/constants.mjs +5 -2
  274. package/package.json +4 -3
  275. package/extensions/dm-fff/package.json +0 -21
  276. package/extensions/dm-fff/src/index.js +0 -691
  277. package/extensions/dm-fff/src/query.js +0 -60
  278. package/extensions/dm-subagents/agents/context-builder.md +0 -46
  279. package/extensions/dm-subagents/agents/planner.md +0 -55
  280. package/extensions/dm-subagents/prompts/parallel-context-build.md +0 -55
  281. package/extensions/dm-subagents/prompts/parallel-handoff-plan.md +0 -61
  282. package/extensions/dm-subagents/src/runs/background/wait.js +0 -206
  283. package/extensions/dm-subagents/src/runs/foreground/chain-clarify.js +0 -1013
  284. package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +0 -981
  285. package/extensions/dm-subagents/src/runs/shared/turn-budget.js +0 -50
@@ -0,0 +1,803 @@
1
+ import { createHash } from "node:crypto";
2
+ import { computeWatchdogRepoChangeSignature, eventIndicatesRepoEdit } from "./change-signature.js";
3
+ import { WatchdogEmissionGuard } from "./emission-guard.js";
4
+ import {
5
+ collectWatchdogLspDiagnostics,
6
+ formatWatchdogLspDiagnosticsBlock,
7
+ WatchdogLspDiagnosticsLedger,
8
+ watchdogWarningFromLspDiagnostics
9
+ } from "./lsp-diagnostics.js";
10
+ import { WatchdogScopeArtifact, isWatchdogAutoFollowPromptEvent } from "./scope.js";
11
+ import { resolveWatchdogConfig } from "./settings.js";
12
+ import { formatWatchdogTurnDelta } from "./turn-delta.js";
13
+ import { normalizeWatchdogWarningDetails } from "./warning-format.js";
14
+ const DEFAULT_REVIEW = () => ({ warnings: [] });
15
+ const MAX_REVIEW_INPUT_CHARS = 24000;
16
+ const REVIEW_DELTA_SEPARATOR = `
17
+
18
+ ---
19
+
20
+ `;
21
+ function errorMessage(error) {
22
+ return error instanceof Error ? error.message : String(error);
23
+ }
24
+ function promptFromBeforeAgentStart(event) {
25
+ if (!event || typeof event !== "object")
26
+ return;
27
+ const input = event;
28
+ if (typeof input.prompt === "string")
29
+ return input.prompt;
30
+ if (typeof input.systemPrompt === "string")
31
+ return input.systemPrompt;
32
+ return;
33
+ }
34
+ function reviewInputSignature(input) {
35
+ return createHash("sha256").update(input).digest("hex");
36
+ }
37
+
38
+ export class MainWatchdogRuntime {
39
+ cwd;
40
+ resolveConfig;
41
+ review;
42
+ reviewConnected;
43
+ reviewDescription;
44
+ displayWarning;
45
+ sendUserMessage;
46
+ reviewChangesOnly;
47
+ lspDiagnostics;
48
+ repoChangeSignature;
49
+ lspLedger = new WatchdogLspDiagnosticsLedger;
50
+ scope = new WatchdogScopeArtifact;
51
+ configResult;
52
+ sessionOverrideEnabled;
53
+ sessionModelOverride;
54
+ status = "idle";
55
+ pendingDeltas = [];
56
+ pendingDeltaChars = 0;
57
+ guard = new WatchdogEmissionGuard;
58
+ guardMaxWarnings = null;
59
+ epoch = 0;
60
+ reviewIdCounter = 0;
61
+ agentEndIdCounter = 0;
62
+ activeAgentEndId;
63
+ activeAgentEndAbortController;
64
+ activeReviewId;
65
+ activeReviewWarning;
66
+ reviewing = false;
67
+ waitingAtAgentEnd = false;
68
+ disposed = false;
69
+ includeUserPromptInNextDelta = false;
70
+ userPrompt;
71
+ waiters = [];
72
+ lastWarning;
73
+ displayedWarningSequence = 0;
74
+ lastError;
75
+ lastReviewInputSignature;
76
+ turnStartChangeSignature;
77
+ lastReviewedChangeSignature;
78
+ currentChangedPaths;
79
+ lastLspSnapshot;
80
+ observedRepoEditThisTurn = false;
81
+ toolResultsThisRun = 0;
82
+ midRunReviewing = false;
83
+ autoFollowQueued = false;
84
+ autoFollowAttempts = 0;
85
+ consecutiveAutoFollowIdentity;
86
+ consecutiveAutoFollowRepeats = 0;
87
+ autoFollowStalemate = false;
88
+ pendingAutoFollowPrompts = [];
89
+ midRunGeneration = 0;
90
+ activeReviewAbortController;
91
+ failedReviews = 0;
92
+ staleReviews = 0;
93
+ constructor(options = {}) {
94
+ this.cwd = options.cwd ?? process.cwd();
95
+ this.resolveConfig = options.resolveConfig ?? resolveWatchdogConfig;
96
+ this.review = options.review ?? DEFAULT_REVIEW;
97
+ this.reviewConnected = Boolean(options.review);
98
+ this.reviewDescription = options.reviewDescription ?? (options.review ? "injected seam" : "not wired");
99
+ this.displayWarning = options.displayWarning;
100
+ this.sendUserMessage = options.sendUserMessage;
101
+ this.reviewChangesOnly = options.reviewChangesOnly === true;
102
+ this.lspDiagnostics = options.lspDiagnostics ?? collectWatchdogLspDiagnostics;
103
+ this.repoChangeSignature = options.repoChangeSignature ?? computeWatchdogRepoChangeSignature;
104
+ this.configResult = this.resolveConfig(this.cwd);
105
+ this.guardMaxWarnings = this.configResult.config.maxWarnings;
106
+ this.guard = new WatchdogEmissionGuard({ maxWarnings: this.guardMaxWarnings });
107
+ this.turnStartChangeSignature = this.currentRepoChangeSignature();
108
+ this.lastReviewedChangeSignature = this.turnStartChangeSignature?.key;
109
+ }
110
+ bindSession(ctx) {
111
+ this.cwd = ctx.cwd;
112
+ this.sessionOverrideEnabled = undefined;
113
+ this.sessionModelOverride = undefined;
114
+ this.refreshConfig(ctx.cwd);
115
+ this.reset("session_start", { clearReviewInputSignature: true, resetChangeSignature: true, clearLspLedger: true, clearScope: true, resetAutoFollow: true });
116
+ }
117
+ refreshConfig(cwd = this.cwd) {
118
+ this.cwd = cwd;
119
+ const wasEnabled = this.isEnabled();
120
+ const session = this.sessionOverrideEnabled === undefined && this.sessionModelOverride === undefined ? undefined : {
121
+ ...this.sessionOverrideEnabled === undefined ? {} : { enabled: this.sessionOverrideEnabled },
122
+ main: {
123
+ ...this.sessionOverrideEnabled === undefined ? {} : { enabled: this.sessionOverrideEnabled },
124
+ ...this.sessionModelOverride ?? {}
125
+ }
126
+ };
127
+ this.configResult = this.resolveConfig(this.cwd, session === undefined ? undefined : { session });
128
+ if (this.configResult.config.maxWarnings !== this.guardMaxWarnings) {
129
+ this.guardMaxWarnings = this.configResult.config.maxWarnings;
130
+ this.guard = new WatchdogEmissionGuard({ maxWarnings: this.guardMaxWarnings });
131
+ }
132
+ if (wasEnabled && !this.isEnabled())
133
+ this.invalidateActiveReview("watchdog disabled");
134
+ return this.configResult;
135
+ }
136
+ setSessionEnabled(enabled, cwd = this.cwd) {
137
+ this.sessionOverrideEnabled = enabled;
138
+ this.reset("session override");
139
+ this.refreshConfig(cwd);
140
+ return this.getSnapshot();
141
+ }
142
+ setSessionModel(patch, cwd = this.cwd) {
143
+ const next = { ...this.sessionModelOverride ?? {} };
144
+ if (patch.model === null)
145
+ delete next.model;
146
+ else if (patch.model !== undefined)
147
+ next.model = patch.model;
148
+ if (patch.thinking === null)
149
+ delete next.thinking;
150
+ else if (patch.thinking !== undefined)
151
+ next.thinking = patch.thinking;
152
+ this.sessionModelOverride = next.model === undefined && next.thinking === undefined ? undefined : next;
153
+ this.reset("session model override");
154
+ this.refreshConfig(cwd);
155
+ return this.getSnapshot();
156
+ }
157
+ clearSessionModel(cwd = this.cwd) {
158
+ this.sessionModelOverride = undefined;
159
+ this.reset("session model override cleared");
160
+ this.refreshConfig(cwd);
161
+ return this.getSnapshot();
162
+ }
163
+ clearSessionOverride(cwd = this.cwd) {
164
+ this.sessionOverrideEnabled = undefined;
165
+ this.sessionModelOverride = undefined;
166
+ this.reset("session override cleared");
167
+ this.refreshConfig(cwd);
168
+ return this.getSnapshot();
169
+ }
170
+ reset(_reason = "reset", options = {}) {
171
+ this.abortActiveAgentEnd();
172
+ this.epoch++;
173
+ this.status = "idle";
174
+ this.clearPendingDeltas();
175
+ this.reviewing = false;
176
+ this.waitingAtAgentEnd = false;
177
+ this.activeReviewId = undefined;
178
+ this.activeReviewWarning = undefined;
179
+ this.includeUserPromptInNextDelta = false;
180
+ this.userPrompt = undefined;
181
+ this.lastError = undefined;
182
+ this.currentChangedPaths = undefined;
183
+ this.observedRepoEditThisTurn = false;
184
+ this.toolResultsThisRun = 0;
185
+ this.midRunReviewing = false;
186
+ this.autoFollowQueued = false;
187
+ if (options.clearLspLedger) {
188
+ this.lspLedger.reset();
189
+ this.lastLspSnapshot = undefined;
190
+ }
191
+ if (options.clearScope) {
192
+ this.scope.reset();
193
+ this.pendingAutoFollowPrompts = [];
194
+ }
195
+ if (options.resetAutoFollow)
196
+ this.resetAutoFollowState();
197
+ if (options.clearReviewInputSignature)
198
+ this.lastReviewInputSignature = undefined;
199
+ if (options.resetChangeSignature)
200
+ this.resetRepoChangeBaseline({ reviewed: true });
201
+ this.guard.reset();
202
+ this.resolveWaiters(true);
203
+ }
204
+ dispose() {
205
+ this.disposed = true;
206
+ this.abortActiveAgentEnd();
207
+ this.epoch++;
208
+ this.status = "idle";
209
+ this.clearPendingDeltas();
210
+ this.reviewing = false;
211
+ this.waitingAtAgentEnd = false;
212
+ this.activeReviewId = undefined;
213
+ this.activeReviewWarning = undefined;
214
+ this.lastReviewInputSignature = undefined;
215
+ this.currentChangedPaths = undefined;
216
+ this.lastLspSnapshot = undefined;
217
+ this.lspLedger.reset();
218
+ this.scope.reset();
219
+ this.observedRepoEditThisTurn = false;
220
+ this.toolResultsThisRun = 0;
221
+ this.midRunReviewing = false;
222
+ this.autoFollowQueued = false;
223
+ this.resolveWaiters(false);
224
+ }
225
+ handleBeforeAgentStart(event, ctx) {
226
+ if (this.disposed)
227
+ return;
228
+ const incomingPrompt = promptFromBeforeAgentStart(event);
229
+ const pendingIndex = incomingPrompt === undefined ? -1 : this.pendingAutoFollowPrompts.indexOf(incomingPrompt);
230
+ const autoFollowPrompt = pendingIndex >= 0 || isWatchdogAutoFollowPromptEvent(event);
231
+ if (pendingIndex >= 0)
232
+ this.pendingAutoFollowPrompts.splice(pendingIndex, 1);
233
+ this.reset("before_agent_start", { resetAutoFollow: !autoFollowPrompt });
234
+ this.refreshConfig(ctx.cwd);
235
+ this.userPrompt = incomingPrompt;
236
+ if (!autoFollowPrompt && this.userPrompt?.trim()) {
237
+ this.includeUserPromptInNextDelta = true;
238
+ this.scope.addPrompt(this.userPrompt);
239
+ } else {
240
+ this.includeUserPromptInNextDelta = false;
241
+ }
242
+ this.resetRepoChangeBaseline();
243
+ }
244
+ handleTurnEnd(event, ctx) {
245
+ if (this.disposed)
246
+ return;
247
+ this.refreshConfig(ctx.cwd);
248
+ if (!this.isEnabled())
249
+ return;
250
+ try {
251
+ this.observedRepoEditThisTurn ||= eventIndicatesRepoEdit(event);
252
+ const delta = formatWatchdogTurnDelta({
253
+ includeUserPrompt: this.includeUserPromptInNextDelta,
254
+ userPrompt: this.userPrompt,
255
+ events: [event]
256
+ });
257
+ this.includeUserPromptInNextDelta = false;
258
+ this.enqueueDelta(delta);
259
+ } catch (error) {
260
+ this.fail(`Failed to format watchdog turn delta: ${errorMessage(error)}`);
261
+ }
262
+ }
263
+ enqueueDelta(delta) {
264
+ if (this.disposed || !delta.trim() || !this.isEnabled())
265
+ return;
266
+ this.appendBoundedDelta(delta);
267
+ if (!this.reviewing && !this.waitingAtAgentEnd && !this.midRunReviewing)
268
+ this.status = "queued";
269
+ }
270
+ handleToolResult(ctx) {
271
+ if (this.disposed)
272
+ return;
273
+ this.refreshConfig(ctx.cwd);
274
+ if (!this.isEnabled())
275
+ return;
276
+ const everyNTools = this.configResult.config.cadence.everyNTools;
277
+ if (everyNTools === null)
278
+ return;
279
+ this.toolResultsThisRun++;
280
+ if (this.toolResultsThisRun % everyNTools !== 0)
281
+ return;
282
+ if (this.reviewing || this.waitingAtAgentEnd || this.midRunReviewing)
283
+ return;
284
+ const delta = this.buildReviewInput(undefined, "");
285
+ if (!delta.trim())
286
+ return;
287
+ this.reviewMidRunDelta(delta);
288
+ }
289
+ async handleAgentEnd(_event, ctx) {
290
+ if (this.disposed)
291
+ return;
292
+ this.refreshConfig(ctx.cwd);
293
+ if (!this.isEnabled())
294
+ return;
295
+ const changeSignature = this.resolveReviewChangeSignature(ctx.cwd);
296
+ if (this.reviewChangesOnly && !changeSignature) {
297
+ this.clearPendingDeltas();
298
+ if (this.status === "queued")
299
+ this.status = "idle";
300
+ this.resolveWaiters(true);
301
+ return;
302
+ }
303
+ if (changeSignature && changeSignature.key === this.lastReviewedChangeSignature) {
304
+ this.clearPendingDeltas();
305
+ this.status = "idle";
306
+ this.resolveWaiters(true);
307
+ return;
308
+ }
309
+ this.cancelMidRunReview();
310
+ this.waitingAtAgentEnd = true;
311
+ const agentEndEpoch = this.epoch;
312
+ const agentEndId = ++this.agentEndIdCounter;
313
+ const lspAbortController = new AbortController;
314
+ this.activeAgentEndId = agentEndId;
315
+ this.activeAgentEndAbortController = lspAbortController;
316
+ let displayedDuringAgentEnd;
317
+ const previousDisplayedSequence = this.displayedWarningSequence;
318
+ try {
319
+ this.guard.startModelUpdate();
320
+ const lspBlock = await this.collectLspDiagnostics(changeSignature, {
321
+ epoch: agentEndEpoch,
322
+ agentEndId,
323
+ signal: lspAbortController.signal
324
+ });
325
+ if (this.activeAgentEndAbortController === lspAbortController)
326
+ this.activeAgentEndAbortController = undefined;
327
+ if (!this.isAgentEndCurrent(agentEndEpoch, agentEndId))
328
+ return;
329
+ const delta = this.buildReviewInput(changeSignature, lspBlock);
330
+ this.clearPendingDeltas();
331
+ if (!delta.trim()) {
332
+ this.waitingAtAgentEnd = false;
333
+ if (this.status === "queued")
334
+ this.status = "idle";
335
+ this.resolveWaiters(true);
336
+ return;
337
+ }
338
+ const signature = reviewInputSignature(delta);
339
+ if (!this.reviewChangesOnly && signature === this.lastReviewInputSignature) {
340
+ this.waitingAtAgentEnd = false;
341
+ this.status = "idle";
342
+ this.resolveWaiters(true);
343
+ return;
344
+ }
345
+ const outcome = await this.reviewDelta(delta, this.configResult.config.agentEndTimeoutMs);
346
+ this.waitingAtAgentEnd = false;
347
+ if (outcome === "timeout") {
348
+ this.staleReviews++;
349
+ this.invalidateActiveReview("agent-end timeout");
350
+ this.status = "stale";
351
+ this.markLastWarningStale();
352
+ this.resolveWaiters(true);
353
+ return;
354
+ }
355
+ if (outcome === "completed" && this.status !== "failed" && this.status !== "stale") {
356
+ this.lastReviewInputSignature = signature;
357
+ if (changeSignature)
358
+ this.lastReviewedChangeSignature = changeSignature.key;
359
+ this.currentChangedPaths = changeSignature?.changedPaths;
360
+ this.status = "idle";
361
+ }
362
+ displayedDuringAgentEnd = this.displayedWarningSequence !== previousDisplayedSequence ? this.lastWarning : undefined;
363
+ this.queueAutoFollowIfNeeded(displayedDuringAgentEnd);
364
+ this.resolveWaiters(true);
365
+ } finally {
366
+ if (this.activeAgentEndAbortController === lspAbortController)
367
+ this.activeAgentEndAbortController = undefined;
368
+ if (this.activeAgentEndId === agentEndId)
369
+ this.activeAgentEndId = undefined;
370
+ }
371
+ }
372
+ recordDisplayedWarning(warning) {
373
+ const details = normalizeWatchdogWarningDetails(warning, { state: "displayed", source: warning.source ?? "main" });
374
+ this.lastWarning = details;
375
+ return details;
376
+ }
377
+ getSnapshot(cwd) {
378
+ if (cwd)
379
+ this.refreshConfig(cwd);
380
+ return {
381
+ status: this.status,
382
+ enabled: this.isEnabled(),
383
+ config: this.configResult.config,
384
+ configOk: this.configResult.ok,
385
+ errors: [...this.configResult.errors],
386
+ sources: [...this.configResult.sources],
387
+ bufferedDeltas: this.pendingDeltas.length,
388
+ epoch: this.epoch,
389
+ ...this.activeReviewId !== undefined ? { activeReviewId: this.activeReviewId } : {},
390
+ ...this.sessionOverrideEnabled !== undefined ? { sessionOverride: this.sessionOverrideEnabled } : {},
391
+ ...this.sessionModelOverride !== undefined ? { sessionModelOverride: { ...this.sessionModelOverride } } : {},
392
+ ...this.lastWarning ? { lastWarning: this.lastWarning } : {},
393
+ ...this.lastError ? { lastError: this.lastError } : {},
394
+ failedReviews: this.failedReviews,
395
+ staleReviews: this.staleReviews,
396
+ reviewConnected: this.reviewConnected,
397
+ reviewDescription: this.reviewDescription,
398
+ autoFollowQueued: this.autoFollowQueued,
399
+ autoFollowAttempts: this.autoFollowAttempts,
400
+ autoFollowStalemate: this.autoFollowStalemate,
401
+ reviewTrigger: this.reviewChangesOnly ? "repo-edits" : "turn-delta",
402
+ ...this.currentChangedPaths?.length ? { changedPaths: [...this.currentChangedPaths] } : {},
403
+ lsp: this.lspSnapshot()
404
+ };
405
+ }
406
+ async waitForIdle(timeoutMs = 1000) {
407
+ return this.waitForSettled(timeoutMs);
408
+ }
409
+ isEnabled() {
410
+ return this.configResult.ok && this.configResult.config.main.enabled;
411
+ }
412
+ abortActiveAgentEnd() {
413
+ this.activeAgentEndAbortController?.abort();
414
+ this.activeAgentEndAbortController = undefined;
415
+ this.activeAgentEndId = undefined;
416
+ }
417
+ isAgentEndCurrent(epoch, agentEndId) {
418
+ return !this.disposed && this.epoch === epoch && this.activeAgentEndId === agentEndId && this.waitingAtAgentEnd && this.isEnabled();
419
+ }
420
+ isCurrent(epoch, reviewId) {
421
+ return !this.disposed && this.epoch === epoch && this.activeReviewId === reviewId;
422
+ }
423
+ warningMeetsThreshold(warning) {
424
+ return this.configResult.config.severityThreshold === "concern" || warning.severity === "blocker";
425
+ }
426
+ acceptWarning(epoch, reviewId, warning) {
427
+ if (!this.isCurrent(epoch, reviewId) || !this.isEnabled() || !this.warningMeetsThreshold(warning))
428
+ return false;
429
+ const decision = this.guard.evaluate(warning);
430
+ if (!decision.accepted)
431
+ return false;
432
+ const details = normalizeWatchdogWarningDetails(warning, {
433
+ state: "candidate",
434
+ source: warning.source ?? "main",
435
+ identity: decision.identity
436
+ });
437
+ this.lastWarning = details;
438
+ this.activeReviewWarning = details;
439
+ return true;
440
+ }
441
+ displayBoundaryWarning(warning) {
442
+ if (!this.isEnabled() || !this.warningMeetsThreshold(warning))
443
+ return false;
444
+ const decision = this.guard.evaluate(warning);
445
+ if (!decision.accepted)
446
+ return false;
447
+ const details = normalizeWatchdogWarningDetails(warning, {
448
+ state: "displayed",
449
+ source: warning.source ?? "main",
450
+ identity: decision.identity,
451
+ displayedAt: new Date().toISOString()
452
+ });
453
+ this.lastWarning = details;
454
+ this.displayedWarningSequence++;
455
+ this.displayWarning?.(details);
456
+ return true;
457
+ }
458
+ invalidateActiveReview(_reason) {
459
+ this.abortActiveAgentEnd();
460
+ this.epoch++;
461
+ this.status = "idle";
462
+ this.clearPendingDeltas();
463
+ this.reviewing = false;
464
+ this.waitingAtAgentEnd = false;
465
+ this.activeReviewId = undefined;
466
+ this.activeReviewWarning = undefined;
467
+ }
468
+ async reviewMidRunDelta(delta) {
469
+ if (this.midRunReviewing || this.reviewing || this.waitingAtAgentEnd || this.disposed)
470
+ return;
471
+ this.midRunReviewing = true;
472
+ const generation = this.midRunGeneration;
473
+ try {
474
+ const outcome = await this.reviewDelta(delta, this.configResult.config.agentEndTimeoutMs, { correction: true });
475
+ if (generation !== this.midRunGeneration)
476
+ return;
477
+ if (outcome === "timeout") {
478
+ this.staleReviews++;
479
+ this.status = "stale";
480
+ this.markLastWarningStale();
481
+ }
482
+ } finally {
483
+ if (generation === this.midRunGeneration) {
484
+ this.midRunReviewing = false;
485
+ if (this.status === "reviewing")
486
+ this.status = this.pendingDeltas.length ? "queued" : "idle";
487
+ this.resolveWaiters(this.isSettled());
488
+ }
489
+ }
490
+ }
491
+ cancelMidRunReview() {
492
+ if (!this.midRunReviewing)
493
+ return;
494
+ this.midRunGeneration++;
495
+ this.activeReviewAbortController?.abort();
496
+ this.activeReviewAbortController = undefined;
497
+ this.staleReviews++;
498
+ this.reviewing = false;
499
+ this.midRunReviewing = false;
500
+ this.activeReviewId = undefined;
501
+ this.activeReviewWarning = undefined;
502
+ }
503
+ async reviewDelta(delta, timeoutMs, options = {}) {
504
+ if (this.reviewing || this.disposed)
505
+ return "stale";
506
+ this.reviewing = true;
507
+ const reviewEpoch = this.epoch;
508
+ const reviewId = ++this.reviewIdCounter;
509
+ this.activeReviewId = reviewId;
510
+ this.activeReviewWarning = undefined;
511
+ this.status = "reviewing";
512
+ let timeout;
513
+ const abortController = new AbortController;
514
+ this.activeReviewAbortController = abortController;
515
+ const reviewPromise = Promise.resolve().then(() => this.review({
516
+ delta,
517
+ epoch: reviewEpoch,
518
+ reviewId,
519
+ config: this.configResult.config,
520
+ hasScope: this.scopeBlock().trim().length > 0,
521
+ signal: abortController.signal,
522
+ emitWarning: (warning) => this.acceptWarning(reviewEpoch, reviewId, warning)
523
+ }));
524
+ try {
525
+ const result = await Promise.race([
526
+ reviewPromise,
527
+ new Promise((resolve) => {
528
+ timeout = setTimeout(() => resolve("timeout"), timeoutMs);
529
+ })
530
+ ]);
531
+ if (result === "timeout") {
532
+ abortController.abort();
533
+ return "timeout";
534
+ }
535
+ if (!this.isCurrent(reviewEpoch, reviewId))
536
+ return "stale";
537
+ if (!result)
538
+ return "stale";
539
+ for (const warning of result.warnings ?? [])
540
+ this.acceptWarning(reviewEpoch, reviewId, warning);
541
+ if (result.stopReason && result.stopReason !== "stop") {
542
+ this.fail(`Watchdog review ended with stop reason '${result.stopReason}'.`);
543
+ return "completed";
544
+ }
545
+ this.displayAcceptedReviewWarning(options.correction);
546
+ return "completed";
547
+ } catch (error) {
548
+ if (this.isCurrent(reviewEpoch, reviewId)) {
549
+ this.fail(`Watchdog review failed: ${errorMessage(error)}`);
550
+ return "completed";
551
+ }
552
+ return "stale";
553
+ } finally {
554
+ if (timeout)
555
+ clearTimeout(timeout);
556
+ if (this.activeReviewAbortController === abortController)
557
+ this.activeReviewAbortController = undefined;
558
+ if (this.epoch === reviewEpoch && this.activeReviewId === reviewId) {
559
+ this.reviewing = false;
560
+ this.activeReviewId = undefined;
561
+ this.activeReviewWarning = undefined;
562
+ }
563
+ this.resolveWaiters(this.isSettled());
564
+ }
565
+ }
566
+ displayAcceptedReviewWarning(correction = false) {
567
+ if (!this.activeReviewWarning)
568
+ return;
569
+ const details = {
570
+ ...this.activeReviewWarning,
571
+ state: "displayed",
572
+ displayedAt: new Date().toISOString()
573
+ };
574
+ this.lastWarning = details;
575
+ this.displayedWarningSequence++;
576
+ this.displayWarning?.(details, correction ? { deliverAs: "steer" } : undefined);
577
+ }
578
+ resetAutoFollowState() {
579
+ this.autoFollowQueued = false;
580
+ this.autoFollowAttempts = 0;
581
+ this.consecutiveAutoFollowIdentity = undefined;
582
+ this.consecutiveAutoFollowRepeats = 0;
583
+ this.autoFollowStalemate = false;
584
+ }
585
+ queueAutoFollowIfNeeded(warning) {
586
+ if (!warning || warning.severity !== "blocker" || warning.stale || !this.configResult.config.autoFollow.blockers || !this.isEnabled())
587
+ return;
588
+ const identity = warning.identity ?? reviewInputSignature([warning.severity, warning.summary, warning.evidence].join(`
589
+ `));
590
+ if (this.consecutiveAutoFollowIdentity === identity)
591
+ this.consecutiveAutoFollowRepeats++;
592
+ else {
593
+ this.consecutiveAutoFollowIdentity = identity;
594
+ this.consecutiveAutoFollowRepeats = 1;
595
+ }
596
+ if (this.consecutiveAutoFollowRepeats >= this.configResult.config.autoFollow.stalemateRepeats) {
597
+ this.autoFollowStalemate = true;
598
+ this.lastWarning = { ...warning, state: "stalemate", stalemateRepeats: this.consecutiveAutoFollowRepeats };
599
+ return;
600
+ }
601
+ const maxAttempts = this.configResult.config.autoFollow.maxAttempts;
602
+ if (maxAttempts !== null && this.autoFollowAttempts >= maxAttempts)
603
+ return;
604
+ if (!this.sendUserMessage)
605
+ return;
606
+ this.autoFollowAttempts++;
607
+ this.autoFollowQueued = true;
608
+ const prompt = [
609
+ "Watchdog auto-follow: address this blocker before continuing.",
610
+ `Summary: ${warning.summary}`,
611
+ `Evidence: ${warning.evidence}`,
612
+ `Recommended action: ${warning.recommendedAction}`
613
+ ].join(`
614
+ `);
615
+ this.pendingAutoFollowPrompts.push(prompt);
616
+ if (this.pendingAutoFollowPrompts.length > 8)
617
+ this.pendingAutoFollowPrompts.shift();
618
+ Promise.resolve(this.sendUserMessage(prompt)).catch((error) => {
619
+ this.autoFollowQueued = false;
620
+ const index = this.pendingAutoFollowPrompts.indexOf(prompt);
621
+ if (index >= 0)
622
+ this.pendingAutoFollowPrompts.splice(index, 1);
623
+ this.lastError = `Watchdog auto-follow failed: ${errorMessage(error)}`;
624
+ });
625
+ }
626
+ currentRepoChangeSignature(cwd = this.cwd) {
627
+ return this.reviewChangesOnly && this.isEnabled() ? this.repoChangeSignature(cwd) : undefined;
628
+ }
629
+ resetRepoChangeBaseline(options = {}) {
630
+ this.turnStartChangeSignature = this.currentRepoChangeSignature(options.cwd ?? this.cwd);
631
+ if (options.reviewed)
632
+ this.lastReviewedChangeSignature = this.turnStartChangeSignature?.key;
633
+ else
634
+ this.lastReviewedChangeSignature ??= this.turnStartChangeSignature?.key;
635
+ this.currentChangedPaths = this.turnStartChangeSignature?.changedPaths;
636
+ this.observedRepoEditThisTurn = false;
637
+ }
638
+ resolveReviewChangeSignature(cwd = this.cwd) {
639
+ if (!this.reviewChangesOnly)
640
+ return;
641
+ const current = this.currentRepoChangeSignature(cwd);
642
+ if (current) {
643
+ this.currentChangedPaths = current.changedPaths;
644
+ if (current.key === this.turnStartChangeSignature?.key)
645
+ return;
646
+ if (current.changedPaths.length === 0)
647
+ return;
648
+ return current;
649
+ }
650
+ return this.observedRepoEditThisTurn ? { root: cwd, key: `observed-edit:${this.epoch}:${this.reviewIdCounter}:${this.pendingDeltaChars}`, changedPaths: [] } : undefined;
651
+ }
652
+ async collectLspDiagnostics(changeSignature, current) {
653
+ const config = this.configResult.config.lsp;
654
+ if (!config.enabled || !changeSignature?.changedPaths.length) {
655
+ this.lastLspSnapshot = {
656
+ enabled: config.enabled,
657
+ status: config.enabled ? "skipped" : "disabled",
658
+ checkedPaths: [],
659
+ skippedPaths: [],
660
+ diagnostics: [],
661
+ diagnosticCount: 0,
662
+ freshDiagnosticCount: 0,
663
+ updatedAt: new Date().toISOString()
664
+ };
665
+ return "";
666
+ }
667
+ try {
668
+ const raw = await this.lspDiagnostics({
669
+ cwd: this.cwd,
670
+ root: changeSignature.root,
671
+ changedPaths: changeSignature.changedPaths,
672
+ config,
673
+ signal: current.signal
674
+ });
675
+ if (!this.isAgentEndCurrent(current.epoch, current.agentEndId))
676
+ return "";
677
+ const diagnosticCount = raw.diagnostics.length;
678
+ const fresh = this.lspLedger.reduce(raw);
679
+ this.lastLspSnapshot = {
680
+ ...fresh,
681
+ enabled: true,
682
+ diagnosticCount,
683
+ freshDiagnosticCount: fresh.diagnostics.length,
684
+ updatedAt: new Date().toISOString()
685
+ };
686
+ const warning = watchdogWarningFromLspDiagnostics(fresh);
687
+ if (warning)
688
+ this.displayBoundaryWarning(warning);
689
+ return formatWatchdogLspDiagnosticsBlock(fresh);
690
+ } catch (error) {
691
+ if (!this.isAgentEndCurrent(current.epoch, current.agentEndId))
692
+ return "";
693
+ this.lastLspSnapshot = {
694
+ enabled: true,
695
+ status: "failed",
696
+ checkedPaths: [],
697
+ skippedPaths: changeSignature.changedPaths,
698
+ diagnostics: [],
699
+ diagnosticCount: 0,
700
+ freshDiagnosticCount: 0,
701
+ message: `LSP diagnostics failed: ${errorMessage(error)}`,
702
+ updatedAt: new Date().toISOString()
703
+ };
704
+ return "";
705
+ }
706
+ }
707
+ lspSnapshot() {
708
+ if (this.lastLspSnapshot)
709
+ return {
710
+ ...this.lastLspSnapshot,
711
+ checkedPaths: [...this.lastLspSnapshot.checkedPaths],
712
+ skippedPaths: [...this.lastLspSnapshot.skippedPaths],
713
+ diagnostics: [...this.lastLspSnapshot.diagnostics]
714
+ };
715
+ const enabled = this.isEnabled() && this.configResult.config.lsp.enabled;
716
+ return {
717
+ enabled,
718
+ status: enabled ? "skipped" : "disabled",
719
+ checkedPaths: [],
720
+ skippedPaths: [],
721
+ diagnostics: [],
722
+ diagnosticCount: 0,
723
+ freshDiagnosticCount: 0
724
+ };
725
+ }
726
+ appendBoundedDelta(delta) {
727
+ let entry = delta.trim();
728
+ if (!entry)
729
+ return;
730
+ if (entry.length > MAX_REVIEW_INPUT_CHARS)
731
+ entry = entry.slice(-MAX_REVIEW_INPUT_CHARS);
732
+ this.pendingDeltas.push(entry);
733
+ this.pendingDeltaChars += entry.length;
734
+ while (this.pendingDeltas.length > 1 && this.pendingDeltaChars + (this.pendingDeltas.length - 1) * REVIEW_DELTA_SEPARATOR.length > MAX_REVIEW_INPUT_CHARS) {
735
+ const removed = this.pendingDeltas.shift();
736
+ if (removed)
737
+ this.pendingDeltaChars -= removed.length;
738
+ }
739
+ }
740
+ buildReviewInput(changeSignature, lspBlock = "") {
741
+ const input = this.pendingDeltas.join(REVIEW_DELTA_SEPARATOR);
742
+ const scopeBlock = this.scopeBlock();
743
+ const changes = changeSignature?.changedPaths.length ? ["Changed repo paths:", ...changeSignature.changedPaths.slice(0, 200).map((file) => `- ${file}`)].join(`
744
+ `) : "";
745
+ const contextPieces = [scopeBlock, changes, lspBlock].filter(Boolean);
746
+ if (!contextPieces.length)
747
+ return input.length > MAX_REVIEW_INPUT_CHARS ? input.slice(-MAX_REVIEW_INPUT_CHARS) : input;
748
+ const maxContextLength = Math.floor(MAX_REVIEW_INPUT_CHARS / 2);
749
+ const maxPieceLength = Math.max(1000, Math.floor(maxContextLength / contextPieces.length));
750
+ const boundedContext = contextPieces.map((piece) => piece.length > maxPieceLength ? `${piece.slice(0, maxPieceLength - 6)}
751
+ - ...` : piece).join(REVIEW_DELTA_SEPARATOR);
752
+ const separatorLength = input ? REVIEW_DELTA_SEPARATOR.length : 0;
753
+ const inputBudget = MAX_REVIEW_INPUT_CHARS - boundedContext.length - separatorLength;
754
+ const boundedInput = inputBudget <= 0 ? "" : input.length > inputBudget ? input.slice(-inputBudget) : input;
755
+ return [boundedContext, boundedInput].filter(Boolean).join(REVIEW_DELTA_SEPARATOR);
756
+ }
757
+ scopeBlock() {
758
+ return this.configResult.config.scope.enabled ? this.scope.render() : "";
759
+ }
760
+ clearPendingDeltas() {
761
+ this.pendingDeltas = [];
762
+ this.pendingDeltaChars = 0;
763
+ }
764
+ fail(message) {
765
+ this.failedReviews++;
766
+ this.lastError = message;
767
+ this.status = "failed";
768
+ this.clearPendingDeltas();
769
+ this.resolveWaiters(true);
770
+ }
771
+ markLastWarningStale() {
772
+ if (!this.lastWarning || this.lastWarning.state === "displayed")
773
+ return;
774
+ this.lastWarning = { ...this.lastWarning, stale: true, state: "stale" };
775
+ }
776
+ isSettled() {
777
+ return !this.reviewing && this.pendingDeltas.length === 0;
778
+ }
779
+ waitForSettled(timeoutMs) {
780
+ if (this.isSettled())
781
+ return Promise.resolve(true);
782
+ return new Promise((resolve) => {
783
+ const waiter = {
784
+ resolve,
785
+ timer: setTimeout(() => {
786
+ this.waiters = this.waiters.filter((entry) => entry !== waiter);
787
+ resolve(false);
788
+ }, timeoutMs)
789
+ };
790
+ this.waiters.push(waiter);
791
+ });
792
+ }
793
+ resolveWaiters(settled) {
794
+ if (!settled && !this.disposed)
795
+ return;
796
+ const waiters = this.waiters;
797
+ this.waiters = [];
798
+ for (const waiter of waiters) {
799
+ clearTimeout(waiter.timer);
800
+ waiter.resolve(settled);
801
+ }
802
+ }
803
+ }