@chankov/agent-fleet 0.0.2 → 0.0.4

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 (362) hide show
  1. package/.claude/commands/doctor-agent-fleet.md +1 -1
  2. package/.claude/commands/setup-agent-fleet.md +5 -5
  3. package/.opencode/commands/af-doctor-agent-fleet.md +2 -0
  4. package/.opencode/commands/af-setup-agent-fleet.md +1 -1
  5. package/.pi/agents/peers.yaml +4 -0
  6. package/.pi/agents/teams.yaml +2 -2
  7. package/.pi/harnesses/agent-hub/README.md +254 -18
  8. package/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  9. package/.pi/harnesses/agent-hub/delegate.ts +32 -9
  10. package/.pi/harnesses/agent-hub/drift-watchdog.js +165 -0
  11. package/.pi/harnesses/agent-hub/footer.ts +29 -0
  12. package/.pi/harnesses/agent-hub/helpers.ts +49 -0
  13. package/.pi/harnesses/agent-hub/index.ts +1269 -322
  14. package/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  15. package/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  16. package/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  17. package/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  18. package/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  19. package/.pi/harnesses/agent-hub/monitor-session-bridge.ts +11 -0
  20. package/.pi/harnesses/agent-hub/package.json +5 -4
  21. package/.pi/harnesses/agent-hub/research-retention.js +34 -0
  22. package/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  23. package/.pi/harnesses/agent-hub/run-budget.js +155 -0
  24. package/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  25. package/.pi/harnesses/agent-hub/spawn.ts +161 -94
  26. package/.pi/harnesses/agent-hub/version.ts +18 -0
  27. package/.pi/harnesses/ask-user-remote/README.md +2 -0
  28. package/.pi/harnesses/coms/README.md +21 -0
  29. package/.pi/harnesses/coms/index.ts +2 -0
  30. package/.pi/harnesses/coms/package.json +5 -4
  31. package/.pi/harnesses/coms/version.ts +18 -0
  32. package/.pi/harnesses/damage-control-continue/README.md +32 -31
  33. package/.pi/harnesses/damage-control-continue/index.ts +23 -9
  34. package/.pi/harnesses/damage-control-continue/package.json +5 -4
  35. package/.pi/harnesses/damage-control-continue/version.ts +18 -0
  36. package/.pi/harnesses/{damage-control/shared.ts → lib/damage-control-shared.ts} +20 -6
  37. package/.pi/prompts/doctor-agent-fleet.md +1 -1
  38. package/.pi/prompts/setup-agent-fleet.md +5 -5
  39. package/.versions/0.0.4/.claude/commands/build.md +44 -0
  40. package/.versions/0.0.4/.claude/commands/code-simplify.md +22 -0
  41. package/.versions/0.0.4/.claude/commands/design-agent.md +14 -0
  42. package/.versions/0.0.4/.claude/commands/doctor-agent-fleet.md +17 -0
  43. package/.versions/0.0.4/.claude/commands/orchestrate.md +112 -0
  44. package/.versions/0.0.4/.claude/commands/plan.md +16 -0
  45. package/.versions/0.0.4/.claude/commands/prime.md +22 -0
  46. package/.versions/0.0.4/.claude/commands/review.md +16 -0
  47. package/.versions/0.0.4/.claude/commands/setup-agent-fleet.md +25 -0
  48. package/.versions/0.0.4/.claude/commands/ship.md +72 -0
  49. package/.versions/0.0.4/.claude/commands/spec.md +15 -0
  50. package/.versions/0.0.4/.claude/commands/test.md +19 -0
  51. package/.versions/0.0.4/.claude/commands/webperf.md +32 -0
  52. package/.versions/0.0.4/.claude/orchestrate-teams.yaml +24 -0
  53. package/.versions/0.0.4/.opencode/commands/af-build.md +17 -0
  54. package/.versions/0.0.4/.opencode/commands/af-code-simplify.md +16 -0
  55. package/.versions/0.0.4/.opencode/commands/af-compound.md +16 -0
  56. package/.versions/0.0.4/.opencode/commands/af-design-agent.md +15 -0
  57. package/.versions/0.0.4/.opencode/commands/af-doctor-agent-fleet.md +17 -0
  58. package/.versions/0.0.4/.opencode/commands/af-orchestrate.md +112 -0
  59. package/.versions/0.0.4/.opencode/commands/af-plan.md +16 -0
  60. package/.versions/0.0.4/.opencode/commands/af-prime.md +22 -0
  61. package/.versions/0.0.4/.opencode/commands/af-review.md +15 -0
  62. package/.versions/0.0.4/.opencode/commands/af-setup-agent-fleet.md +15 -0
  63. package/.versions/0.0.4/.opencode/commands/af-ship.md +16 -0
  64. package/.versions/0.0.4/.opencode/commands/af-spec.md +16 -0
  65. package/.versions/0.0.4/.opencode/commands/af-test.md +21 -0
  66. package/.versions/0.0.4/.opencode/commands/af-webperf.md +32 -0
  67. package/.versions/0.0.4/.opencode/orchestrate-teams.yaml +24 -0
  68. package/.versions/0.0.4/.pi/agents/dispatch-policy.yaml +32 -0
  69. package/.versions/0.0.4/.pi/agents/model-profiles.yaml +20 -0
  70. package/.versions/0.0.4/.pi/agents/peers.yaml +146 -0
  71. package/.versions/0.0.4/.pi/agents/teams.yaml +39 -0
  72. package/.versions/0.0.4/.pi/damage-control-rules.yaml +297 -0
  73. package/.versions/0.0.4/.pi/extensions/agent-fleet-update-check/README.md +58 -0
  74. package/.versions/0.0.4/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  75. package/{.pi/harnesses/damage-control → .versions/0.0.4/.pi/extensions/agent-fleet-update-check}/package.json +1 -1
  76. package/.versions/0.0.4/.pi/extensions/btw/README.md +118 -0
  77. package/.versions/0.0.4/.pi/extensions/btw/index.ts +917 -0
  78. package/.versions/0.0.4/.pi/extensions/btw/package.json +6 -0
  79. package/.versions/0.0.4/.pi/extensions/btw/state.js +179 -0
  80. package/.versions/0.0.4/.pi/extensions/chrome-devtools-mcp/README.md +58 -0
  81. package/.versions/0.0.4/.pi/extensions/chrome-devtools-mcp/index.ts +92 -0
  82. package/.versions/0.0.4/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  83. package/.versions/0.0.4/.pi/extensions/compact-and-continue/README.md +42 -0
  84. package/.versions/0.0.4/.pi/extensions/compact-and-continue/index.ts +120 -0
  85. package/.versions/0.0.4/.pi/extensions/compact-and-continue/package.json +6 -0
  86. package/.versions/0.0.4/.pi/extensions/mcp-bridge/README.md +46 -0
  87. package/.versions/0.0.4/.pi/extensions/mcp-bridge/index.ts +206 -0
  88. package/.versions/0.0.4/.pi/extensions/mcp-bridge/package.json +6 -0
  89. package/.versions/0.0.4/.pi/extensions/package-lock.json +1143 -0
  90. package/.versions/0.0.4/.pi/extensions/package.json +9 -0
  91. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/README.md +201 -0
  92. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/config.ts +198 -0
  93. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  94. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/index.ts +248 -0
  95. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/package.json +6 -0
  96. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  97. package/.versions/0.0.4/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  98. package/.versions/0.0.4/.pi/harnesses/agent-hub/README.md +798 -0
  99. package/.versions/0.0.4/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  100. package/.versions/0.0.4/.pi/harnesses/agent-hub/artifacts.js +92 -0
  101. package/.versions/0.0.4/.pi/harnesses/agent-hub/backend-policy.js +153 -0
  102. package/.versions/0.0.4/.pi/harnesses/agent-hub/delegate.ts +386 -0
  103. package/.versions/0.0.4/.pi/harnesses/agent-hub/drift-watchdog.js +165 -0
  104. package/.versions/0.0.4/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  105. package/.versions/0.0.4/.pi/harnesses/agent-hub/footer.ts +29 -0
  106. package/.versions/0.0.4/.pi/harnesses/agent-hub/helpers.ts +214 -0
  107. package/.versions/0.0.4/.pi/harnesses/agent-hub/index.ts +8045 -0
  108. package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  109. package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  110. package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  111. package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  112. package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  113. package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-session-bridge.ts +11 -0
  114. package/.versions/0.0.4/.pi/harnesses/agent-hub/package.json +7 -0
  115. package/.versions/0.0.4/.pi/harnesses/agent-hub/research-retention.js +34 -0
  116. package/.versions/0.0.4/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  117. package/.versions/0.0.4/.pi/harnesses/agent-hub/return-contract.js +215 -0
  118. package/.versions/0.0.4/.pi/harnesses/agent-hub/run-budget.js +155 -0
  119. package/.versions/0.0.4/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  120. package/.versions/0.0.4/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  121. package/.versions/0.0.4/.pi/harnesses/agent-hub/spawn.ts +246 -0
  122. package/.versions/0.0.4/.pi/harnesses/agent-hub/version.ts +18 -0
  123. package/.versions/0.0.4/.pi/harnesses/ask-user-remote/README.md +18 -0
  124. package/.versions/0.0.4/.pi/harnesses/ask-user-remote/index.ts +293 -0
  125. package/.versions/0.0.4/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  126. package/.versions/0.0.4/.pi/harnesses/coms/README.md +92 -0
  127. package/.versions/0.0.4/.pi/harnesses/coms/index.ts +1745 -0
  128. package/.versions/0.0.4/.pi/harnesses/coms/package.json +7 -0
  129. package/.versions/0.0.4/.pi/harnesses/coms/version.ts +18 -0
  130. package/.versions/0.0.4/.pi/harnesses/damage-control-continue/README.md +117 -0
  131. package/.versions/0.0.4/.pi/harnesses/damage-control-continue/index.ts +536 -0
  132. package/.versions/0.0.4/.pi/harnesses/damage-control-continue/package.json +7 -0
  133. package/.versions/0.0.4/.pi/harnesses/damage-control-continue/version.ts +18 -0
  134. package/.versions/0.0.4/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  135. package/.versions/0.0.4/.pi/harnesses/lib/herdr-client.ts +458 -0
  136. package/.versions/0.0.4/.pi/harnesses/lib/herdr-presence.ts +288 -0
  137. package/.versions/0.0.4/.pi/harnesses/package-lock.json +35 -0
  138. package/.versions/0.0.4/.pi/harnesses/package.json +9 -0
  139. package/.versions/0.0.4/.pi/prompts/build.md +24 -0
  140. package/.versions/0.0.4/.pi/prompts/code-simplify.md +22 -0
  141. package/.versions/0.0.4/.pi/prompts/doctor-agent-fleet.md +15 -0
  142. package/.versions/0.0.4/.pi/prompts/plan.md +16 -0
  143. package/.versions/0.0.4/.pi/prompts/review.md +16 -0
  144. package/.versions/0.0.4/.pi/prompts/setup-agent-fleet.md +27 -0
  145. package/.versions/0.0.4/.pi/prompts/ship.md +17 -0
  146. package/.versions/0.0.4/.pi/prompts/spec.md +15 -0
  147. package/.versions/0.0.4/.pi/prompts/test.md +19 -0
  148. package/.versions/0.0.4/.pi/skills/bowser/SKILL.md +145 -0
  149. package/.versions/0.0.4/.version +1 -0
  150. package/.versions/0.0.4/agents/architect.md +23 -0
  151. package/.versions/0.0.4/agents/bowser.md +26 -0
  152. package/.versions/0.0.4/agents/builder.md +53 -0
  153. package/.versions/0.0.4/agents/code-reviewer.md +205 -0
  154. package/.versions/0.0.4/agents/deep-researcher.md +31 -0
  155. package/.versions/0.0.4/agents/documenter.md +18 -0
  156. package/.versions/0.0.4/agents/orchestrator.md +54 -0
  157. package/.versions/0.0.4/agents/plan-reviewer.md +60 -0
  158. package/.versions/0.0.4/agents/planner.md +69 -0
  159. package/.versions/0.0.4/agents/releaser.md +24 -0
  160. package/.versions/0.0.4/agents/researcher.md +28 -0
  161. package/.versions/0.0.4/agents/security-auditor.md +166 -0
  162. package/.versions/0.0.4/agents/test-engineer.md +151 -0
  163. package/.versions/0.0.4/agents/web-debugger.md +42 -0
  164. package/.versions/0.0.4/agents/web-performance-auditor.md +192 -0
  165. package/.versions/0.0.4/codex/CONDUCTOR.md +148 -0
  166. package/.versions/0.0.4/docs/ARCHITECTURE.md +210 -0
  167. package/.versions/0.0.4/docs/agent-fleet-setup.md +366 -0
  168. package/.versions/0.0.4/docs/claude-code-coms-bridge.md +103 -0
  169. package/.versions/0.0.4/docs/codex-remote-conductor.md +170 -0
  170. package/.versions/0.0.4/docs/coms-hermes-bridge.md +121 -0
  171. package/.versions/0.0.4/docs/getting-started.md +183 -0
  172. package/.versions/0.0.4/docs/npm-install.md +337 -0
  173. package/.versions/0.0.4/docs/opencode-setup.md +248 -0
  174. package/.versions/0.0.4/docs/pi-extensions.md +288 -0
  175. package/.versions/0.0.4/docs/pi-setup.md +463 -0
  176. package/.versions/0.0.4/docs/skill-anatomy.md +150 -0
  177. package/.versions/0.0.4/hermes/README.md +228 -0
  178. package/.versions/0.0.4/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  179. package/.versions/0.0.4/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  180. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-cap.test.py +15 -0
  181. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-discovery.test.py +19 -0
  182. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-envelope.test.py +13 -0
  183. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-forged-owner.test.py +11 -0
  184. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-lease-list.test.py +9 -0
  185. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-multihub.test.py +17 -0
  186. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-output.test.py +34 -0
  187. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +151 -0
  188. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter.test.py +39 -0
  189. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  190. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/plugin-api-validation.test.py +12 -0
  191. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  192. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/review-live-wiring.red.test.py +22 -0
  193. package/.versions/0.0.4/hermes/skills/hub-conductor/SKILL.md +84 -0
  194. package/.versions/0.0.4/hermes/skills/hub-liaison/SKILL.md +84 -0
  195. package/.versions/0.0.4/hooks/SIMPLIFY-IGNORE.md +90 -0
  196. package/.versions/0.0.4/hooks/coms-stop-hook.mjs +73 -0
  197. package/.versions/0.0.4/hooks/hooks.json +14 -0
  198. package/.versions/0.0.4/hooks/session-start.sh +74 -0
  199. package/.versions/0.0.4/hooks/simplify-ignore.sh +302 -0
  200. package/.versions/0.0.4/justfile +256 -0
  201. package/.versions/0.0.4/references/accessibility-checklist.md +160 -0
  202. package/.versions/0.0.4/references/definition-of-done.md +67 -0
  203. package/.versions/0.0.4/references/fleet-coordination-patterns.md +151 -0
  204. package/.versions/0.0.4/references/observability-checklist.md +91 -0
  205. package/.versions/0.0.4/references/orchestration-patterns.md +370 -0
  206. package/.versions/0.0.4/references/performance-checklist.md +153 -0
  207. package/.versions/0.0.4/references/prompting-patterns.md +380 -0
  208. package/.versions/0.0.4/references/security-checklist.md +179 -0
  209. package/.versions/0.0.4/references/testing-patterns.md +236 -0
  210. package/.versions/0.0.4/scripts/codex-conductor.ts +41 -0
  211. package/.versions/0.0.4/scripts/codex-remote-control.ts +167 -0
  212. package/.versions/0.0.4/scripts/coms-claude-bridge.ts +286 -0
  213. package/.versions/0.0.4/scripts/coms-cli.ts +484 -0
  214. package/.versions/0.0.4/scripts/coms-hermes-bridge.ts +403 -0
  215. package/.versions/0.0.4/scripts/hermes-monitor-capability-runner.ts +25 -0
  216. package/.versions/0.0.4/scripts/hermes-monitor-scenario.ts +7 -0
  217. package/.versions/0.0.4/scripts/lib/claude-bridge-core.ts +100 -0
  218. package/.versions/0.0.4/scripts/lib/codex-conductor.ts +88 -0
  219. package/.versions/0.0.4/scripts/lib/codex-remote-control.ts +480 -0
  220. package/.versions/0.0.4/scripts/lib/coms-envelope.ts +539 -0
  221. package/.versions/0.0.4/scripts/lib/fake-herdr-server.ts +88 -0
  222. package/.versions/0.0.4/scripts/lib/herdr-layout.ts +263 -0
  223. package/.versions/0.0.4/scripts/lib/hermes-bridge-core.ts +238 -0
  224. package/.versions/0.0.4/scripts/lib/hermes-monitor-herdr.ts +28 -0
  225. package/.versions/0.0.4/scripts/lib/hermes-monitor-model.ts +9 -0
  226. package/.versions/0.0.4/scripts/lib/hermes-monitor-registry.ts +6 -0
  227. package/.versions/0.0.4/scripts/lib/hermes-monitor-socket.ts +118 -0
  228. package/.versions/0.0.4/scripts/lib/hermes-monitor-store.ts +31 -0
  229. package/.versions/0.0.4/scripts/lib/persona-banner.ts +62 -0
  230. package/.versions/0.0.4/scripts/lib/spawn-stagger.ts +101 -0
  231. package/.versions/0.0.4/scripts/lib/team-project.ts +184 -0
  232. package/.versions/0.0.4/scripts/lib/team-snapshot.ts +147 -0
  233. package/.versions/0.0.4/scripts/peer-banner.ts +40 -0
  234. package/.versions/0.0.4/scripts/team-snapshot.ts +238 -0
  235. package/.versions/0.0.4/scripts/team-up.ts +333 -0
  236. package/.versions/0.0.4/skills/_internal/grilling.md +11 -0
  237. package/.versions/0.0.4/skills/browser-testing-with-devtools/SKILL.md +352 -0
  238. package/.versions/0.0.4/skills/code-review-and-quality/SKILL.md +381 -0
  239. package/.versions/0.0.4/skills/compound-learning/SKILL.md +137 -0
  240. package/.versions/0.0.4/skills/context-engineering/SKILL.md +291 -0
  241. package/.versions/0.0.4/skills/deprecation-and-migration/SKILL.md +206 -0
  242. package/.versions/0.0.4/skills/designing-agents/SKILL.md +394 -0
  243. package/.versions/0.0.4/skills/designing-agents/pi-harness-authoring.md +222 -0
  244. package/.versions/0.0.4/skills/frontend-ui-engineering/SKILL.md +328 -0
  245. package/.versions/0.0.4/skills/git-workflow-and-versioning/SKILL.md +316 -0
  246. package/.versions/0.0.4/skills/guided-workspace-setup/SKILL.md +535 -0
  247. package/.versions/0.0.4/skills/guided-workspace-setup/companion-manifest.json +33 -0
  248. package/.versions/0.0.4/skills/idea-refine/SKILL.md +182 -0
  249. package/.versions/0.0.4/skills/idea-refine/examples.md +238 -0
  250. package/.versions/0.0.4/skills/idea-refine/frameworks.md +99 -0
  251. package/.versions/0.0.4/skills/idea-refine/refinement-criteria.md +113 -0
  252. package/.versions/0.0.4/skills/idea-refine/scripts/idea-refine.sh +15 -0
  253. package/.versions/0.0.4/skills/incremental-implementation/SKILL.md +287 -0
  254. package/.versions/0.0.4/skills/interview-me/SKILL.md +226 -0
  255. package/.versions/0.0.4/skills/orchestration-verification/SKILL.md +181 -0
  256. package/.versions/0.0.4/skills/peer-coms/SKILL.md +90 -0
  257. package/.versions/0.0.4/skills/performance-optimization/SKILL.md +350 -0
  258. package/.versions/0.0.4/skills/planning-and-task-breakdown/SKILL.md +236 -0
  259. package/.versions/0.0.4/skills/security-and-hardening/SKILL.md +461 -0
  260. package/.versions/0.0.4/skills/spec-driven-development/SKILL.md +245 -0
  261. package/.versions/0.0.4/skills/using-agent-skills/SKILL.md +199 -0
  262. package/.versions/0.0.4/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  263. package/.versions/0.0.4/vendor/agent-skills-upstream/LICENSE +21 -0
  264. package/.versions/0.0.4/vendor/agent-skills-upstream/README.md +11 -0
  265. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  266. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  267. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  268. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  269. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  270. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  271. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  272. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  273. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  274. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  275. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  276. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  277. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  278. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  279. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  280. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  281. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  282. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  283. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  284. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  285. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  286. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  287. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  288. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  289. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  290. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  291. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  292. package/.versions/0.0.4/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  293. package/CHANGELOG.md +53 -0
  294. package/README.md +103 -541
  295. package/agents/architect.md +1 -1
  296. package/agents/builder.md +1 -1
  297. package/agents/code-reviewer.md +1 -1
  298. package/agents/deep-researcher.md +3 -3
  299. package/agents/orchestrator.md +20 -11
  300. package/agents/plan-reviewer.md +3 -3
  301. package/agents/planner.md +1 -1
  302. package/agents/security-auditor.md +1 -1
  303. package/agents/test-engineer.md +11 -4
  304. package/bin/lib/validate-overrides.js +19 -0
  305. package/bin/snapshot-version.js +17 -1
  306. package/bin/sync-harness-versions.js +94 -0
  307. package/codex/CONDUCTOR.md +148 -0
  308. package/docs/ARCHITECTURE.md +210 -0
  309. package/docs/agent-fleet-setup.md +11 -0
  310. package/docs/claude-code-coms-bridge.md +10 -0
  311. package/docs/codex-remote-conductor.md +170 -0
  312. package/docs/coms-hermes-bridge.md +121 -0
  313. package/docs/getting-started.md +14 -0
  314. package/docs/npm-install.md +2 -0
  315. package/docs/pi-extensions.md +49 -14
  316. package/docs/pi-setup.md +12 -4
  317. package/hermes/README.md +228 -0
  318. package/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  319. package/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  320. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-cap.test.py +15 -0
  321. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-discovery.test.py +19 -0
  322. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-envelope.test.py +13 -0
  323. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-forged-owner.test.py +11 -0
  324. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-lease-list.test.py +9 -0
  325. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-multihub.test.py +17 -0
  326. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-output.test.py +34 -0
  327. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +151 -0
  328. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter.test.py +39 -0
  329. package/hermes/plugins/agent-fleet-monitor/dashboard/dist/index.js +10 -0
  330. package/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  331. package/hermes/plugins/agent-fleet-monitor/dashboard/plugin-api-validation.test.py +12 -0
  332. package/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  333. package/hermes/plugins/agent-fleet-monitor/dashboard/review-live-wiring.red.test.py +22 -0
  334. package/hermes/skills/hub-conductor/SKILL.md +84 -0
  335. package/hermes/skills/hub-liaison/SKILL.md +84 -0
  336. package/justfile +106 -23
  337. package/package.json +17 -5
  338. package/scripts/codex-conductor.ts +41 -0
  339. package/scripts/codex-remote-control.ts +167 -0
  340. package/scripts/coms-cli.ts +311 -199
  341. package/scripts/coms-hermes-bridge.ts +2 -2
  342. package/scripts/lib/codex-conductor.ts +88 -0
  343. package/scripts/lib/codex-remote-control.ts +480 -0
  344. package/scripts/lib/coms-envelope.ts +51 -6
  345. package/scripts/lib/fake-herdr-server.ts +88 -0
  346. package/scripts/lib/herdr-layout.ts +18 -3
  347. package/scripts/lib/hermes-bridge-core.ts +4 -4
  348. package/scripts/lib/hermes-monitor-herdr.ts +28 -0
  349. package/scripts/lib/hermes-monitor-model.ts +9 -0
  350. package/scripts/lib/hermes-monitor-registry.ts +6 -0
  351. package/scripts/lib/hermes-monitor-socket.ts +118 -0
  352. package/scripts/lib/hermes-monitor-store.ts +31 -0
  353. package/scripts/lib/team-project.ts +85 -1
  354. package/scripts/team-up.ts +77 -18
  355. package/skills/designing-agents/SKILL.md +2 -2
  356. package/skills/designing-agents/pi-harness-authoring.md +26 -13
  357. package/skills/guided-workspace-setup/SKILL.md +131 -102
  358. package/skills/guided-workspace-setup/companion-manifest.json +33 -0
  359. package/skills/peer-coms/SKILL.md +9 -0
  360. package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  361. package/.pi/harnesses/damage-control/README.md +0 -65
  362. package/.pi/harnesses/damage-control/index.ts +0 -250
@@ -24,14 +24,20 @@
24
24
  * /models [profile] — apply a named model profile (.pi/agents/model-profiles.yaml)
25
25
  * /agent-models-substitute <source> <target> — swap one model across all personas
26
26
  * /dispatch-policy — show which members route to coms peers (.pi/agents/dispatch-policy.yaml)
27
- * /agents-kill <name> — SIGTERM a frozen specialist (and its delegation tree)
28
- * /agents-restart <name>— kill + re-run its last task fresh
27
+ * /agents-kill <name|rN|all> — SIGTERM a frozen specialist (and its delegation
28
+ * tree); on a research helper it kills AND removes the
29
+ * card + session ("all" clears every research helper)
30
+ * (aliases: /research-rm rN, /research-clear)
31
+ * /agents-restart <name|rN> — kill + re-run its last task fresh (research: must
32
+ * be finished; runs on a fresh session)
29
33
  * /zoom <name|rN|child> — scrollable read-only view of an agent's stream
30
34
  * (team member, research helper rN, or delegate child id)
31
35
  * /research <task> — spawn a read-only research helper (@persona, --model)
32
- * /research-cont rN ... — resume a finished research helper
33
- * /research-rm rN — remove a research helper (kill if running)
34
- * /research-clear — remove all research helpers
36
+ * /agents-cont rN ... — resume a finished research helper (alias: /research-cont)
37
+ *
38
+ * Finished research helpers are auto-pruned: auto-research pipe helpers as soon
39
+ * as they finish (findings persist as files under findings/), manual/persona
40
+ * helpers beyond the `research-keep` most recent (default 4, overrides file).
35
41
  * /persona — select/reset the dispatcher persona
36
42
  * /handoff <peer> — hand the session off to a coms peer (summarized brief)
37
43
  * /coms — refresh the coms peer pool (--all / --project <name>)
@@ -64,18 +70,32 @@ import {
64
70
  type AutocompleteItem, truncateToWidth, visibleWidth,
65
71
  } from "@mariozechner/pi-tui";
66
72
  import { spawn, type ChildProcess } from "child_process";
67
- import { spawnPiAgent, killPiTree } from "./spawn.ts";
73
+ import { spawnPiAgent, killPiTree, type PiRunControl, type Termination } from "./spawn.ts";
74
+ import { researchTerminationOutcome, researchWatchdogSpawnOptions } from "./research-watchdog.ts";
75
+ import { renderHubFooterLeft } from "./footer.ts";
76
+ import { HARNESS_VERSION, registerVersionStatus } from "./version.ts";
77
+ import { cancelLocalOwnedProcess, cancelLocalWaitOnly, monitorKeyForAgent } from "./monitor-control.ts";
78
+ import { createMonitorLifecycle, monitorLifecycleConfig } from "./monitor-lifecycle.ts";
79
+ import { MonitorRegistry } from "../../../scripts/lib/hermes-monitor-registry.ts";
80
+ import { MonitorStore } from "../../../scripts/lib/hermes-monitor-store.ts";
81
+ import { createMonitorSessionBridge } from "./monitor-session-bridge.ts";
82
+ import { MonitorRuntime } from "./monitor-runtime.ts";
83
+ import { monitorReconcileEvidence, stableMonitorHubId } from "./monitor-recovery.ts";
68
84
  import {
69
85
  AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
70
- appendExemptionToFile, exemptionsFilePath, fileExemptionsFor,
71
- type AccessDecision, type AccessDecisionChoice, type AccessRequest,
72
- } from "../damage-control/shared.ts";
73
- import { clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, MAX_DELEGATE_DEPTH, parseTeamsYaml, safeAgentKey, safePathWithin } from "./helpers.ts";
86
+ exemptionsFilePath, type AccessRequest,
87
+ } from "../lib/damage-control-shared.ts";
88
+ import { clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, MAX_DELEGATE_DEPTH, normalizeAgentInput, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
89
+ import { DEFAULT_HUB_MODE, DEFAULT_TASK_TIER, HUB_MODES, TASK_TIERS, budgetStatusLine, checkTurnBudget, normalizeHubMode, normalizeTaskTier, resolveTurnBudget, shouldRecycleSession } from "./run-budget.js";
90
+ import { DEFAULT_WATCHDOG_SETTING, WATCHDOG_SETTINGS, buildJudgePrompt, createDriftMonitor, normalizeWatchdogSetting, parseJudgeVerdict, resolveWatchdogActive } from "./drift-watchdog.js";
74
91
  import { artifactPreviewFromText, formatInputArtifactsSection, resolveArtifactPaths, ARTIFACT_KINDS } from "./artifacts.js";
75
92
  import { crossCheck, extractAssertionIds, parseStructuredReturn } from "./return-contract.js";
76
93
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
77
94
  import { validateEvidence } from "./evidence-rules.js";
78
95
  import { comsRequiredRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
96
+ import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
97
+ import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
98
+ import { createAccessApprovalRouter } from "./access-approval.ts";
79
99
  import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
80
100
  import {
81
101
  formatPeerStatus,
@@ -178,6 +198,9 @@ interface AgentState {
178
198
  contextPct: number;
179
199
  sessionFile: string | null;
180
200
  runCount: number;
201
+ // Runs served by the CURRENT accumulated session (-c resume chain). Reset on
202
+ // recycle; drives shouldRecycleSession together with the measured contextPct.
203
+ runsSinceFresh: number;
181
204
  timer?: ReturnType<typeof setInterval>;
182
205
  // Mid-turn delegation (delegate tool). Children parsed live from the event
183
206
  // file, keyed by child id; rendered as nested rows under the card and kept
@@ -217,12 +240,16 @@ interface AgentState {
217
240
  // team with reconnaissance/search/doc-reading — it never writes and never runs bash.
218
241
  // Keyed by a numeric id surfaced to the operator as the handle `rN`. Ephemeral by
219
242
  // construction: session files live under the same dir as team sessions and are wiped
220
- // on session_start; `/research-clear` removes them mid-session. Resumable via
221
- // `/research-cont` (subcont-style, bumping turnCount).
243
+ // on session_start; finished helpers are auto-pruned per the retention policy
244
+ // (research-retention.js — auto-pipe helpers immediately, older manual ones beyond
245
+ // the `research-keep` cap); `/agents-kill rN` (alias `/research-rm`) kills AND
246
+ // removes one by hand. Resumable via `/agents-cont` (alias `/research-cont`,
247
+ // subcont-style, bumping turnCount) while retained.
222
248
  interface ResearchState {
223
249
  id: number;
224
250
  def: AgentDef; // a `kind: research` persona, or a synthesized def for anon helpers
225
251
  persona: boolean; // true → spawned from a persona; false → ad-hoc anonymous
252
+ ephemeral: boolean; // true → auto-research pipe spawn: pruned as soon as it finishes
226
253
  model: string; // resolved pi model spec (shown on the card)
227
254
  status: "idle" | "running" | "done" | "error";
228
255
  task: string;
@@ -232,6 +259,7 @@ interface ResearchState {
232
259
  contextPct: number;
233
260
  sessionFile: string | null; // set after a successful run → enables `-c` resume
234
261
  turnCount: number;
262
+ finishedAt?: number; // last time a run ended (any status) — LRU key for retention
235
263
  timer?: ReturnType<typeof setInterval>;
236
264
  proc?: ChildProcess;
237
265
  killedByOperator?: boolean;
@@ -369,6 +397,31 @@ function extractNeedsResearch(output: string): string[] {
369
397
  // orientation): canonical files (e.g. Docs/AGENTS.md) or
370
398
  // doc folders. Specialists and research helpers read the
371
399
  // ones relevant to their task; context, not compliance.
400
+ // research-keep: <n>|all — how many finished manual/persona research helpers
401
+ // to retain for /agents-cont resume (LRU, default 4);
402
+ // "all" disables pruning. Auto-research pipe helpers
403
+ // are always pruned as soon as they finish.
404
+ // recon-search-timeout-s: <1..3600>|off — parent-side deadline for each
405
+ // read/grep/find/ls call made by research helpers
406
+ // and read-only delegate children (default 120).
407
+ // mode: fast|standard|strict — default execution mode (see run-budget.js).
408
+ // fast = single-specialist path, standard = batched
409
+ // work with turn budgets (default), strict = full
410
+ // Verification Contract with wide budgets.
411
+ // max-dispatches-per-turn: <n>|off — dispatch_agent calls allowed per user turn
412
+ // (replaces the mode default; "off" = unlimited).
413
+ // max-research-per-turn: <n>|off — spawn_research calls allowed per user turn.
414
+ // turn-wall-time-s: <n>|off — wall-clock budget per user turn.
415
+ // agent-turn-timeout-s: <n>|off — whole-run deadline for each spawned
416
+ // specialist/research/delegate run (not per tool).
417
+ // session-recycle-runs: <n>|off — recycle a specialist's accumulated session
418
+ // after this many resumed runs (also recycled at
419
+ // ≥60% measured context regardless).
420
+ // watchdog: on|off|auto — drift watchdog default for dispatched
421
+ // specialists (default auto; see drift-watchdog.js).
422
+ // watchdog-judge-model: <model spec> — model for the drift judge (default:
423
+ // the researcher persona's model, else the
424
+ // dispatcher's).
372
425
 
373
426
  interface AgentTeamOverrides {
374
427
  language: string;
@@ -380,6 +433,20 @@ interface AgentTeamOverrides {
380
433
  personaDelegateDepth: Record<string, number>;
381
434
  rulesDirs: string[];
382
435
  docsPaths: string[];
436
+ researchKeep: number;
437
+ reconSearchTimeoutMs: number | null;
438
+ hubMode: string;
439
+ // Per-axis turn-budget overrides for run-budget.js resolveTurnBudget():
440
+ // number replaces the mode default, null = "off", undefined = keep default.
441
+ budgetOverrides: {
442
+ maxDispatches?: number | null;
443
+ maxResearch?: number | null;
444
+ wallMs?: number | null;
445
+ agentTurnMs?: number | null;
446
+ recycleRuns?: number | null;
447
+ };
448
+ watchdogSetting: string;
449
+ watchdogJudgeModel: string | null;
383
450
  warnings: string[];
384
451
  }
385
452
 
@@ -393,6 +460,12 @@ const DEFAULT_OVERRIDES: AgentTeamOverrides = {
393
460
  personaDelegateDepth: {},
394
461
  rulesDirs: [],
395
462
  docsPaths: [],
463
+ researchKeep: DEFAULT_RESEARCH_KEEP,
464
+ reconSearchTimeoutMs: 120_000,
465
+ hubMode: DEFAULT_HUB_MODE,
466
+ budgetOverrides: {},
467
+ watchdogSetting: DEFAULT_WATCHDOG_SETTING,
468
+ watchdogJudgeModel: null,
396
469
  warnings: [],
397
470
  };
398
471
 
@@ -406,6 +479,7 @@ function freshOverrides(): AgentTeamOverrides {
406
479
  personaDelegateDepth: {},
407
480
  rulesDirs: [],
408
481
  docsPaths: [],
482
+ budgetOverrides: {},
409
483
  warnings: [],
410
484
  };
411
485
  }
@@ -444,6 +518,59 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
444
518
  if (key === "docs" && value) {
445
519
  result.docsPaths = value.split(",").map(s => s.trim()).filter(Boolean);
446
520
  }
521
+ if (key === "research-keep" && value) {
522
+ const keep = parseResearchKeep(value);
523
+ if (keep != null) {
524
+ result.researchKeep = keep;
525
+ } else {
526
+ result.warnings.push(`research-keep "${value}" is not a non-negative integer or "all" — using the default (${DEFAULT_RESEARCH_KEEP})`);
527
+ }
528
+ }
529
+ if (key === "recon-search-timeout-s" && value) {
530
+ if (value.toLowerCase() === "off") {
531
+ result.reconSearchTimeoutMs = null;
532
+ } else if (/^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 3600) {
533
+ result.reconSearchTimeoutMs = Number(value) * 1000;
534
+ } else {
535
+ result.warnings.push(`recon-search-timeout-s "${value}" is not an integer from 1 to 3600 or "off" — using the default (120)`);
536
+ }
537
+ }
538
+ if (key === "mode" && value) {
539
+ const mode = normalizeHubMode(value);
540
+ if (mode) {
541
+ result.hubMode = mode;
542
+ } else {
543
+ result.warnings.push(`mode "${value}" is not one of ${HUB_MODES.join("|")} — using the default (${DEFAULT_HUB_MODE})`);
544
+ }
545
+ }
546
+ if (key === "watchdog" && value) {
547
+ const setting = normalizeWatchdogSetting(value);
548
+ if (setting) {
549
+ result.watchdogSetting = setting;
550
+ } else {
551
+ result.warnings.push(`watchdog "${value}" is not one of ${WATCHDOG_SETTINGS.join("|")} — using the default (${DEFAULT_WATCHDOG_SETTING})`);
552
+ }
553
+ }
554
+ if (key === "watchdog-judge-model" && value) result.watchdogJudgeModel = value;
555
+ // Turn-budget keys: a positive integer replaces the mode default, "off"
556
+ // disables the axis. Counts are unitless; *-s keys are seconds → ms.
557
+ const budgetKeys: Record<string, { field: keyof AgentTeamOverrides["budgetOverrides"]; scaleMs: boolean }> = {
558
+ "max-dispatches-per-turn": { field: "maxDispatches", scaleMs: false },
559
+ "max-research-per-turn": { field: "maxResearch", scaleMs: false },
560
+ "turn-wall-time-s": { field: "wallMs", scaleMs: true },
561
+ "agent-turn-timeout-s": { field: "agentTurnMs", scaleMs: true },
562
+ "session-recycle-runs": { field: "recycleRuns", scaleMs: false },
563
+ };
564
+ if (budgetKeys[key] && value) {
565
+ const { field, scaleMs } = budgetKeys[key];
566
+ if (value.toLowerCase() === "off") {
567
+ result.budgetOverrides[field] = null;
568
+ } else if (/^\d+$/.test(value) && Number(value) >= 1) {
569
+ result.budgetOverrides[field] = Number(value) * (scaleMs ? 1000 : 1);
570
+ } else {
571
+ result.warnings.push(`${key} "${value}" is not a positive integer or "off" — using the ${result.hubMode} mode default`);
572
+ }
573
+ }
447
574
  const slug = "[a-z0-9]+(?:-[a-z0-9]+)*";
448
575
  const modelKey = key.match(new RegExp(`^model\\.(${slug})$`));
449
576
  if (modelKey && value) result.personaModels[modelKey[1]] = value;
@@ -1110,45 +1237,9 @@ function scanAgentDirs(cwd: string): AgentDef[] {
1110
1237
  return agents;
1111
1238
  }
1112
1239
 
1113
- // Resolve a damage-control harness so spawned subagents inherit a guardrail.
1114
- // Order: (1) the exact `-e` path this session was launched with (mirrors `just hub`,
1115
- // robust to symlinks / consuming projects), (2) the repo-local harness under cwd.
1116
- // `dirName` selects the variant: "damage-control" (hard-stop, aborts the turn) or
1117
- // "damage-control-continue" (delivers feedback and keeps going). The dir-name regex
1118
- // is anchored on the trailing slash so "damage-control" never matches the longer
1119
- // "damage-control-continue/index.ts" path (and vice-versa). Returns an absolute
1120
- // path, or null if that variant isn't present.
1121
- function resolveDamageControlVariant(cwd: string, dirName: string): string | null {
1122
- const argv = process.argv;
1123
- const re = new RegExp(`${dirName}[/\\\\]index\\.ts$`);
1124
- for (let i = 0; i < argv.length - 1; i++) {
1125
- if (argv[i] === "-e" || argv[i] === "--extension") {
1126
- const abs = resolve(argv[i + 1]);
1127
- if (re.test(abs) && existsSync(abs)) return abs;
1128
- }
1129
- }
1130
- const local = join(cwd, ".pi", "harnesses", dirName, "index.ts");
1131
- return existsSync(local) ? local : null;
1132
- }
1133
-
1134
- // Persona names (lowercased) that read-only-research, so they get the continue
1135
- // damage-control variant instead of the hard-stop one when dispatched directly.
1240
+ // Persona names whose read-only tools receive the research watchdog policy.
1136
1241
  const RESEARCHER_PERSONAS = new Set(["researcher", "deep-researcher"]);
1137
1242
 
1138
- // The hard-stop guardrail (aborts the turn) loaded into specialists that aren't
1139
- // research helpers. Null → those subagents spawn unguarded, exactly as before.
1140
- function resolveDamageControlExtension(cwd: string): string | null {
1141
- return resolveDamageControlVariant(cwd, "damage-control");
1142
- }
1143
-
1144
- // The continue guardrail (blocks but feeds back, no abort) used for the
1145
- // orchestrator/dispatcher main session and spawned research helpers. Falls back
1146
- // to the hard-stop variant when continue isn't installed, so researchers stay
1147
- // guarded either way.
1148
- function resolveDamageControlContinueExtension(cwd: string): string | null {
1149
- return resolveDamageControlVariant(cwd, "damage-control-continue") ?? resolveDamageControlExtension(cwd);
1150
- }
1151
-
1152
1243
  // The delegate extension injected into specialists that declare `subagents:`.
1153
1244
  // It lives next to this file; fall back to the conventional project path when
1154
1245
  // import.meta resolution doesn't map to a real file (e.g. a bundling loader).
@@ -1683,6 +1774,9 @@ export default function (pi: ExtensionAPI) {
1683
1774
  const pendingReplies: Map<string, PendingReply> = new Map();
1684
1775
  const inboundQueue: Map<string, InboundContext> = new Map();
1685
1776
  let server: net.Server | null = null;
1777
+ let monitorLifecycle: ReturnType<typeof createMonitorLifecycle> | null = null;
1778
+ let monitorHubId: string | null = null;
1779
+ let monitorBridge: ReturnType<typeof createMonitorSessionBridge> | null = null;
1686
1780
  let pingTimer: NodeJS.Timeout | null = null;
1687
1781
  let keepaliveTimer: NodeJS.Timeout | null = null;
1688
1782
  // herdr presence backend (active when this session runs inside a herdr
@@ -1711,18 +1805,22 @@ export default function (pi: ExtensionAPI) {
1711
1805
  // escalations land here, and spawned children read it through the
1712
1806
  // AGENT_HUB_EXEMPTIONS_FILE env plumbing.
1713
1807
  let exemptionsFile: string | null = null;
1714
- // access_request dialogs are serialized (concurrent children don't fight
1715
- // for the screen), in-flight asks are deduped per agent+pattern, and
1716
- // explicit denials are cached so a confused child can't re-prompt.
1717
- let accessAskQueue: Promise<unknown> = Promise.resolve();
1718
- const accessDenyCache = new Set<string>();
1719
- const pendingAccessAsks = new Map<string, Promise<AccessDecisionChoice>>();
1808
+ const accessApprovalRouter = createAccessApprovalRouter({
1809
+ getContext: () => currentCtx,
1810
+ getExemptionsFile: () => exemptionsFile,
1811
+ appendLog: (entry) => { try { pi.appendEntry("damage-control-log", entry); } catch { /* best-effort */ } },
1812
+ now: nowIso,
1813
+ });
1720
1814
 
1721
1815
  const agentStates: Map<string, AgentState> = new Map();
1722
1816
  // Read-only research helpers (Phase 4), keyed by numeric id (handle `rN`). Lives
1723
1817
  // alongside the standing team but renders in its own widget row.
1724
1818
  const researchStates: Map<number, ResearchState> = new Map();
1725
1819
  let nextResearchId = 1;
1820
+ // Retention cap for finished durable (manual/persona) helpers — set from the
1821
+ // overrides file's `research-keep:` key at session start (default 4, Infinity
1822
+ // for "all"). Ephemeral auto-pipe helpers ignore the cap: pruned on finish.
1823
+ let researchKeep = DEFAULT_RESEARCH_KEEP;
1726
1824
 
1727
1825
  // ── Execution history (/agents-history) ──────────
1728
1826
  // A tree of every dispatch: orchestrator (dispatcher) turns, the specialists they
@@ -1897,17 +1995,61 @@ than bulk-reading doc trees; when an entry point is a folder, start from its REA
1897
1995
  or index file. If your work changes something the docs describe (architecture, public
1898
1996
  APIs, commands, structure), say so in your final response so the docs can be updated.`;
1899
1997
  }
1900
- // Resolved once at session_start: the hard-stop damage-control harness loaded
1901
- // into spawned specialists (builder, test-engineer, …) so guardrails follow them.
1902
- let damageControlExtPath: string | null = null;
1903
- // The continue variant (blocks but feeds back instead of aborting), loaded into
1904
- // spawned research helpers (researcher / deep-researcher) so a blocked read lets
1905
- // them adapt and keep going rather than dead-end the turn. The orchestrator/
1906
- // dispatcher main session loads it via the `just hub` recipe.
1907
- let damageControlContinueExtPath: string | null = null;
1998
+ // The one supported safety harness. Every native specialist, researcher, and
1999
+ // nested delegate receives it; a missing harness refuses child dispatch.
2000
+ let safetyHarnessPath: string | null = null;
1908
2001
  // Resolved once at session_start: the delegate extension injected into
1909
2002
  // specialists that declare `subagents:` (null → delegation disabled).
1910
2003
  let delegateExtPath: string | null = null;
2004
+ // Per-tool deadline for read/grep/find/ls in research helpers/delegates. The
2005
+ // whole-run bound is separate: the turn budget's agentTurnMs (run-budget.js).
2006
+ let reconSearchTimeoutMs: number | null = 120_000;
2007
+ // ── Execution mode & per-turn budgets (run-budget.js) ──
2008
+ // hubMode: overrides-file default, switchable live via /hub-mode (session-
2009
+ // lifetime). Budgets are per USER TURN: counters reset in before_agent_start,
2010
+ // so exhaustion means "stop, summarize, ask" and the next user message opens
2011
+ // a fresh window. currentTurnStartedAt (above) doubles as the wall-clock base.
2012
+ let hubMode: string = DEFAULT_HUB_MODE;
2013
+ let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
2014
+ let turnDispatchCount = 0;
2015
+ let turnResearchCount = 0;
2016
+ // Task tier (complexity triage): declared by the dispatcher via set_task_tier,
2017
+ // reset each user turn. Null until declared; the first dispatch of a turn
2018
+ // assumes DEFAULT_TASK_TIER outside strict mode. Caps = min(mode, tier).
2019
+ let turnTaskTier: string | null = null;
2020
+ // Duplicate-dispatch guard: fingerprints of (agent, task) already dispatched
2021
+ // THIS turn. Auto-research resumes and /agents-restart call dispatchAgent
2022
+ // directly, so only real dispatcher tool calls are guarded.
2023
+ const turnDispatchFingerprints = new Set<string>();
2024
+ // ── Drift watchdog (drift-watchdog.js) ──
2025
+ // Hub-wide setting from the overrides file, live-switchable via /watchdog;
2026
+ // per-agent overrides ("on"/"off") win over it; a dispatch_agent `watchdog`
2027
+ // param wins over both.
2028
+ let watchdogSetting: string = DEFAULT_WATCHDOG_SETTING;
2029
+ let watchdogJudgeModel: string | null = null;
2030
+ const watchdogAgentOverrides = new Map<string, "on" | "off">();
2031
+ function currentBudget() {
2032
+ return resolveTurnBudget(hubMode, budgetOverrides, turnTaskTier);
2033
+ }
2034
+ function updateModeStatus() {
2035
+ try {
2036
+ widgetCtx?.ui?.setStatus("hub-mode", budgetStatusLine(hubMode, { dispatches: turnDispatchCount, research: turnResearchCount }, currentBudget(), turnTaskTier));
2037
+ } catch {}
2038
+ }
2039
+ // ── Per-turn cost report (/hub-report) ──
2040
+ interface TurnReport {
2041
+ startedAt: number;
2042
+ tier: string | null;
2043
+ dispatches: { agent: string; status: string; elapsed: number; billed: number; out: number }[];
2044
+ research: number;
2045
+ recycles: number;
2046
+ driftStops: number;
2047
+ refusals: number;
2048
+ }
2049
+ const freshTurnReport = (): TurnReport => ({ startedAt: Date.now(), tier: null, dispatches: [], research: 0, recycles: 0, driftStops: 0, refusals: 0 });
2050
+ let turnReport: TurnReport = freshTurnReport();
2051
+ let lastTurnReport: TurnReport | null = null;
2052
+ const sessionTotals = { turns: 0, dispatches: 0, research: 0, recycles: 0, driftStops: 0, refusals: 0, billed: 0, out: 0 };
1911
2053
  // Session-wide delegated-spend counter (tokens across all delegate children),
1912
2054
  // surfaced in the status line. Resets on session_start.
1913
2055
  let delegatedTokens = 0;
@@ -2234,6 +2376,30 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2234
2376
  }
2235
2377
  }
2236
2378
 
2379
+ function freshAgentState(def: AgentDef): AgentState {
2380
+ const key = safeAgentKey(def.name);
2381
+ const sessionFile = safePathWithin(sessionDir, `${key}.json`);
2382
+ return {
2383
+ def,
2384
+ status: "idle",
2385
+ task: "",
2386
+ toolCount: 0,
2387
+ elapsed: 0,
2388
+ lastWork: "",
2389
+ contextPct: 0,
2390
+ sessionFile: existsSync(sessionFile) ? sessionFile : null,
2391
+ runCount: 0,
2392
+ runsSinceFresh: 0,
2393
+ timeline: [],
2394
+ };
2395
+ }
2396
+
2397
+ // Auto-size grid columns based on team size
2398
+ function recomputeGrid() {
2399
+ const size = agentStates.size;
2400
+ gridCols = size <= 3 ? size : size === 4 ? 2 : 3;
2401
+ }
2402
+
2237
2403
  function activateTeam(teamName: string) {
2238
2404
  activeTeamName = teamName;
2239
2405
  const members = teams[teamName] || [];
@@ -2244,25 +2410,47 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2244
2410
  for (const member of members) {
2245
2411
  const def = defsByName.get(member.toLowerCase());
2246
2412
  if (!def) continue;
2247
- const key = safeAgentKey(def.name);
2248
- const sessionFile = safePathWithin(sessionDir, `${key}.json`);
2249
- agentStates.set(def.name.toLowerCase(), {
2250
- def,
2251
- status: "idle",
2252
- task: "",
2253
- toolCount: 0,
2254
- elapsed: 0,
2255
- lastWork: "",
2256
- contextPct: 0,
2257
- sessionFile: existsSync(sessionFile) ? sessionFile : null,
2258
- runCount: 0,
2259
- timeline: [],
2260
- });
2413
+ agentStates.set(def.name.toLowerCase(), freshAgentState(def));
2261
2414
  }
2415
+ recomputeGrid();
2416
+ }
2262
2417
 
2263
- // Auto-size grid columns based on team size
2264
- const size = agentStates.size;
2265
- gridCols = size <= 3 ? size : size === 4 ? 2 : 3;
2418
+ // ── Dynamic roster (add/drop/save; /agents-add, /agents-drop, team_adjust) ──
2419
+ // The system prompt is rebuilt every turn from agentStates, so a roster
2420
+ // change takes effect on the dispatcher's next turn with no restart.
2421
+
2422
+ function rosterAdd(name: string): { ok: boolean; message: string } {
2423
+ const key = normalizeAgentInput(name);
2424
+ const def = allAgentDefs.find(d => d.name.toLowerCase() === key);
2425
+ if (!def) {
2426
+ const available = allAgentDefs.map(d => d.name).sort().join(", ") || "(none)";
2427
+ return { ok: false, message: `No persona "${name}". Available: ${available}` };
2428
+ }
2429
+ if (agentStates.has(def.name.toLowerCase())) {
2430
+ return { ok: false, message: `${displayName(def.name)} is already in the active team` };
2431
+ }
2432
+ agentStates.set(def.name.toLowerCase(), freshAgentState(def));
2433
+ recomputeGrid();
2434
+ updateWidget();
2435
+ return { ok: true, message: `${displayName(def.name)} added to the active team` };
2436
+ }
2437
+
2438
+ function rosterDrop(name: string): { ok: boolean; message: string } {
2439
+ const key = normalizeAgentInput(name);
2440
+ const state = agentStates.get(key);
2441
+ if (!state) {
2442
+ return { ok: false, message: `"${name}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ") || "empty"})` };
2443
+ }
2444
+ if (state.status === "running") {
2445
+ return { ok: false, message: `${displayName(state.def.name)} is running — wait for it to finish or /agents-kill it first` };
2446
+ }
2447
+ if (agentStates.size <= 1) {
2448
+ return { ok: false, message: `${displayName(state.def.name)} is the last team member — add a replacement before dropping it` };
2449
+ }
2450
+ agentStates.delete(key);
2451
+ recomputeGrid();
2452
+ updateWidget();
2453
+ return { ok: true, message: `${displayName(state.def.name)} dropped from the active team (its session file is kept for re-adding)` };
2266
2454
  }
2267
2455
 
2268
2456
  // ── Grid Rendering ───────────────────────────
@@ -2944,14 +3132,49 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
2944
3132
  };
2945
3133
  }
2946
3134
 
3135
+ // One-shot drift judge (drift-watchdog.js layer 2): a cheap model reads the
3136
+ // original task + recent tool trail and answers ON_TRACK/DRIFTING/STUCK. It
3137
+ // runs WHILE the specialist keeps working; only a negative verdict stops the
3138
+ // run. Judge failures fail open — a broken judge must never kill good work.
3139
+ async function runDriftJudge(
3140
+ input: { agentLabel: string; agentKey: string; task: string; scopeGlobs: string[]; trail: string[]; violation: { rule: string; detail: string } },
3141
+ ctx: any,
3142
+ ): Promise<{ verdict: string; reason: string } | null> {
3143
+ const researcherDef = allAgentDefs.find(d => d.name.toLowerCase() === "researcher");
3144
+ const model = watchdogJudgeModel
3145
+ ?? (researcherDef ? resolvedModel(researcherDef) : null)
3146
+ ?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "openrouter/google/gemini-3-flash-preview");
3147
+ const judgeSession = safePathWithin(sessionDir, `drift-judge-${input.agentKey}.json`);
3148
+ try { unlinkSync(judgeSession); } catch {}
3149
+ try {
3150
+ const res = await spawnPiAgent({
3151
+ model,
3152
+ tools: "read",
3153
+ thinking: "off",
3154
+ appendSystemPrompt: "You are a strict, terse runtime watchdog. Answer with exactly one VERDICT line.",
3155
+ sessionFile: judgeSession,
3156
+ prompt: buildJudgePrompt({ agent: input.agentLabel, task: input.task, scopeGlobs: input.scopeGlobs, trail: input.trail, violation: input.violation }),
3157
+ detached: true,
3158
+ turnDeadlineMs: 60_000,
3159
+ });
3160
+ if (res.spawnError || res.exitCode !== 0) return null;
3161
+ return parseJudgeVerdict(res.output);
3162
+ } catch {
3163
+ return null;
3164
+ } finally {
3165
+ try { unlinkSync(judgeSession); } catch {}
3166
+ }
3167
+ }
3168
+
2947
3169
  async function dispatchAgent(
2948
3170
  agentName: string,
2949
3171
  task: string,
2950
3172
  ctx: any,
2951
3173
  inputArtifacts: InputArtifactPreview[] = [],
2952
3174
  scopeGlobs: string[] = [],
2953
- ): Promise<{ output: string; exitCode: number; elapsed: number }> {
2954
- const key = agentName.toLowerCase();
3175
+ watchdogParam?: boolean,
3176
+ ): Promise<{ output: string; exitCode: number; elapsed: number; billed?: number; out?: number }> {
3177
+ const key = normalizeAgentInput(agentName);
2955
3178
  const state = agentStates.get(key);
2956
3179
  if (!state) {
2957
3180
  return Promise.resolve({
@@ -2985,7 +3208,10 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
2985
3208
 
2986
3209
  const histEntry = historyStart("agent", displayName(state.def.name));
2987
3210
  state.histEntry = histEntry;
2988
-
3211
+ const agentKey = safeAgentKey(state.def.name);
3212
+ const runNumber = state.runCount;
3213
+ const monitorKey = monitorKeyForAgent(state.def.name, state.runCount);
3214
+ const monitorStart = monitorBridge?.startChild({ key: monitorKey, id: `run-${agentKey}-${state.runCount}`, generation: 1, parentId: `hub-turn-${monitorHubId}`, specialist: agentKey }, process.env);
2989
3215
  const startTime = Date.now();
2990
3216
  state.timer = setInterval(() => {
2991
3217
  state.elapsed = Date.now() - startTime;
@@ -2998,7 +3224,8 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
2998
3224
  // at any point. A coms-preferring member with a live same-name pool peer
2999
3225
  // is served by that peer; everything downstream (return contract, ASK_USER,
3000
3226
  // research pipe, history) consumes the same result shape either way.
3001
- const finishRun = (output: string, exitCode: number, opts?: { idle?: boolean; notice?: string }) => {
3227
+ const finishRun = async (output: string, exitCode: number, opts?: { idle?: boolean; notice?: string }) => {
3228
+ await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, output, exitCode === 0 ? "completed" : "failed"));
3002
3229
  clearInterval(state.timer);
3003
3230
  state.elapsed = Date.now() - startTime;
3004
3231
  state.status = opts?.idle ? "idle" : exitCode === 0 ? "done" : "error";
@@ -3039,6 +3266,7 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3039
3266
  ctx.ui.notify(route.comsMissedNotice, "warning");
3040
3267
  }
3041
3268
  if (route.backend === "coms") {
3269
+ void monitorBridge?.registerWaitOnly(monitorKey, () => state.comsAbort?.());
3042
3270
  const allowNativeFallback = (dispatchPolicy.substitutions[personaKey]?.fallback ?? "native") !== "none";
3043
3271
  const timeoutMs = route.timeout_s ? route.timeout_s * 1000 : TIMEOUT_MS;
3044
3272
  const comsRes = await dispatchViaComs(state, task, route.peerName, timeoutMs, allowNativeFallback, ctx, inputArtifacts, scopeGlobs);
@@ -3065,10 +3293,26 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3065
3293
  : "openrouter/google/gemini-3-flash-preview");
3066
3294
 
3067
3295
  // Session file for this agent
3068
- const agentKey = safeAgentKey(state.def.name);
3069
- const runNumber = state.runCount;
3070
3296
  const agentSessionFile = safePathWithin(sessionDir, `${agentKey}.json`);
3071
3297
 
3298
+ // Session recycling: resuming an accumulated session re-bills its whole
3299
+ // context on every model call, and that — not output — is where degraded
3300
+ // sessions burned their tokens (85M of 102M observed tokens were cache
3301
+ // reads). Past the run/context threshold, start fresh: the task text plus
3302
+ // artifact paths must carry the state (they should anyway).
3303
+ const turnBudget = currentBudget();
3304
+ let sessionRecycled = false;
3305
+ if (state.sessionFile && shouldRecycleSession(state.runsSinceFresh, state.contextPct, turnBudget)) {
3306
+ try { unlinkSync(agentSessionFile); } catch {}
3307
+ state.sessionFile = null;
3308
+ state.runsSinceFresh = 0;
3309
+ state.contextPct = 0;
3310
+ sessionRecycled = true;
3311
+ turnReport.recycles++;
3312
+ sessionTotals.recycles++;
3313
+ ctx.ui.notify(`${displayName(state.def.name)}: session recycled (stale context) — starting fresh`, "info");
3314
+ }
3315
+
3072
3316
  // Clarification protocol — every specialist learns to bubble up questions
3073
3317
  // to the dispatcher instead of guessing.
3074
3318
  const clarificationProtocol = `
@@ -3119,15 +3363,11 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3119
3363
  return [role, override ? { ...r, model: override } : r];
3120
3364
  }))
3121
3365
  : null;
3122
- const delegationActive = !!subagentRoles && !!delegateExtPath;
3123
- // Researcher personas get the continue variant (block-but-keep-going) like the
3124
- // dedicated research helpers; every other specialist gets the hard-stop variant.
3125
- // Research helpers normally spawn via spawnResearch, but a custom team could list
3126
- // a researcher persona — honor it here too.
3127
- const dispatchDamageControl = RESEARCHER_PERSONAS.has(personaKey)
3128
- ? damageControlContinueExtPath
3129
- : damageControlExtPath;
3130
- const extensions = dispatchDamageControl ? [dispatchDamageControl] : [];
3366
+ // Fast mode is a single-specialist path: no nested delegation trees.
3367
+ const delegationActive = turnBudget.delegation && !!subagentRoles && !!delegateExtPath;
3368
+ const safety = requireSafetyHarness(safetyHarnessPath);
3369
+ if (!safety.ok) return finishRun(safety.error, 1);
3370
+ const extensions = [...safety.extensions];
3131
3371
  let effectiveTools = state.def.tools;
3132
3372
  let delegateEnv: Record<string, string> | undefined;
3133
3373
  let delegationProtocol = "";
@@ -3148,8 +3388,10 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3148
3388
  parentTools: state.def.tools,
3149
3389
  personaPrompt: state.def.systemPrompt,
3150
3390
  eventDir: delegationDir,
3151
- damageControl: damageControlExtPath || undefined,
3391
+ damageControl: safetyHarnessPath || undefined,
3152
3392
  delegateExt: delegateExtPath,
3393
+ reconSearchTimeoutMs,
3394
+ turnDeadlineMs: turnBudget.agentTurnMs,
3153
3395
  cwd: ctx.cwd || process.cwd(),
3154
3396
  }),
3155
3397
  };
@@ -3180,11 +3422,37 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3180
3422
  const thinkingLevel = resolveThinkingLevel(resolvedThinking(state.def));
3181
3423
  const wantThinking = thinkingLevel !== "off";
3182
3424
 
3425
+ // ── Drift watchdog: layer-1 rules on the live stream, judge on escalation ──
3426
+ // Precedence: dispatch param > per-agent /watchdog override > hub setting.
3427
+ const watchdogArmed = resolveWatchdogActive(watchdogParam, watchdogAgentOverrides.get(key), watchdogSetting);
3428
+ const driftMonitor = watchdogArmed ? createDriftMonitor({ scopeGlobs }) : null;
3429
+ let driftControl: PiRunControl | undefined;
3430
+ let driftStop: { rule: string; detail: string; verdict: string; reason: string } | null = null;
3431
+ let judgeBusy = false;
3432
+ let judgeCooldownUntil = 0;
3433
+ const escalateDrift = (violation: { rule: string; detail: string }) => {
3434
+ if (!driftMonitor || judgeBusy || driftStop || Date.now() < judgeCooldownUntil) return;
3435
+ judgeBusy = true;
3436
+ void runDriftJudge(
3437
+ { agentLabel: displayName(state.def.name), agentKey, task, scopeGlobs, trail: driftMonitor.trail(), violation },
3438
+ ctx,
3439
+ ).then(v => {
3440
+ judgeBusy = false;
3441
+ judgeCooldownUntil = Date.now() + 90_000;
3442
+ if (v && (v.verdict === "drifting" || v.verdict === "stuck")) {
3443
+ driftStop = { ...violation, verdict: v.verdict, reason: v.reason };
3444
+ driftControl?.terminate("drift_stop");
3445
+ }
3446
+ }).catch(() => { judgeBusy = false; });
3447
+ };
3448
+
3183
3449
  // Spawn via the shared helper — first run creates the session, subsequent
3184
3450
  // runs resume it (-c). Stream events drive the card + zoom timeline.
3185
3451
  // `detached` puts the specialist in its own process group so /agents-kill
3186
3452
  // can SIGTERM the whole delegation tree (killPiTree).
3187
3453
  let fullText = "";
3454
+ let runBilled = 0;
3455
+ let runOut = 0;
3188
3456
  const res = await spawnPiAgent({
3189
3457
  model,
3190
3458
  tools: effectiveTools,
@@ -3196,9 +3464,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3196
3464
  extensions,
3197
3465
  env: { ...guardrailEnv(agentKey), ...(delegateEnv || {}) },
3198
3466
  detached: true,
3467
+ // A research persona dispatched through a custom team is still a native
3468
+ // research helper, so it receives the same per-tool watchdog.
3469
+ ...(RESEARCHER_PERSONAS.has(personaKey) ? { toolWatchdog: { timeoutMs: reconSearchTimeoutMs } } : {}),
3470
+ // Whole-run deadline from the active mode's budget (null in strict mode).
3471
+ turnDeadlineMs: turnBudget.agentTurnMs,
3199
3472
  }, {
3200
- onProcess: (p) => { state.proc = p; },
3473
+ onProcess: (p) => { state.proc = p; void monitorStart?.then(task => monitorBridge?.registerOwnedProcessFor(task, p)); },
3474
+ ...(driftMonitor ? { onControl: (c: PiRunControl) => { driftControl = c; } } : {}),
3201
3475
  onTextDelta: (delta) => {
3476
+ void monitorStart?.then(task => monitorBridge?.appendOutputFor(task, delta));
3202
3477
  fullText += delta;
3203
3478
  state.lastWork = fullText.split("\n").filter((l: string) => l.trim()).pop() || "";
3204
3479
  appendTimelineText(state.timeline, "text", delta);
@@ -3220,10 +3495,25 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3220
3495
  });
3221
3496
  updateWidget();
3222
3497
  state.zoomRender?.();
3498
+ const violation = driftMonitor?.onToolStart(toolName, argStr);
3499
+ if (violation) escalateDrift(violation);
3223
3500
  },
3224
- onUsage: (usage) => {
3501
+ onToolEnd: (toolName, _id, isError) => {
3502
+ const violation = driftMonitor?.onToolEnd(toolName, isError);
3503
+ if (violation) escalateDrift(violation);
3504
+ },
3505
+ onUsage: (usage, source) => {
3506
+ // Sum per-message usage; the agent_end usage restates the LAST
3507
+ // message, so it only counts when no message_end ever arrived.
3508
+ if (source === "message_end" || (runBilled === 0 && runOut === 0)) {
3509
+ runBilled += (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
3510
+ runOut += usage.output || 0;
3511
+ }
3225
3512
  if (contextWindow > 0) {
3226
- state.contextPct = ((usage.input || 0) / contextWindow) * 100;
3513
+ // Real context = fresh input + cache reads + cache writes. Counting
3514
+ // usage.input alone showed 1–20% while tens of thousands of cached
3515
+ // tokens were re-sent per step, so the restart advice never fired.
3516
+ state.contextPct = (((usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0)) / contextWindow) * 100;
3227
3517
  updateWidget();
3228
3518
  }
3229
3519
  },
@@ -3239,6 +3529,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3239
3529
 
3240
3530
  // The process could not be spawned at all (proc `error` event).
3241
3531
  if (res.spawnError) {
3532
+ await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, `Error spawning agent: ${res.spawnError}`, "failed"));
3242
3533
  state.status = "error";
3243
3534
  state.lastWork = `Error: ${res.spawnError}`;
3244
3535
  state.killedByOperator = false;
@@ -3258,12 +3549,55 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3258
3549
 
3259
3550
  const full = res.output;
3260
3551
  const code = res.exitCode;
3552
+ if (res.termination) {
3553
+ const reason = res.termination.reason;
3554
+ const tool = res.termination.tool;
3555
+ state.status = "error";
3556
+ state.lastWork = reason === "tool_timeout"
3557
+ ? `tool_timeout: ${tool?.toolName || "tool"} (${tool?.toolCallId || "unknown"})`
3558
+ : reason === "turn_timeout"
3559
+ ? `turn_timeout after ${Math.round(state.elapsed / 1000)}s`
3560
+ : reason === "drift_stop"
3561
+ ? `drift_stop: ${driftStop?.verdict || "watchdog"} (${driftStop?.rule || "rule"})`
3562
+ : "cancelled by caller";
3563
+ updateWidget();
3564
+ state.zoomRender?.(true);
3565
+ historyEnd(histEntry, "error");
3566
+ const onTerminate = state.onTerminate;
3567
+ state.onTerminate = undefined;
3568
+ onTerminate?.();
3569
+ if (reason === "drift_stop") {
3570
+ turnReport.driftStops++;
3571
+ sessionTotals.driftStops++;
3572
+ ctx.ui.notify(`${displayName(state.def.name)} stopped by the drift watchdog (${driftStop?.verdict || "verdict"}: ${driftStop?.reason || driftStop?.detail || "no reason"})`, "warning");
3573
+ }
3574
+ const explanation = reason === "tool_timeout"
3575
+ ? `exceeded its per-tool watchdog on ${tool?.toolName || "tool"} (${tool?.toolCallId || "unknown"})`
3576
+ : reason === "turn_timeout"
3577
+ ? `exceeded the per-run deadline (${Math.round(state.elapsed / 1000)}s; agent-turn-timeout-s / mode budget). ` +
3578
+ `Do NOT re-dispatch the same task unchanged — split it into smaller pieces, or ask the user to raise the deadline`
3579
+ : reason === "drift_stop"
3580
+ ? `was stopped by the drift watchdog. Rule "${driftStop?.rule || "unknown"}" fired (${driftStop?.detail || "no detail"}); ` +
3581
+ `judge verdict ${(driftStop?.verdict || "drifting").toUpperCase()}: ${driftStop?.reason || "(no reason given)"}. ` +
3582
+ `Re-dispatch ONCE with a corrected, NARROWED task that addresses this verdict — never repeat the same task unchanged. ` +
3583
+ `If you believe the watchdog is wrong, tell the user; they can disable it with /watchdog ${key} off`
3584
+ : "was cancelled by its caller";
3585
+ return {
3586
+ output: `${reason}: agent ${displayName(state.def.name)} ${explanation}; terminationConfirmed=${res.termination.confirmed}.` +
3587
+ (full.trim() ? `\n\nPartial output before termination:\n${full.slice(-2000)}` : ""),
3588
+ exitCode: reason === "cancelled" ? 130 : reason === "drift_stop" ? 125 : 124,
3589
+ elapsed: state.elapsed,
3590
+ billed: runBilled,
3591
+ out: runOut,
3592
+ };
3593
+ }
3261
3594
 
3262
3595
  // Operator kill (Phase 2). The exit was a SIGTERM from /agents-kill or
3263
3596
  // /agents-restart, not a real completion: free the card (status → idle),
3264
3597
  // fire any restart waiter, and return a message that tells the dispatcher
3265
3598
  // LLM not to auto-retry. /agents-restart handles the fresh re-dispatch.
3266
3599
  if (state.killedByOperator) {
3600
+ await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, "operator killed run", "cancelled"));
3267
3601
  // !! (not `=== true`): TS otherwise narrows the field to the `false`
3268
3602
  // assigned during setup — the concurrent /agents-restart mutation that
3269
3603
  // makes this true is invisible to the checker across the await.
@@ -3288,11 +3622,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3288
3622
  };
3289
3623
  }
3290
3624
 
3625
+ await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, full, code === 0 ? "completed" : "failed"));
3291
3626
  state.status = code === 0 ? "done" : "error";
3292
3627
 
3293
3628
  // Mark session file as available for resume
3294
3629
  if (code === 0) {
3295
3630
  state.sessionFile = agentSessionFile;
3631
+ state.runsSinceFresh++;
3296
3632
  }
3297
3633
 
3298
3634
  state.lastWork = full.split("\n").filter((l: string) => l.trim()).pop() || "";
@@ -3323,11 +3659,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3323
3659
  ? `${full}${errBlock}`
3324
3660
  : `Agent "${displayName(state.def.name)}" exited with code ${code} and produced no output.${errBlock}`;
3325
3661
  }
3662
+ if (sessionRecycled) {
3663
+ output = `(ℹ ${displayName(state.def.name)}'s session was recycled before this run — it has no memory of earlier dispatches; state must travel via task text/artifacts.)\n\n${output}`;
3664
+ }
3326
3665
 
3327
3666
  return {
3328
3667
  output,
3329
3668
  exitCode: code ?? 1,
3330
3669
  elapsed: state.elapsed,
3670
+ billed: runBilled,
3671
+ out: runOut,
3331
3672
  };
3332
3673
  }
3333
3674
 
@@ -3358,12 +3699,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3358
3699
  return ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "openrouter/google/gemini-3-flash-preview";
3359
3700
  }
3360
3701
 
3361
- function createResearchState(def: AgentDef, persona: boolean, model: string): ResearchState {
3702
+ function createResearchState(def: AgentDef, persona: boolean, model: string, ephemeral = false): ResearchState {
3362
3703
  const id = nextResearchId++;
3363
3704
  const state: ResearchState = {
3364
3705
  id,
3365
3706
  def,
3366
3707
  persona,
3708
+ ephemeral,
3367
3709
  model,
3368
3710
  status: "running",
3369
3711
  task: "",
@@ -3379,8 +3721,23 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3379
3721
  return state;
3380
3722
  }
3381
3723
 
3382
- // Env plumbing for spawned children: the shared exemptions file (both
3383
- // damage-control variants honor pre-granted exemptions from it) and, when
3724
+ // Retention pass, run whenever a helper finishes: drop finished auto-pipe
3725
+ // helpers immediately (their findings persist as files under findings/, their
3726
+ // handles are never resumed) and finished durable helpers beyond the
3727
+ // `research-keep` most recent — so the research row doesn't grow without
3728
+ // bound. Running helpers are untouched; ids stay monotonic (no handle reuse).
3729
+ // /agents-history is unaffected: the timeline holds its own entries.
3730
+ function pruneResearch() {
3731
+ const ids = selectResearchPrunable(Array.from(researchStates.values()), researchKeep);
3732
+ if (ids.length === 0) return;
3733
+ for (const id of ids) {
3734
+ try { unlinkSync(researchSessionPath(id)); } catch {}
3735
+ researchStates.delete(id);
3736
+ }
3737
+ updateResearchWidget();
3738
+ }
3739
+
3740
+ // Env plumbing for spawned children: the shared exemptions file and, when
3384
3741
  // coms is up, the endpoint damage-control-continue escalates blocked path
3385
3742
  // access to (access_request → user dialog in this hub). spawnPiAgent
3386
3743
  // spreads process.env, so delegate grandchildren inherit these for free.
@@ -3400,7 +3757,11 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3400
3757
  prompt: string,
3401
3758
  ctx: any,
3402
3759
  inputArtifacts: InputArtifactPreview[] = [],
3403
- ): Promise<{ output: string; exitCode: number; elapsed: number }> {
3760
+ signal?: AbortSignal,
3761
+ ): Promise<{ output: string; exitCode: number; elapsed: number; termination?: Termination }> {
3762
+ const safety = requireSafetyHarness(safetyHarnessPath);
3763
+ if (!safety.ok) return { output: safety.error, exitCode: 1, elapsed: 0 };
3764
+
3404
3765
  state.status = "running";
3405
3766
  state.task = prompt;
3406
3767
  state.toolCount = 0;
@@ -3435,11 +3796,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3435
3796
  sessionFile: sessionPath,
3436
3797
  resume: !!state.sessionFile,
3437
3798
  prompt: appendInputArtifacts(prompt, inputArtifacts),
3438
- // Research helpers get the continue variant: a blocked read (e.g. peeking
3439
- // at .env to verify a key) feeds back and lets them adapt rather than
3440
- // aborting the whole research turn.
3441
- extensions: damageControlContinueExtPath ? [damageControlContinueExtPath] : [],
3799
+ // A blocked read feeds back so the helper can adapt without aborting.
3800
+ extensions: safety.extensions,
3442
3801
  env: guardrailEnv(`research-r${state.id}`),
3802
+ // Shared native-research policy: owns a child group and applies the
3803
+ // configured per-tool deadline (including explicit `off`/null).
3804
+ ...researchWatchdogSpawnOptions(reconSearchTimeoutMs, signal),
3805
+ // Whole-run deadline from the active mode's budget (null in strict mode).
3806
+ turnDeadlineMs: currentBudget().agentTurnMs,
3443
3807
  }, {
3444
3808
  onProcess: (p) => { state.proc = p; },
3445
3809
  onTextDelta: (delta) => {
@@ -3467,7 +3831,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3467
3831
  },
3468
3832
  onUsage: (usage) => {
3469
3833
  if (contextWindow > 0) {
3470
- state.contextPct = ((usage.input || 0) / contextWindow) * 100;
3834
+ // Same context truth as dispatchAgent: include cache reads/writes.
3835
+ state.contextPct = (((usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0)) / contextWindow) * 100;
3471
3836
  updateResearchWidget();
3472
3837
  }
3473
3838
  },
@@ -3480,11 +3845,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3480
3845
  // The process could not be spawned at all (proc `error` event).
3481
3846
  if (res.spawnError) {
3482
3847
  state.status = "error";
3848
+ state.finishedAt = Date.now();
3483
3849
  state.lastWork = `Error: ${res.spawnError}`;
3484
3850
  state.killedByOperator = false;
3485
3851
  updateResearchWidget();
3486
3852
  state.zoomRender?.(true);
3487
3853
  historyEnd(histEntry, "error");
3854
+ pruneResearch();
3488
3855
  return {
3489
3856
  output: `Error spawning research helper: ${res.spawnError}`,
3490
3857
  exitCode: 1,
@@ -3494,16 +3861,36 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3494
3861
 
3495
3862
  const full = res.output;
3496
3863
  const code = res.exitCode;
3864
+ const termination = res.termination;
3865
+ if (termination) {
3866
+ const outcome = researchTerminationOutcome(state.id, termination);
3867
+ state.status = "error";
3868
+ state.finishedAt = Date.now();
3869
+ state.lastWork = outcome.lastWork;
3870
+ updateResearchWidget();
3871
+ state.zoomRender?.(true);
3872
+ historyEnd(histEntry, "error");
3873
+ pruneResearch();
3874
+ return {
3875
+ output: outcome.output,
3876
+ exitCode: outcome.exitCode,
3877
+ elapsed: state.elapsed,
3878
+ termination,
3879
+ };
3880
+ }
3497
3881
 
3498
- // Operator kill (via /research-rm or /research-clear). Resolve gracefully so
3499
- // a spawn_research tool call awaiting this helper doesn't hang.
3882
+ // Operator kill (via /agents-kill rN|all or its research-* aliases).
3883
+ // Resolve gracefully so a spawn_research tool call awaiting this helper
3884
+ // doesn't hang.
3500
3885
  if (state.killedByOperator) {
3501
3886
  state.killedByOperator = false;
3502
3887
  state.status = "idle";
3888
+ state.finishedAt = Date.now();
3503
3889
  state.lastWork = "(killed by operator)";
3504
3890
  updateResearchWidget();
3505
3891
  state.zoomRender?.(true);
3506
3892
  historyEnd(histEntry, "idle");
3893
+ pruneResearch();
3507
3894
  return {
3508
3895
  output: `Research helper r${state.id} was killed by the operator before it finished.`,
3509
3896
  exitCode: code ?? 143,
@@ -3512,11 +3899,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3512
3899
  }
3513
3900
 
3514
3901
  state.status = code === 0 ? "done" : "error";
3902
+ state.finishedAt = Date.now();
3515
3903
  if (code === 0) state.sessionFile = sessionPath;
3516
3904
  state.lastWork = full.split("\n").filter((l: string) => l.trim()).pop() || "";
3517
3905
  updateResearchWidget();
3518
3906
  state.zoomRender?.(true);
3519
3907
  historyEnd(histEntry, state.status);
3908
+ pruneResearch();
3520
3909
 
3521
3910
  ctx.ui.notify(
3522
3911
  `Research r${state.id} ${state.status} in ${Math.round(state.elapsed / 1000)}s`,
@@ -3686,95 +4075,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3686
4075
  );
3687
4076
  }
3688
4077
 
3689
- // A headless child's damage-control-continue hit a protected-path block and
3690
- // escalates for approval. Synchronous over this one socket: the child has no
3691
- // server of its own, so we hold the connection open and write the decision
3692
- // line when the user answers. The child fails closed after its own timeout;
3693
- // a late "allow" still lands in the exemptions file, so the next attempt
3694
- // (from any child) passes.
4078
+ // A headless child's protected-path block is routed to the serialized,
4079
+ // fail-closed approval controller. The socket remains open until a decision.
3695
4080
  function handleAccessRequest(socket: net.Socket, req: AccessRequest): void {
3696
- const respond = (decision: AccessDecisionChoice) => {
3697
- const reply: AccessDecision = { type: "access_decision", msg_id: req.msg_id, decision };
3698
- try { socket.write(JSON.stringify(reply) + "\n"); } catch { /* child may have timed out */ }
3699
- try { socket.end(); } catch { /* ignore */ }
3700
- };
3701
- const agent = (typeof req.agent === "string" && req.agent) || req.sender_session || "unknown-agent";
3702
- const pattern = typeof req.pattern === "string" ? req.pattern : "";
3703
- if (!pattern) {
3704
- respond("deny");
3705
- return;
3706
- }
3707
- const cacheKey = `${agent}::${pattern}`;
3708
-
3709
- // Already granted session-wide (an earlier ask or /allow) — no dialog.
3710
- if (fileExemptionsFor(exemptionsFile ?? undefined, agent).some((e) => e.pattern === pattern)) {
3711
- respond("allow_all");
3712
- return;
3713
- }
3714
- if (accessDenyCache.has(cacheKey)) {
3715
- respond("deny");
3716
- return;
3717
- }
3718
- // The same ask is already on screen (e.g. delegate children racing) — share the outcome.
3719
- const pending = pendingAccessAsks.get(cacheKey);
3720
- if (pending) {
3721
- pending.then(respond).catch(() => respond("deny"));
3722
- return;
3723
- }
3724
-
3725
- const ask: Promise<AccessDecisionChoice> = accessAskQueue.then(async (): Promise<AccessDecisionChoice> => {
3726
- const ctx = currentCtx;
3727
- if (!ctx || !ctx.hasUI) return "deny";
3728
- const DENY = "Deny (keep blocked)";
3729
- const ONCE = "Allow once";
3730
- const AGENT = `Allow for ${agent} (this session)`;
3731
- const ALL = "Allow for all agents (this session)";
3732
- try {
3733
- ctx.ui.notify(
3734
- `🛡️ Access request from ${agent}: ${req.rule}\n tool: ${req.tool}\n attempted: ${String(req.invocation || "").slice(0, 200)}`,
3735
- "warning",
3736
- );
3737
- // Generous timeout — the child gives up (fail closed) long before
3738
- // this; keeping the dialog up lets a late answer persist below.
3739
- const choice = await ctx.ui.select(
3740
- `🛡️ ${agent} requests access: ${pattern}`,
3741
- [DENY, ONCE, AGENT, ALL],
3742
- { timeout: 600_000 },
3743
- );
3744
- if (choice === ONCE) return "allow_once";
3745
- if (choice === AGENT) return "allow_agent";
3746
- if (choice === ALL) return "allow_all";
3747
- // Only an explicit Deny is cached; a dismissed/timed-out dialog may be re-asked.
3748
- if (choice === DENY) accessDenyCache.add(cacheKey);
3749
- return "deny";
3750
- } catch {
3751
- return "deny";
3752
- }
3753
- });
3754
- accessAskQueue = ask.catch(() => {});
3755
- pendingAccessAsks.set(cacheKey, ask);
3756
- ask.then((decision) => {
3757
- pendingAccessAsks.delete(cacheKey);
3758
- if ((decision === "allow_agent" || decision === "allow_all") && exemptionsFile) {
3759
- try {
3760
- appendExemptionToFile(exemptionsFile, {
3761
- pattern,
3762
- scope: "session",
3763
- agent: decision === "allow_agent" ? agent : undefined,
3764
- grantedVia: "escalation",
3765
- grantedAt: nowIso(),
3766
- });
3767
- } catch { /* best-effort — allow_once semantics still hold via the reply */ }
3768
- }
3769
- try { pi.appendEntry("damage-control-log", { action: `escalation_${decision}`, agent, pattern, tool: req.tool, rule: req.rule }); } catch { /* best-effort */ }
3770
- try {
3771
- currentCtx?.ui.notify(
3772
- `🛡️ Access ${decision === "deny" ? "denied" : `granted (${decision.replace(/_/g, " ")})`}: ${pattern} — ${agent}`,
3773
- decision === "deny" ? "warning" : "info",
3774
- );
3775
- } catch { /* ignore */ }
3776
- respond(decision);
3777
- }).catch(() => respond("deny"));
4081
+ void accessApprovalRouter.handle(socket, req);
3778
4082
  }
3779
4083
 
3780
4084
  function connHandler(socket: net.Socket): void {
@@ -4181,11 +4485,54 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4181
4485
  agent: Type.String({ description: "Agent name (case-insensitive)" }),
4182
4486
  task: Type.String({ description: "Task description for the agent to execute" }),
4183
4487
  artifacts: Type.Optional(Type.Array(Type.String({ description: "Optional repo-relative or session-artifact-relative input artifact path. The hub injects only path + one-line preview; the specialist must read the file itself." }))),
4184
- scope: Type.Optional(Type.Array(Type.String({ description: "Optional advisory file scope globs for writable agents. Changes outside are reported in details.scopeViolations; nothing is auto-reverted." }))),
4488
+ scope: Type.Optional(Type.Array(Type.String({ description: "Optional advisory file scope globs for writable agents. Changes outside are reported in details.scopeViolations; nothing is auto-reverted. Also arms the drift watchdog's live out-of-scope rule." }))),
4489
+ watchdog: Type.Optional(Type.Boolean({ description: "Force the drift watchdog on/off for THIS dispatch (default: per-agent /watchdog override, then the hub-wide setting)." })),
4185
4490
  }),
4186
4491
 
4187
4492
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
4188
- const { agent, task, artifacts, scope } = params as { agent: string; task: string; artifacts?: string[]; scope?: string[] };
4493
+ const { task, artifacts, scope, watchdog } = params as { agent: string; task: string; artifacts?: string[]; scope?: string[]; watchdog?: boolean };
4494
+ // Display names / underscores resolve to the persona slug key space, so
4495
+ // `agent: "Test Engineer"` never burns a dispatch on a lookup error.
4496
+ const agent = normalizeAgentInput((params as { agent: string }).agent);
4497
+ // Unclassified turn: assume the default tier (outside strict, whose full
4498
+ // contract runs uncapped by tiers). The prompt asks for set_task_tier
4499
+ // FIRST; this is the fail-safe, not the intended path.
4500
+ if (turnTaskTier === null && hubMode !== "strict") {
4501
+ turnTaskTier = DEFAULT_TASK_TIER;
4502
+ turnReport.tier = turnTaskTier;
4503
+ updateModeStatus();
4504
+ }
4505
+ // Turn-budget gate: refuse BEFORE any spawn. The dispatcher must stop,
4506
+ // summarize, and ask the user; a new user turn opens a fresh window.
4507
+ const budgetRefusal = checkTurnBudget(
4508
+ "dispatch",
4509
+ { dispatches: turnDispatchCount, research: turnResearchCount },
4510
+ currentBudget(),
4511
+ Date.now() - (currentTurnStartedAt || Date.now()),
4512
+ hubMode,
4513
+ );
4514
+ if (budgetRefusal) {
4515
+ turnReport.refusals++;
4516
+ sessionTotals.refusals++;
4517
+ return {
4518
+ content: [{ type: "text", text: budgetRefusal.message }],
4519
+ details: { agent, task, status: "budget_refused", reason: budgetRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
4520
+ };
4521
+ }
4522
+ // Duplicate-dispatch guard: the same agent with a near-identical task in
4523
+ // one turn is running in circles — the result already exists.
4524
+ const fingerprint = taskFingerprint(agent, task);
4525
+ if (turnDispatchFingerprints.has(fingerprint)) {
4526
+ turnReport.refusals++;
4527
+ sessionTotals.refusals++;
4528
+ return {
4529
+ content: [{ type: "text", text: `⚠ Duplicate dispatch refused: you already dispatched ${agent} with this task (or a trivial rewording of it) THIS turn. Use the earlier result — re-read its digest/returnPath — or change the task materially (new instructions, corrected inputs) before re-dispatching.` }],
4530
+ details: { agent, task, status: "duplicate_refused", elapsed: 0, exitCode: 1, fullOutput: "" },
4531
+ };
4532
+ }
4533
+ turnDispatchCount++;
4534
+ sessionTotals.dispatches++;
4535
+ updateModeStatus();
4189
4536
  let writableTracked = false;
4190
4537
  let scopeSnapshot: any = null;
4191
4538
  let scopeOverlapBaseline = writableOverlapCounter;
@@ -4215,7 +4562,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4215
4562
  scopeSnapshot = snapshotWorktree(ctx.cwd || process.cwd());
4216
4563
  }
4217
4564
 
4218
- let result = await dispatchAgent(agent, task, ctx, inputArtifacts, scopeGlobs);
4565
+ let result = await dispatchAgent(agent, task, ctx, inputArtifacts, scopeGlobs, watchdog);
4566
+ let dispatchBilled = result.billed ?? 0;
4567
+ let dispatchOut = result.out ?? 0;
4219
4568
 
4220
4569
  // Auto-research pipe: when the specialist pauses with NEEDS_RESEARCH
4221
4570
  // lines, the hub (in code, not the dispatcher LLM) fans out read-only
@@ -4240,7 +4589,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4240
4589
 
4241
4590
  const answered = await Promise.all(researchQs.map(async (q) => {
4242
4591
  const rDef = anonResearchDef();
4243
- const rState = createResearchState(rDef, false, resolveResearchModel(rDef, undefined, ctx));
4592
+ // Ephemeral: auto-pipe helpers are pruned as soon as they finish —
4593
+ // their findings persist as files, their rN handles are never resumed.
4594
+ const rState = createResearchState(rDef, false, resolveResearchModel(rDef, undefined, ctx), true);
4244
4595
  updateResearchWidget();
4245
4596
  const rRes = await spawnResearch(rState, q, ctx);
4246
4597
  const file = safePathWithin(findingsDir, `${agentKey}-r${rState.id}.md`);
@@ -4255,7 +4606,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4255
4606
  const resumePrompt = "Research findings for your NEEDS_RESEARCH questions are ready. " +
4256
4607
  "Read each file with your read tool, then continue from where you paused:\n" +
4257
4608
  answered.map((a, i) => `${i + 1}. ${a.question}\n → ${a.file}`).join("\n");
4258
- result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs);
4609
+ result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog);
4610
+ dispatchBilled += result.billed ?? 0;
4611
+ dispatchOut += result.out ?? 0;
4259
4612
  }
4260
4613
 
4261
4614
  let scopeViolations: any = null;
@@ -4287,6 +4640,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4287
4640
  const questions = extractAskUserQuestions(result.output);
4288
4641
 
4289
4642
  const status = result.exitCode === 0 ? "done" : "error";
4643
+ // Record the fingerprint only for completed or watchdog/deadline-stopped
4644
+ // runs — those must not be repeated unchanged. A failed spawn or plain
4645
+ // error stays retryable (the failure may be transient).
4646
+ if (result.exitCode === 0 || result.exitCode === 124 || result.exitCode === 125) {
4647
+ turnDispatchFingerprints.add(fingerprint);
4648
+ }
4649
+ turnReport.dispatches.push({ agent, status, elapsed: result.elapsed, billed: dispatchBilled, out: dispatchOut });
4650
+ sessionTotals.billed += dispatchBilled;
4651
+ sessionTotals.out += dispatchOut;
4290
4652
  const summary = `[${agent}] ${status} in ${Math.round(result.elapsed / 1000)}s`;
4291
4653
  const questionsNotice = questions.length > 0
4292
4654
  ? `\n\n⚠ ${questions.length} ASK_USER question(s) raised by ${agent}. ` +
@@ -4414,6 +4776,28 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4414
4776
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
4415
4777
  const { task, persona, model, artifacts } = params as { task: string; persona?: string; model?: string; artifacts?: string[] };
4416
4778
 
4779
+ // Turn-budget gate (dispatcher-initiated research only — the auto-research
4780
+ // pipe and the /research command are exempt).
4781
+ const budgetRefusal = checkTurnBudget(
4782
+ "research",
4783
+ { dispatches: turnDispatchCount, research: turnResearchCount },
4784
+ currentBudget(),
4785
+ Date.now() - (currentTurnStartedAt || Date.now()),
4786
+ hubMode,
4787
+ );
4788
+ if (budgetRefusal) {
4789
+ turnReport.refusals++;
4790
+ sessionTotals.refusals++;
4791
+ return {
4792
+ content: [{ type: "text", text: budgetRefusal.message }],
4793
+ details: { status: "budget_refused", reason: budgetRefusal.reason },
4794
+ };
4795
+ }
4796
+ turnResearchCount++;
4797
+ turnReport.research++;
4798
+ sessionTotals.research++;
4799
+ updateModeStatus();
4800
+
4417
4801
  let def: AgentDef;
4418
4802
  let isPersona = false;
4419
4803
  if (persona) {
@@ -4444,11 +4828,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4444
4828
  }
4445
4829
 
4446
4830
  try {
4447
- const result = await spawnResearch(state, task, ctx, inputArtifacts);
4831
+ const result = await spawnResearch(state, task, ctx, inputArtifacts, _signal);
4448
4832
  const truncated = result.output.length > 8000
4449
4833
  ? result.output.slice(0, 8000) + "\n\n... [truncated]"
4450
4834
  : result.output;
4451
- const status = result.exitCode === 0 ? "done" : "error";
4835
+ const status = result.termination
4836
+ ? result.termination.reason
4837
+ : result.exitCode === 0 ? "done" : "error";
4452
4838
  const label = isPersona ? displayName(def.name) : "ad-hoc";
4453
4839
  const summary = `[research r${state.id} · ${label} · read-only] ${status} in ${Math.round(result.elapsed / 1000)}s`;
4454
4840
  return {
@@ -4461,6 +4847,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4461
4847
  elapsed: result.elapsed,
4462
4848
  exitCode: result.exitCode,
4463
4849
  fullOutput: result.output,
4850
+ termination: result.termination,
4464
4851
  artifacts: inputArtifacts.map(a => ({ path: a.path, displayPath: a.displayPath, preview: a.preview })),
4465
4852
  },
4466
4853
  };
@@ -4513,6 +4900,102 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4513
4900
  },
4514
4901
  });
4515
4902
 
4903
+ // ── set_task_tier Tool (complexity triage) ──
4904
+ // The dispatcher classifies each user turn BEFORE its first dispatch; the
4905
+ // declared tier lowers the dispatch/research caps to min(mode, tier) in code.
4906
+ // Skipping it makes the first dispatch assume the default tier (run-budget.js).
4907
+
4908
+ pi.registerTool({
4909
+ name: "set_task_tier",
4910
+ label: "Set Task Tier",
4911
+ description:
4912
+ "Classify THIS user turn's ask before your first dispatch: trivial (one obvious, low-risk change — 1 dispatch), small (a contained change, no planning pipeline — 2 dispatches), feature (a normal multi-step feature — 6 dispatches), project (a large effort — mode budget applies). The hub enforces the resulting caps; re-call it if the ask turns out bigger than classified (raising the tier mid-turn is allowed and cheap — say why).",
4913
+ parameters: Type.Object({
4914
+ tier: Type.String({ description: "One of: trivial | small | feature | project" }),
4915
+ reason: Type.Optional(Type.String({ description: "One line on why this tier fits the ask." })),
4916
+ }),
4917
+ async execute(_callId, params, _signal, _onUpdate, _ctx) {
4918
+ const { tier, reason } = params as { tier: string; reason?: string };
4919
+ const normalized = normalizeTaskTier(tier);
4920
+ if (!normalized) {
4921
+ return {
4922
+ content: [{ type: "text" as const, text: `Unknown tier "${tier}" — expected one of: ${TASK_TIERS.join(", ")}. Tier unchanged (${turnTaskTier ?? "unset"}).` }],
4923
+ details: { status: "error", tier: turnTaskTier },
4924
+ };
4925
+ }
4926
+ turnTaskTier = normalized;
4927
+ turnReport.tier = normalized;
4928
+ updateModeStatus();
4929
+ const b = currentBudget();
4930
+ const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
4931
+ return {
4932
+ content: [{ type: "text" as const, text: `Task tier: ${normalized}${reason ? ` (${reason})` : ""}. Effective caps this turn: ${cap(b.maxDispatches)} dispatches, ${cap(b.maxResearch)} research. Size the apparatus accordingly — do not spend a cap just because it exists.` }],
4933
+ details: { status: "ok", tier: normalized },
4934
+ };
4935
+ },
4936
+ renderCall(args, theme) {
4937
+ return new Text(
4938
+ theme.fg("toolTitle", theme.bold("set_task_tier ")) +
4939
+ theme.fg("accent", String((args as any).tier || "?")) +
4940
+ theme.fg("dim", (args as any).reason ? ` — ${String((args as any).reason).slice(0, 60)}` : ""),
4941
+ 0, 0,
4942
+ );
4943
+ },
4944
+ });
4945
+
4946
+ // ── team_adjust Tool (dispatcher-driven roster changes, gated) ──
4947
+ // The dispatcher may restructure its own team mid-session — but never in fast
4948
+ // mode, never past the roster cap, and the human is notified of every change.
4949
+ const TEAM_ADJUST_ROSTER_CAP = 8;
4950
+
4951
+ pi.registerTool({
4952
+ name: "team_adjust",
4953
+ label: "Team Adjust",
4954
+ description:
4955
+ "Add or drop a specialist persona in the ACTIVE team (the roster you can dispatch to). Use sparingly, when the current roster genuinely cannot serve the task (e.g. add security-auditor for a security-sensitive change, drop an unused specialist). Not available in fast mode. The human sees every change and can revert with /agents-add //agents-drop.",
4956
+ parameters: Type.Object({
4957
+ action: Type.String({ description: "add | drop" }),
4958
+ agent: Type.String({ description: "Persona name (case-insensitive), e.g. security-auditor" }),
4959
+ reason: Type.String({ description: "One line on why the roster must change for this task." }),
4960
+ }),
4961
+ async execute(_callId, params, _signal, _onUpdate, ctx) {
4962
+ const { action, agent, reason } = params as { action: string; agent: string; reason: string };
4963
+ const act = String(action || "").trim().toLowerCase();
4964
+ if (hubMode === "fast") {
4965
+ return {
4966
+ content: [{ type: "text" as const, text: "team_adjust is disabled in fast mode — a single-specialist path never needs roster changes. Ask the user to /hub-mode standard if the task outgrew fast mode." }],
4967
+ details: { status: "refused" },
4968
+ };
4969
+ }
4970
+ if (act !== "add" && act !== "drop") {
4971
+ return { content: [{ type: "text" as const, text: `Unknown action "${action}" — expected add or drop.` }], details: { status: "error" } };
4972
+ }
4973
+ if (act === "add" && agentStates.size >= TEAM_ADJUST_ROSTER_CAP) {
4974
+ return {
4975
+ content: [{ type: "text" as const, text: `Roster cap reached (${TEAM_ADJUST_ROSTER_CAP}) — drop an unused member first, or ask the user to /agents-add manually.` }],
4976
+ details: { status: "refused" },
4977
+ };
4978
+ }
4979
+ const result = act === "add" ? rosterAdd(agent) : rosterDrop(agent);
4980
+ if (result.ok) {
4981
+ ctx.ui.notify(`team_adjust (${act}): ${result.message} — dispatcher's reason: ${reason || "(none given)"}`, "info");
4982
+ }
4983
+ const roster = Array.from(agentStates.values()).map(s => s.def.name).join(", ");
4984
+ return {
4985
+ content: [{ type: "text" as const, text: `${result.message}. Active team: ${roster}.` }],
4986
+ details: { status: result.ok ? "ok" : "refused", roster },
4987
+ };
4988
+ },
4989
+ renderCall(args, theme) {
4990
+ return new Text(
4991
+ theme.fg("toolTitle", theme.bold("team_adjust ")) +
4992
+ theme.fg("accent", `${String((args as any).action || "?")} ${String((args as any).agent || "?")}`) +
4993
+ theme.fg("dim", (args as any).reason ? ` — ${String((args as any).reason).slice(0, 50)}` : ""),
4994
+ 0, 0,
4995
+ );
4996
+ },
4997
+ });
4998
+
4516
4999
  // ── Verification Contract tools (assertion ledger) ──
4517
5000
  // set_assertions builds/rebuilds the ledger before dispatching; update_assertion
4518
5001
  // records a gate outcome. Both persist to disk and refresh the one-line status;
@@ -5304,6 +5787,178 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5304
5787
  },
5305
5788
  });
5306
5789
 
5790
+ // ── /hub-mode: execution mode (fast|standard|strict) ──
5791
+ // Session-lifetime switch over the overrides-file default. Budgets bind on
5792
+ // the NEXT tool call (counters are per user turn and keep running); the
5793
+ // dispatcher prompt rebuilds with the new mode on the next turn.
5794
+ pi.registerCommand("hub-mode", {
5795
+ description: "Show or set the execution mode: fast (single specialist) | standard (batched, default) | strict (full Verification Contract)",
5796
+ handler: async (args, ctx) => {
5797
+ widgetCtx = ctx;
5798
+ const requested = (args || "").trim();
5799
+ if (!requested) {
5800
+ const b = currentBudget();
5801
+ const cap = (n: number | null) => (n == null ? "∞" : String(n));
5802
+ ctx.ui.notify(
5803
+ `Execution mode: ${hubMode}\nThis turn: ${turnDispatchCount}/${cap(b.maxDispatches)} dispatches, ` +
5804
+ `${turnResearchCount}/${cap(b.maxResearch)} research\nSwitch with /hub-mode ${HUB_MODES.join("|")}`,
5805
+ "info",
5806
+ );
5807
+ return;
5808
+ }
5809
+ const mode = normalizeHubMode(requested);
5810
+ if (!mode) {
5811
+ ctx.ui.notify(`Unknown mode "${requested}" — expected one of: ${HUB_MODES.join(", ")}`, "error");
5812
+ return;
5813
+ }
5814
+ hubMode = mode;
5815
+ updateModeStatus();
5816
+ ctx.ui.notify(`Execution mode → ${mode} (budgets apply from the next dispatch; prompt updates next turn)`, "success");
5817
+ },
5818
+ });
5819
+
5820
+ pi.registerCommand("watchdog", {
5821
+ description: "Drift watchdog: /watchdog [on|off|auto] hub-wide, /watchdog <agent> [on|off|clear] per agent, no args to show",
5822
+ handler: async (args, ctx) => {
5823
+ widgetCtx = ctx;
5824
+ const parts = (args || "").trim().split(/\s+/).filter(Boolean);
5825
+ if (parts.length === 0) {
5826
+ const perAgent = watchdogAgentOverrides.size > 0
5827
+ ? Array.from(watchdogAgentOverrides.entries()).map(([k, v]) => `${k}: ${v}`).join(", ")
5828
+ : "(none)";
5829
+ ctx.ui.notify(
5830
+ `Drift watchdog: ${watchdogSetting} (hub-wide)\nPer-agent overrides: ${perAgent}\n` +
5831
+ `Judge model: ${watchdogJudgeModel || "(researcher persona's, else dispatcher's)"}\n` +
5832
+ `Usage: /watchdog on|off|auto — or /watchdog <agent> on|off|clear`,
5833
+ "info",
5834
+ );
5835
+ return;
5836
+ }
5837
+ if (parts.length === 1) {
5838
+ const setting = normalizeWatchdogSetting(parts[0]);
5839
+ if (!setting) {
5840
+ ctx.ui.notify(`Unknown setting "${parts[0]}" — expected one of: ${WATCHDOG_SETTINGS.join(", ")} (or /watchdog <agent> on|off|clear)`, "error");
5841
+ return;
5842
+ }
5843
+ watchdogSetting = setting;
5844
+ ctx.ui.notify(`Drift watchdog → ${setting} (applies from the next dispatch)`, "success");
5845
+ return;
5846
+ }
5847
+ const agentKey = normalizeAgentInput(parts[0]);
5848
+ const value = parts[1].toLowerCase();
5849
+ if (!agentStates.has(agentKey)) {
5850
+ ctx.ui.notify(`"${parts[0]}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ")})`, "error");
5851
+ return;
5852
+ }
5853
+ if (value === "clear") {
5854
+ watchdogAgentOverrides.delete(agentKey);
5855
+ ctx.ui.notify(`Drift watchdog override cleared for ${agentKey} (hub-wide setting "${watchdogSetting}" applies)`, "success");
5856
+ return;
5857
+ }
5858
+ if (value !== "on" && value !== "off") {
5859
+ ctx.ui.notify(`Per-agent watchdog must be on, off, or clear — got "${parts[1]}"`, "error");
5860
+ return;
5861
+ }
5862
+ watchdogAgentOverrides.set(agentKey, value);
5863
+ ctx.ui.notify(`Drift watchdog for ${agentKey} → ${value} (overrides the hub-wide "${watchdogSetting}")`, "success");
5864
+ },
5865
+ });
5866
+
5867
+ pi.registerCommand("agents-add", {
5868
+ description: "Add persona(s) to the active team without switching teams: /agents-add <name> [<name>…]",
5869
+ handler: async (args, ctx) => {
5870
+ widgetCtx = ctx;
5871
+ const names = (args || "").trim().split(/\s+/).filter(Boolean);
5872
+ if (names.length === 0) {
5873
+ const available = allAgentDefs
5874
+ .filter(d => !agentStates.has(d.name.toLowerCase()))
5875
+ .map(d => d.name).sort().join(", ") || "(all personas are already in the team)";
5876
+ ctx.ui.notify(`Usage: /agents-add <persona> [<persona>…]\nNot in the team yet: ${available}`, "info");
5877
+ return;
5878
+ }
5879
+ const results = names.map(n => rosterAdd(n));
5880
+ const level = results.some(r => r.ok) ? "success" : "error";
5881
+ ctx.ui.notify(results.map(r => r.message).join("\n"), level as any);
5882
+ ctx.ui.setStatus("agent-team", `Team: ${activeTeamName}* (${agentStates.size})`);
5883
+ },
5884
+ });
5885
+
5886
+ pi.registerCommand("agents-drop", {
5887
+ description: "Drop persona(s) from the active team: /agents-drop <name> [<name>…]",
5888
+ handler: async (args, ctx) => {
5889
+ widgetCtx = ctx;
5890
+ const names = (args || "").trim().split(/\s+/).filter(Boolean);
5891
+ if (names.length === 0) {
5892
+ ctx.ui.notify(`Usage: /agents-drop <persona> [<persona>…]\nActive team: ${Array.from(agentStates.values()).map(s => s.def.name).join(", ")}`, "info");
5893
+ return;
5894
+ }
5895
+ const results = names.map(n => rosterDrop(n));
5896
+ const level = results.some(r => r.ok) ? "success" : "error";
5897
+ ctx.ui.notify(results.map(r => r.message).join("\n"), level as any);
5898
+ ctx.ui.setStatus("agent-team", `Team: ${activeTeamName}* (${agentStates.size})`);
5899
+ },
5900
+ });
5901
+
5902
+ pi.registerCommand("agents-save", {
5903
+ description: "Persist the CURRENT roster as a named team in .pi/agents/teams.yaml: /agents-save <team-name>",
5904
+ handler: async (args, ctx) => {
5905
+ widgetCtx = ctx;
5906
+ const name = (args || "").trim();
5907
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) {
5908
+ ctx.ui.notify("Usage: /agents-save <team-name> (letters, digits, hyphens, underscores)", "error");
5909
+ return;
5910
+ }
5911
+ const members = Array.from(agentStates.values()).map(s => s.def.name);
5912
+ if (members.length === 0) {
5913
+ ctx.ui.notify("The active team is empty — nothing to save.", "error");
5914
+ return;
5915
+ }
5916
+ const teamsPath = join(ctx.cwd || process.cwd(), ".pi", "agents", "teams.yaml");
5917
+ let raw = "";
5918
+ try { raw = existsSync(teamsPath) ? readFileSync(teamsPath, "utf-8") : ""; } catch {}
5919
+ try {
5920
+ mkdirSync(join(ctx.cwd || process.cwd(), ".pi", "agents"), { recursive: true });
5921
+ writeFileSync(teamsPath, upsertTeamInYaml(raw, name, members), "utf-8");
5922
+ } catch (err) {
5923
+ ctx.ui.notify(`Could not write ${teamsPath}: ${err instanceof Error ? err.message : String(err)}`, "error");
5924
+ return;
5925
+ }
5926
+ teams[name] = members;
5927
+ activeTeamName = name;
5928
+ ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
5929
+ ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "success");
5930
+ },
5931
+ });
5932
+
5933
+ pi.registerCommand("hub-report", {
5934
+ description: "Per-turn cost report: dispatches, research, tokens, recycles, drift stops (last turn + session totals)",
5935
+ handler: async (_args, ctx) => {
5936
+ widgetCtx = ctx;
5937
+ const fmtTok = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
5938
+ const renderReport = (label: string, r: TurnReport): string => {
5939
+ const billed = r.dispatches.reduce((n, d) => n + d.billed, 0);
5940
+ const out = r.dispatches.reduce((n, d) => n + d.out, 0);
5941
+ const rows = r.dispatches.map(d => ` ${d.agent}: ${d.status} in ${Math.round(d.elapsed / 1000)}s · ${fmtTok(d.billed)} billed / ${fmtTok(d.out)} out`);
5942
+ return [
5943
+ `${label} — tier ${r.tier ?? "(unset)"} · ${r.dispatches.length} dispatch(es) · ${r.research} research · ` +
5944
+ `${fmtTok(billed)} billed / ${fmtTok(out)} out · ${r.recycles} recycle(s) · ${r.driftStops} drift stop(s) · ${r.refusals} refusal(s)`,
5945
+ ...rows,
5946
+ ].join("\n");
5947
+ };
5948
+ const lines: string[] = [];
5949
+ if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) {
5950
+ lines.push(renderReport("Current turn", turnReport));
5951
+ }
5952
+ if (lastTurnReport) lines.push(renderReport("Last turn", lastTurnReport));
5953
+ lines.push(
5954
+ `Session — ${sessionTotals.turns} dispatching turn(s) · ${sessionTotals.dispatches} dispatch(es) · ${sessionTotals.research} research · ` +
5955
+ `${fmtTok(sessionTotals.billed)} billed / ${fmtTok(sessionTotals.out)} out · ${sessionTotals.recycles} recycle(s) · ` +
5956
+ `${sessionTotals.driftStops} drift stop(s) · ${sessionTotals.refusals} refusal(s)`,
5957
+ );
5958
+ ctx.ui.notify(lines.join("\n\n"), "info");
5959
+ },
5960
+ });
5961
+
5307
5962
  // Alt+A toggles the agent view between the full dashboard grid (above the
5308
5963
  // editor) and the compact running-agents list (below the editor). alt+a has no
5309
5964
  // default pi binding — every useful ctrl+letter is already taken (ctrl+r is
@@ -5942,43 +6597,93 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5942
6597
  return filtered.length > 0 ? filtered : items;
5943
6598
  };
5944
6599
 
5945
- // /research-cont rN <prompt> — resume a finished helper on its existing session.
6600
+ // ── Unified subagent commands ────────────────
6601
+ // Team specialists are addressed by persona name, research helpers by their rN
6602
+ // handle — one command family covers both (mirroring /zoom's target resolution).
6603
+ // The research-* commands remain as aliases of their agents-* counterparts.
6604
+
6605
+ // Resume a finished helper on its existing session. Shared by /agents-cont and
6606
+ // its /research-cont alias.
6607
+ const researchContHandler = async (args: string | undefined, ctx: any) => {
6608
+ widgetCtx = ctx;
6609
+ const trimmed = (args ?? "").trim();
6610
+ const sp = trimmed.indexOf(" ");
6611
+ if (sp === -1) {
6612
+ ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
6613
+ return;
6614
+ }
6615
+ const rid = parseResearchHandle(trimmed.slice(0, sp));
6616
+ const prompt = trimmed.slice(sp + 1).trim();
6617
+ const state = rid != null ? researchStates.get(rid) : undefined;
6618
+ if (!state) {
6619
+ ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
6620
+ return;
6621
+ }
6622
+ if (!prompt) {
6623
+ ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
6624
+ return;
6625
+ }
6626
+ if (state.status === "running") {
6627
+ ctx.ui.notify(`Research r${state.id} is still running — wait for it to finish.`, "warning");
6628
+ return;
6629
+ }
6630
+ state.turnCount++;
6631
+ updateResearchWidget();
6632
+ ctx.ui.notify(`Continuing research r${state.id} (Turn ${state.turnCount})…`, "info");
6633
+ spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
6634
+ };
6635
+
6636
+ pi.registerCommand("agents-cont", {
6637
+ description: "Continue a finished research helper: /agents-cont rN <prompt>",
6638
+ getArgumentCompletions: researchHandleCompletions,
6639
+ handler: researchContHandler,
6640
+ });
6641
+
5946
6642
  pi.registerCommand("research-cont", {
5947
- description: "Continue a finished research helper: /research-cont rN <prompt>",
6643
+ description: "Continue a finished research helper (alias of /agents-cont): /research-cont rN <prompt>",
5948
6644
  getArgumentCompletions: researchHandleCompletions,
5949
- handler: async (args, ctx) => {
5950
- widgetCtx = ctx;
5951
- const trimmed = (args ?? "").trim();
5952
- const sp = trimmed.indexOf(" ");
5953
- if (sp === -1) {
5954
- ctx.ui.notify("Usage: /research-cont rN <prompt>", "error");
5955
- return;
5956
- }
5957
- const rid = parseResearchHandle(trimmed.slice(0, sp));
5958
- const prompt = trimmed.slice(sp + 1).trim();
5959
- const state = rid != null ? researchStates.get(rid) : undefined;
5960
- if (!state) {
5961
- ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
5962
- return;
5963
- }
5964
- if (!prompt) {
5965
- ctx.ui.notify("Usage: /research-cont rN <prompt>", "error");
5966
- return;
5967
- }
5968
- if (state.status === "running") {
5969
- ctx.ui.notify(`Research r${state.id} is still running — wait for it to finish.`, "warning");
5970
- return;
5971
- }
5972
- state.turnCount++;
5973
- updateResearchWidget();
5974
- ctx.ui.notify(`Continuing research r${state.id} (Turn ${state.turnCount})…`, "info");
5975
- spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
5976
- },
6645
+ handler: researchContHandler,
5977
6646
  });
5978
6647
 
5979
- // /research-rm rN — remove one helper (SIGTERM if running).
6648
+ // Remove one research helper (SIGTERM if running) — the state, its card, and
6649
+ // its session file. Team specialists are standing and cannot be removed.
6650
+ function removeResearchHelper(state: ResearchState, ctx: any) {
6651
+ if (state.proc && state.status === "running") {
6652
+ state.killedByOperator = true;
6653
+ state.proc.kill("SIGTERM");
6654
+ ctx.ui.notify(`Research r${state.id} killed and removed.`, "warning");
6655
+ } else {
6656
+ ctx.ui.notify(`Research r${state.id} removed.`, "info");
6657
+ }
6658
+ try { unlinkSync(researchSessionPath(state.id)); } catch {}
6659
+ researchStates.delete(state.id);
6660
+ updateResearchWidget();
6661
+ }
6662
+
6663
+ // Remove all helpers (SIGTERM any running). Shared by /agents-kill all and /research-clear.
6664
+ function clearResearchHelpers(ctx: any) {
6665
+ let killed = 0;
6666
+ const total = researchStates.size;
6667
+ for (const [, state] of Array.from(researchStates.entries())) {
6668
+ if (state.proc && state.status === "running") {
6669
+ state.killedByOperator = true;
6670
+ state.proc.kill("SIGTERM");
6671
+ killed++;
6672
+ }
6673
+ try { unlinkSync(researchSessionPath(state.id)); } catch {}
6674
+ }
6675
+ researchStates.clear();
6676
+ nextResearchId = 1;
6677
+ updateResearchWidget();
6678
+ const msg = total === 0
6679
+ ? "No research helpers to clear."
6680
+ : `Cleared ${total} research helper${total !== 1 ? "s" : ""}${killed > 0 ? ` (${killed} killed)` : ""}.`;
6681
+ ctx.ui.notify(msg, total === 0 ? "info" : "success");
6682
+ }
6683
+
6684
+ // /research-rm — alias of /agents-kill rN (kill on a research handle removes).
5980
6685
  pi.registerCommand("research-rm", {
5981
- description: "Remove a research helper (kill if running): /research-rm rN",
6686
+ description: "Remove a research helper (alias of /agents-kill rN): /research-rm rN",
5982
6687
  getArgumentCompletions: researchHandleCompletions,
5983
6688
  handler: async (args, ctx) => {
5984
6689
  widgetCtx = ctx;
@@ -5988,41 +6693,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5988
6693
  ctx.ui.notify(`Usage: /research-rm rN. Known: ${Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ") || "none"}`, "error");
5989
6694
  return;
5990
6695
  }
5991
- if (state.proc && state.status === "running") {
5992
- state.killedByOperator = true;
5993
- state.proc.kill("SIGTERM");
5994
- ctx.ui.notify(`Research r${state.id} killed and removed.`, "warning");
5995
- } else {
5996
- ctx.ui.notify(`Research r${state.id} removed.`, "info");
5997
- }
5998
- try { unlinkSync(researchSessionPath(state.id)); } catch {}
5999
- researchStates.delete(state.id);
6000
- updateResearchWidget();
6696
+ removeResearchHelper(state, ctx);
6001
6697
  },
6002
6698
  });
6003
6699
 
6004
- // /research-clear — remove all helpers (SIGTERM any running).
6700
+ // /research-clear — alias of /agents-kill all.
6005
6701
  pi.registerCommand("research-clear", {
6006
- description: "Remove all research helpers",
6702
+ description: "Remove all research helpers (alias of /agents-kill all)",
6007
6703
  handler: async (_args, ctx) => {
6008
6704
  widgetCtx = ctx;
6009
- let killed = 0;
6010
- const total = researchStates.size;
6011
- for (const [, state] of Array.from(researchStates.entries())) {
6012
- if (state.proc && state.status === "running") {
6013
- state.killedByOperator = true;
6014
- state.proc.kill("SIGTERM");
6015
- killed++;
6016
- }
6017
- try { unlinkSync(researchSessionPath(state.id)); } catch {}
6018
- }
6019
- researchStates.clear();
6020
- nextResearchId = 1;
6021
- updateResearchWidget();
6022
- const msg = total === 0
6023
- ? "No research helpers to clear."
6024
- : `Cleared ${total} research helper${total !== 1 ? "s" : ""}${killed > 0 ? ` (${killed} killed)` : ""}.`;
6025
- ctx.ui.notify(msg, total === 0 ? "info" : "success");
6705
+ clearResearchHelpers(ctx);
6026
6706
  },
6027
6707
  });
6028
6708
 
@@ -6049,16 +6729,60 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6049
6729
  },
6050
6730
  });
6051
6731
 
6732
+ // Completions over both target kinds: team persona names + research handles
6733
+ // (rN), each annotated with status — for the unified /agents-kill and
6734
+ // /agents-restart.
6735
+ const subagentTargetCompletions = (prefix: string): AutocompleteItem[] | null => {
6736
+ const items = [...(agentNameCompletions("") ?? []), ...(researchHandleCompletions("") ?? [])];
6737
+ if (items.length === 0) return null;
6738
+ const filtered = items.filter(i => i.value.toLowerCase().startsWith(prefix.toLowerCase()));
6739
+ return filtered.length > 0 ? filtered : items;
6740
+ };
6741
+
6742
+ // /agents-kill completions additionally offer "all" (research helpers only).
6743
+ const agentsKillCompletions = (prefix: string): AutocompleteItem[] | null => {
6744
+ const targets = subagentTargetCompletions("") ?? [];
6745
+ const items = researchStates.size > 0
6746
+ ? [...targets, { value: "all", label: "all — kill & remove every research helper" }]
6747
+ : targets;
6748
+ if (items.length === 0) return null;
6749
+ const filtered = items.filter(i => i.value.toLowerCase().startsWith(prefix.toLowerCase()));
6750
+ return filtered.length > 0 ? filtered : items;
6751
+ };
6752
+
6052
6753
  pi.registerCommand("agents-kill", {
6053
- description: "Kill a running specialist: /agents-kill <name>",
6054
- getArgumentCompletions: agentNameCompletions,
6754
+ description: "Kill a running specialist, or kill & remove research helper(s): /agents-kill <name|rN|all>",
6755
+ getArgumentCompletions: agentsKillCompletions,
6055
6756
  handler: async (args, ctx) => {
6056
6757
  widgetCtx = ctx;
6057
6758
  const name = args?.trim();
6759
+ // "all" clears every research helper (kill any running). Team specialists
6760
+ // are standing — never touched by "all".
6761
+ if (name?.toLowerCase() === "all") {
6762
+ clearResearchHelpers(ctx);
6763
+ return;
6764
+ }
6765
+ // An rN handle targets a research helper. Research helpers are disposable
6766
+ // by design, so kill also REMOVES — the card, the state, and the session
6767
+ // file go with the process (a finished helper is simply removed).
6768
+ const rid = name ? parseResearchHandle(name) : null;
6769
+ if (rid != null) {
6770
+ const rState = researchStates.get(rid);
6771
+ if (!rState) {
6772
+ const known = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
6773
+ ctx.ui.notify(`No research helper "${name}". Known: ${known || "none"}`, "error");
6774
+ return;
6775
+ }
6776
+ removeResearchHelper(rState, ctx);
6777
+ return;
6778
+ }
6058
6779
  const state = name ? agentStates.get(name.toLowerCase()) : undefined;
6059
6780
  if (!state) {
6060
- const known = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
6061
- ctx.ui.notify(`Usage: /agents-kill <name>. Known: ${known || "none"}`, "error");
6781
+ const known = [
6782
+ ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6783
+ ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6784
+ ].join(", ");
6785
+ ctx.ui.notify(`Usage: /agents-kill <name|rN|all>. Known: ${known || "none"}`, "error");
6062
6786
  return;
6063
6787
  }
6064
6788
  if (state.status !== "running" || (!state.proc && !state.comsAbort)) {
@@ -6068,7 +6792,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6068
6792
  // Coms-backed run: no local process to SIGTERM — only the wait can be
6069
6793
  // released; the standing peer keeps running its turn in its own pane.
6070
6794
  if (!state.proc) {
6071
- state.comsAbort?.();
6795
+ void cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.runCount), event: { kind: "wait_only_cancelled" } });
6072
6796
  ctx.ui.notify(`Abandoning ${displayName(state.def.name)}'s coms dispatch (the peer pane keeps running)...`, "info");
6073
6797
  return;
6074
6798
  }
@@ -6076,21 +6800,51 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6076
6800
  // delegate children die with it. The close handler resolves the awaited
6077
6801
  // dispatch with a "do not auto-retry" message, unblocking the dispatcher.
6078
6802
  state.killedByOperator = true;
6079
- killPiTree(state.proc);
6803
+ cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.runCount), treeKill: killPiTree });
6080
6804
  ctx.ui.notify(`Killing ${displayName(state.def.name)}...`, "info");
6081
6805
  },
6082
6806
  });
6083
6807
 
6084
6808
  pi.registerCommand("agents-restart", {
6085
- description: "Kill and re-run a specialist's last task fresh: /agents-restart <name>",
6086
- getArgumentCompletions: agentNameCompletions,
6809
+ description: "Kill and re-run a specialist's (or re-run a finished research helper's) last task fresh: /agents-restart <name|rN>",
6810
+ getArgumentCompletions: subagentTargetCompletions,
6087
6811
  handler: async (args, ctx) => {
6088
6812
  widgetCtx = ctx;
6089
6813
  const name = args?.trim();
6814
+ // An rN handle re-runs a finished helper's last task on a fresh session
6815
+ // (unlike /agents-cont, which resumes the existing one). A running helper
6816
+ // can't be restarted mid-flight — spawnResearch's promise is held by its
6817
+ // original caller, and /agents-kill removes the helper outright.
6818
+ const rid = name ? parseResearchHandle(name) : null;
6819
+ if (rid != null) {
6820
+ const rState = researchStates.get(rid);
6821
+ if (!rState) {
6822
+ const known = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
6823
+ ctx.ui.notify(`No research helper "${name}". Known: ${known || "none"}`, "error");
6824
+ return;
6825
+ }
6826
+ if (rState.status === "running") {
6827
+ ctx.ui.notify(`Research r${rState.id} is still running — wait for it to finish (or /agents-kill r${rState.id} to discard it and /research the task again).`, "warning");
6828
+ return;
6829
+ }
6830
+ if (!rState.task) {
6831
+ ctx.ui.notify(`Research r${rState.id} has no previous task to restart.`, "warning");
6832
+ return;
6833
+ }
6834
+ rState.sessionFile = null;
6835
+ rState.turnCount = 1;
6836
+ updateResearchWidget();
6837
+ ctx.ui.notify(`Restarting research r${rState.id} (fresh)...`, "info");
6838
+ spawnResearch(rState, rState.task, ctx).then(result => deliverResearchFollowUp(rState, result));
6839
+ return;
6840
+ }
6090
6841
  const state = name ? agentStates.get(name.toLowerCase()) : undefined;
6091
6842
  if (!state) {
6092
- const known = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
6093
- ctx.ui.notify(`Usage: /agents-restart <name>. Known: ${known || "none"}`, "error");
6843
+ const known = [
6844
+ ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6845
+ ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6846
+ ].join(", ");
6847
+ ctx.ui.notify(`Usage: /agents-restart <name|rN>. Known: ${known || "none"}`, "error");
6094
6848
  return;
6095
6849
  }
6096
6850
  const task = state.task;
@@ -6102,16 +6856,17 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6102
6856
  // re-dispatching (dispatchAgent rejects a re-entry while status is running).
6103
6857
  // A coms-backed run has no process — abandoning the wait is the "kill".
6104
6858
  if (state.status === "running" && (state.proc || state.comsAbort)) {
6105
- await new Promise<void>(res => {
6106
- state.onTerminate = res;
6107
- if (state.proc) {
6108
- state.killedByOperator = true;
6109
- state.restarting = true;
6110
- killPiTree(state.proc);
6111
- } else {
6112
- state.comsAbort?.();
6113
- }
6114
- });
6859
+ let resolveTermination!: () => void;
6860
+ const terminated = new Promise<void>(res => { resolveTermination = res; });
6861
+ state.onTerminate = resolveTermination;
6862
+ if (state.proc) {
6863
+ state.killedByOperator = true;
6864
+ state.restarting = true;
6865
+ killPiTree(state.proc);
6866
+ } else {
6867
+ await cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.runCount), event: { kind: "restart" } });
6868
+ }
6869
+ await terminated;
6115
6870
  }
6116
6871
  // Re-run fresh: a frozen session file may be inconsistent, so drop it (no -c).
6117
6872
  state.sessionFile = null;
@@ -6333,6 +7088,20 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6333
7088
  currentOrchestratorEntry = null;
6334
7089
  askUserStarts.clear();
6335
7090
  turnAskUserIntervals.length = 0;
7091
+ // Fresh turn → fresh budget window (mode itself persists across turns).
7092
+ // The tier and the duplicate guard are turn-scoped too: a new user message
7093
+ // is a new ask, so it re-triages and may legitimately repeat a task.
7094
+ turnDispatchCount = 0;
7095
+ turnResearchCount = 0;
7096
+ turnTaskTier = null;
7097
+ turnDispatchFingerprints.clear();
7098
+ // Snapshot the previous turn's cost report before opening a fresh one.
7099
+ if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) {
7100
+ lastTurnReport = turnReport;
7101
+ sessionTotals.turns++;
7102
+ }
7103
+ turnReport = freshTurnReport();
7104
+ updateModeStatus();
6336
7105
 
6337
7106
  // Build dynamic agent catalog from active team only
6338
7107
  const agentCatalog = Array.from(agentStates.values())
@@ -6382,8 +7151,8 @@ ask the human. You MUST instead:
6382
7151
  the user in ${userLanguage} and wait for their reply in the next turn.`;
6383
7152
 
6384
7153
  const toolList = askUserAvailable
6385
- ? "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger), and `ask_user` (talk to the human)"
6386
- : "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), and `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger). `ask_user` is NOT available — see the section below";
7154
+ ? "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_task_tier` (classify the ask before the first dispatch), `team_adjust` (add/drop a team persona, sparingly), `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger), and `ask_user` (talk to the human)"
7155
+ : "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_task_tier` (classify the ask before the first dispatch), `team_adjust` (add/drop a team persona, sparingly), and `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger). `ask_user` is NOT available — see the section below";
6387
7156
 
6388
7157
  const dispatchSection = askUserAvailable
6389
7158
  ? `- BEFORE dispatching: if anything is ambiguous, missing, or could go several valid
@@ -6425,6 +7194,105 @@ ask the human. You MUST instead:
6425
7194
  - When a specialist emits an \`ASK_USER:\` line in English, translate it to
6426
7195
  ${userLanguage} before relaying to the user.${userLanguage.toLowerCase() === "english" ? " (If user-language is English this is a no-op.)" : ""}`;
6427
7196
 
7197
+ // ── Execution mode section + mode-conditional Verification Contract ──
7198
+ // The mode is the dispatcher's operating envelope: the hub ENFORCES the
7199
+ // budgets in code (dispatch_agent/spawn_research refuse past them); the
7200
+ // prompt teaches the dispatcher to plan within them instead of hitting them.
7201
+ const budget = currentBudget();
7202
+ const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
7203
+ const capMin = (ms: number | null) => (ms == null ? "unlimited" : `${Math.round(ms / 60_000)} min`);
7204
+ const modeSection = `## Task triage (FIRST, before any dispatch)
7205
+ Call \`set_task_tier\` to classify THIS turn's ask — the hub lowers the enforced caps
7206
+ to min(mode, tier), so an honest tier is how you avoid burning budget on ceremony:
7207
+ - trivial — one obvious, low-risk change (1 dispatch, 1 research). No ledger, no review pipeline.
7208
+ - small — a contained change in familiar code (2 dispatches, 2 research). At most 3 narrow assertions.
7209
+ - feature — a normal multi-step feature (6 dispatches, 4 research). Ledger + one review gate.
7210
+ - project — a large, multi-phase effort (mode budget applies). Full rigor per the mode.
7211
+ If you skip the call, the hub assumes "feature". Re-call it (say why) if the ask turns
7212
+ out bigger — raising the tier mid-turn is allowed. Tie the tier to the USER'S ask, not
7213
+ to how interesting the work is.
7214
+ - A provided plan is a SPEC: when the user hands you an existing plan/task list (a PLAN
7215
+ file, a numbered breakdown), do NOT re-plan or re-spec it. Skip planner and
7216
+ plan-reviewer; batch the plan's tasks straight to the builder and use the plan's own
7217
+ acceptance criteria as the assertions.
7218
+ - Using every persona is a smell, not a virtue: each dispatch must change the outcome.
7219
+ If a dispatch's absence would change nothing, don't make it.
7220
+
7221
+ ## Execution mode: ${hubMode}${turnTaskTier ? ` · tier: ${turnTaskTier}` : ""}
7222
+ Budgets for THIS user turn (enforced by the hub — exhausted budgets make dispatch_agent/
7223
+ spawn_research refuse; a new user message opens a fresh window; /hub-mode switches mode):
7224
+ - dispatch_agent calls: ${cap(budget.maxDispatches)} · spawn_research calls: ${cap(budget.maxResearch)}
7225
+ - turn wall clock: ${capMin(budget.wallMs)} · per-run deadline: ${capMin(budget.agentTurnMs)}
7226
+ Plan within the budget: batch related work into ONE dispatch (a coherent slice of 4–6
7227
+ plan tasks, not one dispatch per micro-task), and when a budget refusal comes back, STOP —
7228
+ summarize progress and ask the user; never retry the refused call in the same turn.
7229
+ Repeating an identical task to the same agent in one turn is refused in code
7230
+ (duplicate guard) — use the earlier result or change the task materially.
7231
+ Every task you dispatch states four things: the objective, the expected output format,
7232
+ the files in scope (also pass them as \`scope\` globs — they arm the live drift watchdog),
7233
+ and the boundaries (what NOT to touch). Vague tasks produce duplicated or drifting work.
7234
+ ${hubMode === "fast"
7235
+ ? `FAST mode rules: this is a single-specialist path for small, low-risk asks.
7236
+ - Use at most ONE specialist dispatch (plus one research call only if truly needed).
7237
+ - Skip the assertion ledger and the plan/review pipeline; rely on the specialist's own
7238
+ verification and report back.
7239
+ - Nested delegation is disabled; do not commission inventories or parity audits.
7240
+ - If the task turns out to be larger than fast mode fits, say so and ask the user to
7241
+ switch modes (/hub-mode standard) instead of burning the budget.`
7242
+ : hubMode === "standard"
7243
+ ? `STANDARD mode rules: rigor where it pays, batching everywhere else.
7244
+ - At most ONE reconnaissance pass before building (skip it for familiar code); prefer the
7245
+ specialist's own recon over a separate research run.
7246
+ - Execute plans in a FEW large batches (4–6 tasks per builder dispatch), each followed by
7247
+ ONE verification gate; do not re-audit everything after every small fix — re-verify only
7248
+ the assertions the fix touched.
7249
+ - One review gate at the end (code review; security only when the change is
7250
+ security-sensitive) — not one per micro-slice.
7251
+ - Reserve deep-researcher for genuinely cross-cutting questions (max 1–2 per task).`
7252
+ : `STRICT mode rules: the full Verification Contract below applies — use for production
7253
+ migrations, security-sensitive work, or when the user explicitly asks for it. The wide
7254
+ budgets are a checkpoint, not a target: when one is hit, stop and check in with the user.`}
7255
+ `;
7256
+
7257
+ const fullVerificationContract = `## Verification Contract (assertion ledger)
7258
+ A clearly stated requirement must never be silently dropped. You OWN a ledger of checkable
7259
+ acceptance assertions; build it before you dispatch, and refuse "done" until each is proven.
7260
+ - BEFORE dispatching a builder for any non-trivial task, convert the request into numbered
7261
+ assertions and record them with \`set_assertions\` — one pass condition each, tagged
7262
+ test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
7263
+ Pass the relevant assertions VERBATIM into each dispatch.
7264
+ - Keep assertions NARROW: one subsystem / one behavior each. Never bundle several
7265
+ subsystems into one giant assertion — a compound assertion forces a full re-audit after
7266
+ every small fix. After a fix, re-verify the touched assertions only.
7267
+ - After each verification gate, call \`update_assertion\` with proven (and name the evidence),
7268
+ unproven, or failed. Advance ONLY on proven; unproven and failed both mean not done.
7269
+ - A runtime-ui assertion (visibility, placement, "appears in the table") is proven only by an
7270
+ actual runtime observation — dispatch a browser-capable specialist; a static review never
7271
+ closes it.
7272
+ - For "make X behave like existing Y" requests, FIRST spawn_research a deep-researcher parity
7273
+ inventory of every site where the exemplar is special-cased, and turn each site into an
7274
+ assertion — otherwise the exemplar ships and its siblings are missed.
7275
+ - On a "wrong again" correction, call \`set_assertions\` again to rebuild the ledger from the
7276
+ LATEST correction before re-dispatching (a regression reset — old summaries are now suspect).
7277
+ - After a context compaction your status line shows only counts (e.g. "2✓ 3○"), not the
7278
+ assertion text. Call \`get_assertions\` to read the full ledger back — ids, tags, pass
7279
+ conditions, and the named evidence on each proven/failed assertion — before you re-dispatch
7280
+ or report done. This is your bounded read-only window onto recorded ground truth; you do not
7281
+ author code.
7282
+ - Specialist returns land pre-parsed in \`details.structuredReturn\` with the raw return at
7283
+ \`details.returnPath\` — read the digest/path directly; NEVER spawn a research helper just to
7284
+ read a return artifact you already hold.
7285
+ The ledger is persisted and its status is shown to the human; it is advisory — it informs your
7286
+ gating, it does not auto-block a dispatch.`;
7287
+
7288
+ const verificationSection = hubMode === "fast"
7289
+ ? `## Verification (fast mode)
7290
+ The assertion ledger is OPTIONAL in fast mode. State what was asked, dispatch the one
7291
+ specialist, and verify from its returned evidence (command output, file:line). If the
7292
+ request carries real acceptance criteria or turns risky, ask the user to switch to
7293
+ standard/strict instead of improvising rigor here.`
7294
+ : fullVerificationContract;
7295
+
6428
7296
  // Peer section only when coms initialised. Decision G4: the coms_* tools are
6429
7297
  // already in the active tool surface when ready; here we just teach the
6430
7298
  // dispatcher how and when to reach for them.
@@ -6460,7 +7328,10 @@ ${languageLines}
6460
7328
  ## Active Team: ${activeTeamName}
6461
7329
  Members: ${teamMembers}
6462
7330
  You can ONLY dispatch to agents listed below. Do not attempt to dispatch to agents
6463
- outside this team.
7331
+ outside this team. The roster CAN change mid-session: the human via /agents-add,
7332
+ /agents-drop, /agents-team — or you via \`team_adjust\` (add/drop with a reason)
7333
+ when the current roster genuinely cannot serve the task. Use it sparingly; more
7334
+ personas is usually the wrong answer.
6464
7335
 
6465
7336
  ## How to Work
6466
7337
  - Analyze the user's request and break it into clear sub-tasks.
@@ -6472,30 +7343,8 @@ ${dispatchSection}
6472
7343
 
6473
7344
  ${askUserBlock}
6474
7345
 
6475
- ## Verification Contract (assertion ledger)
6476
- A clearly stated requirement must never be silently dropped. You OWN a ledger of checkable
6477
- acceptance assertions; build it before you dispatch, and refuse "done" until each is proven.
6478
- - BEFORE dispatching a builder for any non-trivial task, convert the request into numbered
6479
- assertions and record them with \`set_assertions\` — one pass condition each, tagged
6480
- test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
6481
- Pass the relevant assertions VERBATIM into each dispatch.
6482
- - After each verification gate, call \`update_assertion\` with proven (and name the evidence),
6483
- unproven, or failed. Advance ONLY on proven; unproven and failed both mean not done.
6484
- - A runtime-ui assertion (visibility, placement, "appears in the table") is proven only by an
6485
- actual runtime observation — dispatch a browser-capable specialist; a static review never
6486
- closes it.
6487
- - For "make X behave like existing Y" requests, FIRST spawn_research a deep-researcher parity
6488
- inventory of every site where the exemplar is special-cased, and turn each site into an
6489
- assertion — otherwise the exemplar ships and its siblings are missed.
6490
- - On a "wrong again" correction, call \`set_assertions\` again to rebuild the ledger from the
6491
- LATEST correction before re-dispatching (a regression reset — old summaries are now suspect).
6492
- - After a context compaction your status line shows only counts (e.g. "2✓ 3○"), not the
6493
- assertion text. Call \`get_assertions\` to read the full ledger back — ids, tags, pass
6494
- conditions, and the named evidence on each proven/failed assertion — before you re-dispatch
6495
- or report done. This is your bounded read-only window onto recorded ground truth; you do not
6496
- author code.
6497
- The ledger is persisted and its status is shown to the human; it is advisory — it informs your
6498
- gating, it does not auto-block a dispatch.
7346
+ ${modeSection}
7347
+ ${verificationSection}
6499
7348
 
6500
7349
  ## Research helpers (read-only)
6501
7350
  - \`spawn_research\` runs a READ-ONLY helper (read/grep/find/ls — no bash, no writes)
@@ -6562,6 +7411,8 @@ ${researchCatalog}`;
6562
7411
  // ── Session Start ────────────────────────────
6563
7412
 
6564
7413
  pi.on("session_start", async (_event, _ctx) => {
7414
+ registerVersionStatus(_ctx);
7415
+ accessApprovalRouter.reset();
6565
7416
  // Clear widgets + any research helpers from a previous session
6566
7417
  for (const [, st] of Array.from(researchStates.entries())) {
6567
7418
  if (st.proc && st.status === "running") { st.killedByOperator = true; st.proc.kill("SIGTERM"); }
@@ -6586,16 +7437,95 @@ ${researchCatalog}`;
6586
7437
  delegatedTokens = 0;
6587
7438
  widgetCtx = _ctx;
6588
7439
  contextWindow = _ctx.model?.contextWindow || 0;
6589
- damageControlExtPath = resolveDamageControlExtension(_ctx.cwd);
6590
- damageControlContinueExtPath = resolveDamageControlContinueExtension(_ctx.cwd);
6591
- if (!damageControlExtPath) {
7440
+ safetyHarnessPath = resolveSafetyHarness(_ctx.cwd);
7441
+ if (!safetyHarnessPath) {
6592
7442
  _ctx.ui.notify(
6593
- "damage-control harness not found — specialists and research helpers will spawn UNGUARDED. Install .pi/harnesses/damage-control/ (guided setup pairs it with agent-hub).",
6594
- "warning",
7443
+ "damage-control-continue harness not found — native child dispatches will be refused. Install .pi/harnesses/damage-control-continue/.",
7444
+ "error",
6595
7445
  );
6596
7446
  }
6597
7447
  delegateExtPath = resolveDelegateExtension(_ctx.cwd);
6598
7448
 
7449
+ const monitorConfig = monitorLifecycleConfig(process.env);
7450
+ if (monitorBridge || monitorLifecycle) { try { await monitorBridge?.cancelAllWaitOnly(); await monitorLifecycle?.stop(); } finally { monitorBridge=null; monitorLifecycle=null; } }
7451
+ if (monitorConfig) {
7452
+ try {
7453
+ fs.mkdirSync(monitorConfig.profilePath, { recursive: true, mode: 0o700 });
7454
+ const stableHubId = stableMonitorHubId({ profileId: monitorConfig.profileId, checkout: _ctx.cwd || process.cwd(), workspaceId: process.env.HERDR_WORKSPACE_ID, paneId: process.env.HERDR_PANE_ID });
7455
+ monitorHubId = stableHubId;
7456
+ const store = new MonitorStore();
7457
+ const monitorRegistry = new MonitorRegistry({ runtimeDir: monitorConfig.runtimeDir });
7458
+ monitorLifecycle = createMonitorLifecycle({
7459
+ registry: monitorRegistry,
7460
+ treeKill: killPiTree,
7461
+ wait: (proc: ChildProcess) => new Promise<boolean>((resolve) => proc.once("close", () => resolve(true))),
7462
+ getRecoveryEvidence: async (task: any) => {
7463
+ if (task?.ownerSessionId) {
7464
+ const evidence = monitorRegistry.evidenceForOwner(task.ownerSessionId, task.hubInstanceId ?? stableHubId);
7465
+ if (evidence.transient) return { transient: true };
7466
+ const herdr = await monitorReconcileEvidence({
7467
+ hubId: task.hubInstanceId ?? stableHubId,
7468
+ currentHubId: stableHubId,
7469
+ paneId: process.env.HERDR_PANE_ID,
7470
+ workspaceId: process.env.HERDR_WORKSPACE_ID,
7471
+ herdr: {
7472
+ pane: { get: async (id: string) => (await herdrApi.paneGet(id)).pane },
7473
+ workspace: { get: async (id: string) => {
7474
+ const panes = await herdrApi.paneList({ workspace_id: id });
7475
+ return panes.panes.length ? { id } : null;
7476
+ } },
7477
+ },
7478
+ });
7479
+ return {
7480
+ oldOwner: evidence.owner,
7481
+ oldSocket: evidence.socket,
7482
+ oldSession: evidence.session,
7483
+ oldHerdr: herdr.herdr,
7484
+ transient: herdr.transient,
7485
+ };
7486
+ }
7487
+ return monitorReconcileEvidence({
7488
+ owner: monitorLifecycle?.isAlive(),
7489
+ socket: monitorLifecycle?.isAlive(),
7490
+ session: true,
7491
+ hubId: stableHubId,
7492
+ currentHubId: stableHubId,
7493
+ paneId: process.env.HERDR_PANE_ID,
7494
+ workspaceId: process.env.HERDR_WORKSPACE_ID,
7495
+ herdr: {
7496
+ pane: { get: async (id: string) => (await herdrApi.paneGet(id)).pane },
7497
+ workspace: { get: async (id: string) => {
7498
+ const panes = await herdrApi.paneList({ workspace_id: id });
7499
+ return panes.panes.length ? { id } : null;
7500
+ } },
7501
+ },
7502
+ });
7503
+ },
7504
+ });
7505
+ monitorBridge = createMonitorSessionBridge({
7506
+ runtime: new MonitorRuntime({
7507
+ runtimeDir: monitorConfig.runtimeDir,
7508
+ profileId: monitorConfig.profileId,
7509
+ hubInstanceId: stableHubId,
7510
+ }),
7511
+ registerOwnedProcess: (_key: string, process: ChildProcess, task: any) => monitorLifecycle?.registerOwnedGeneration({
7512
+ taskId: task.id,
7513
+ generation: task.generation,
7514
+ process,
7515
+ }),
7516
+ cancelOwnedProcess: (request: any) => monitorLifecycle?.lowLevelCancelOwnedGeneration(request) ?? {
7517
+ cancelled: false,
7518
+ reason: "unsupported",
7519
+ },
7520
+ });
7521
+ if (!monitorBridge.snapshot().tasks.some((task: any) => task.kind === "parent")) monitorBridge.startParent({ id: `hub-turn-${stableHubId}`, hubInstanceId: stableHubId, checkoutId: _ctx.cwd || process.cwd() });
7522
+ await monitorLifecycle.startBridge(monitorBridge, { profilePath: monitorConfig.profilePath, profileId: monitorConfig.profileId, hubInstanceId: stableHubId });
7523
+ } catch (error) {
7524
+ monitorLifecycle = null;
7525
+ _ctx.ui.notify(`Agent Fleet monitor disabled: ${error instanceof Error ? error.message : String(error)}`, "warning");
7526
+ }
7527
+ }
7528
+
6599
7529
  // ── Embedded coms init ──
6600
7530
  // Always refresh the ctx the coms handlers use. Bind the endpoint + register
6601
7531
  // in the pool exactly once per process (guard on comsReady), so a /new session
@@ -6745,6 +7675,17 @@ ${researchCatalog}`;
6745
7675
  // Load per-project overrides (user-facing language, persona gate, models).
6746
7676
  const overrides = parseAgentTeamOverrides(_ctx.cwd);
6747
7677
  userLanguage = overrides.language;
7678
+ researchKeep = overrides.researchKeep;
7679
+ reconSearchTimeoutMs = overrides.reconSearchTimeoutMs;
7680
+ hubMode = overrides.hubMode;
7681
+ budgetOverrides = overrides.budgetOverrides;
7682
+ watchdogSetting = overrides.watchdogSetting;
7683
+ watchdogJudgeModel = overrides.watchdogJudgeModel;
7684
+ turnDispatchCount = 0;
7685
+ turnResearchCount = 0;
7686
+ turnTaskTier = null;
7687
+ turnDispatchFingerprints.clear();
7688
+ updateModeStatus();
6748
7689
  if (overrides.warnings.length > 0) {
6749
7690
  _ctx.ui.notify(`agent-fleet-overrides warnings:\n${overrides.warnings.join("\n")}`, "warning");
6750
7691
  }
@@ -6846,7 +7787,7 @@ ${researchCatalog}`;
6846
7787
  // The coms_* tools when the peer layer bound successfully; ask_user only when
6847
7788
  // pi-ask-user is installed. Per decision G4 the dispatcher persona NEVER narrows
6848
7789
  // this surface.
6849
- const dispatcherTools = ["dispatch_agent", "spawn_research", "set_assertions", "update_assertion", "get_assertions"];
7790
+ const dispatcherTools = ["dispatch_agent", "spawn_research", "set_task_tier", "team_adjust", "set_assertions", "update_assertion", "get_assertions"];
6850
7791
  if (comsReady) dispatcherTools.push("coms_list", "coms_send", "coms_get", "coms_await");
6851
7792
  if (askUserAvailable) dispatcherTools.push("ask_user");
6852
7793
  // Fleet tools only inside a herdr pane with a live server (graceful
@@ -6935,9 +7876,7 @@ ${researchCatalog}`;
6935
7876
  const filled = Math.round(pct / 10);
6936
7877
  const bar = "#".repeat(filled) + "-".repeat(10 - filled);
6937
7878
 
6938
- const left = theme.fg("dim", ` ${model}${think}`) +
6939
- theme.fg("muted", " · ") +
6940
- theme.fg("accent", activeTeamName);
7879
+ const left = renderHubFooterLeft(theme, HARNESS_VERSION, model, think, activeTeamName);
6941
7880
  const hint = theme.fg("muted", "Alt+A ") + theme.fg("dim", `view:${viewMode}`);
6942
7881
  // The btw extension flips this global the first time a /btw command or
6943
7882
  // Alt+' is used; surface its reopen shortcut right next to the Alt+A hint.
@@ -7067,6 +8006,14 @@ ${researchCatalog}`;
7067
8006
  try { server.close(); } catch { /* ignore */ }
7068
8007
  server = null;
7069
8008
  }
8009
+ if (monitorBridge) { try { await monitorBridge.cancelAllWaitOnly(); } catch { /* ignore */ } }
8010
+ if (monitorLifecycle) {
8011
+ try { await monitorLifecycle.stop(); } catch { /* ignore */ }
8012
+ monitorLifecycle = null;
8013
+ }
8014
+ monitorBridge?.reset();
8015
+ monitorBridge?.stop();
8016
+ monitorBridge = null;
7070
8017
  if (identity) {
7071
8018
  if (process.platform !== "win32") {
7072
8019
  try { fs.unlinkSync(identity.endpoint); } catch { /* ignore */ }