@chankov/agent-fleet 0.0.5 → 0.0.7

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 (695) hide show
  1. package/.claude/commands/set-hermes-watchdog.md +6 -0
  2. package/.opencode/commands/af-set-hermes-watchdog.md +6 -0
  3. package/.pi/extensions/agent-fleet-update-check/README.md +4 -4
  4. package/.pi/extensions/btw/README.md +10 -10
  5. package/.pi/extensions/btw/index.ts +11 -11
  6. package/.pi/extensions/chrome-devtools-mcp/README.md +2 -2
  7. package/.pi/extensions/chrome-devtools-mcp/index.ts +1 -0
  8. package/.pi/extensions/compact-and-continue/README.md +2 -2
  9. package/.pi/extensions/pi-voice-stt/README.md +7 -7
  10. package/.pi/extensions/pi-voice-stt/index.ts +4 -4
  11. package/.pi/harnesses/agent-hub/README.md +133 -74
  12. package/.pi/harnesses/agent-hub/artifacts.js +56 -2
  13. package/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  14. package/.pi/harnesses/agent-hub/backend-policy.js +1 -1
  15. package/.pi/harnesses/agent-hub/context-window.js +106 -0
  16. package/.pi/harnesses/agent-hub/delegate.ts +61 -12
  17. package/.pi/harnesses/agent-hub/drift-watchdog.js +55 -9
  18. package/.pi/harnesses/agent-hub/helpers.ts +34 -0
  19. package/.pi/harnesses/agent-hub/index.ts +970 -406
  20. package/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  21. package/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  22. package/.pi/harnesses/agent-hub/monitor-lifecycle.ts +2 -2
  23. package/.pi/harnesses/agent-hub/monitor-session-bridge.ts +257 -11
  24. package/.pi/harnesses/agent-hub/package.json +1 -1
  25. package/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  26. package/.pi/harnesses/agent-hub/return-contract.js +78 -0
  27. package/.pi/harnesses/agent-hub/return-extract.js +75 -0
  28. package/.pi/harnesses/agent-hub/run-budget.js +30 -4
  29. package/.pi/harnesses/agent-hub/session-health.js +110 -0
  30. package/.pi/harnesses/agent-hub/spawn.ts +109 -1
  31. package/.pi/harnesses/agent-hub/spawned-peers.js +74 -0
  32. package/.pi/harnesses/coms/README.md +6 -5
  33. package/.pi/harnesses/coms/index.ts +92 -70
  34. package/.pi/harnesses/coms/package.json +1 -1
  35. package/.pi/harnesses/damage-control-continue/README.md +9 -9
  36. package/.pi/harnesses/damage-control-continue/index.ts +11 -11
  37. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  38. package/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  39. package/.pi/harnesses/lib/herdr-client.ts +7 -2
  40. package/.pi/harnesses/lib/herdr-presence.ts +141 -30
  41. package/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  42. package/.pi/harnesses/lib/hermes-monitor-model.ts +9 -0
  43. package/.pi/harnesses/lib/hermes-monitor-registry.ts +1 -1
  44. package/.pi/harnesses/lib/hermes-monitor-socket.ts +47 -2
  45. package/.pi/prompts/{doctor-agent-fleet.md → af-doctor-agent-fleet.md} +1 -1
  46. package/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  47. package/.pi/prompts/{setup-agent-fleet.md → af-setup-agent-fleet.md} +1 -1
  48. package/.versions/0.0.6/.claude/commands/build.md +44 -0
  49. package/.versions/0.0.6/.claude/commands/code-simplify.md +22 -0
  50. package/.versions/0.0.6/.claude/commands/design-agent.md +14 -0
  51. package/.versions/0.0.6/.claude/commands/doctor-agent-fleet.md +17 -0
  52. package/.versions/0.0.6/.claude/commands/orchestrate.md +112 -0
  53. package/.versions/0.0.6/.claude/commands/plan.md +16 -0
  54. package/.versions/0.0.6/.claude/commands/prime.md +22 -0
  55. package/.versions/0.0.6/.claude/commands/review.md +16 -0
  56. package/.versions/0.0.6/.claude/commands/set-hermes-telegram.md +15 -0
  57. package/.versions/0.0.6/.claude/commands/setup-agent-fleet.md +25 -0
  58. package/.versions/0.0.6/.claude/commands/ship.md +72 -0
  59. package/.versions/0.0.6/.claude/commands/spec.md +15 -0
  60. package/.versions/0.0.6/.claude/commands/test.md +19 -0
  61. package/.versions/0.0.6/.claude/commands/webperf.md +32 -0
  62. package/.versions/0.0.6/.claude/orchestrate-teams.yaml +24 -0
  63. package/.versions/0.0.6/.opencode/commands/af-build.md +17 -0
  64. package/.versions/0.0.6/.opencode/commands/af-code-simplify.md +16 -0
  65. package/.versions/0.0.6/.opencode/commands/af-compound.md +16 -0
  66. package/.versions/0.0.6/.opencode/commands/af-design-agent.md +15 -0
  67. package/.versions/0.0.6/.opencode/commands/af-doctor-agent-fleet.md +17 -0
  68. package/.versions/0.0.6/.opencode/commands/af-orchestrate.md +112 -0
  69. package/.versions/0.0.6/.opencode/commands/af-plan.md +16 -0
  70. package/.versions/0.0.6/.opencode/commands/af-prime.md +22 -0
  71. package/.versions/0.0.6/.opencode/commands/af-review.md +15 -0
  72. package/.versions/0.0.6/.opencode/commands/af-set-hermes-telegram.md +15 -0
  73. package/.versions/0.0.6/.opencode/commands/af-setup-agent-fleet.md +15 -0
  74. package/.versions/0.0.6/.opencode/commands/af-ship.md +16 -0
  75. package/.versions/0.0.6/.opencode/commands/af-spec.md +16 -0
  76. package/.versions/0.0.6/.opencode/commands/af-test.md +21 -0
  77. package/.versions/0.0.6/.opencode/commands/af-webperf.md +32 -0
  78. package/.versions/0.0.6/.opencode/orchestrate-teams.yaml +24 -0
  79. package/.versions/0.0.6/.pi/agents/dispatch-policy.yaml +32 -0
  80. package/.versions/0.0.6/.pi/agents/model-profiles.yaml +20 -0
  81. package/.versions/0.0.6/.pi/agents/peers.yaml +146 -0
  82. package/.versions/0.0.6/.pi/agents/teams.yaml +39 -0
  83. package/.versions/0.0.6/.pi/damage-control-rules.yaml +297 -0
  84. package/.versions/0.0.6/.pi/extensions/agent-fleet-update-check/README.md +58 -0
  85. package/.versions/0.0.6/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  86. package/.versions/0.0.6/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  87. package/.versions/0.0.6/.pi/extensions/btw/README.md +118 -0
  88. package/.versions/0.0.6/.pi/extensions/btw/index.ts +917 -0
  89. package/.versions/0.0.6/.pi/extensions/btw/package.json +6 -0
  90. package/.versions/0.0.6/.pi/extensions/btw/state.js +179 -0
  91. package/.versions/0.0.6/.pi/extensions/chrome-devtools-mcp/README.md +58 -0
  92. package/.versions/0.0.6/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  93. package/.versions/0.0.6/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  94. package/.versions/0.0.6/.pi/extensions/compact-and-continue/README.md +42 -0
  95. package/.versions/0.0.6/.pi/extensions/compact-and-continue/index.ts +120 -0
  96. package/.versions/0.0.6/.pi/extensions/compact-and-continue/package.json +6 -0
  97. package/.versions/0.0.6/.pi/extensions/mcp-bridge/README.md +46 -0
  98. package/.versions/0.0.6/.pi/extensions/mcp-bridge/index.ts +206 -0
  99. package/.versions/0.0.6/.pi/extensions/mcp-bridge/package.json +6 -0
  100. package/.versions/0.0.6/.pi/extensions/package-lock.json +1143 -0
  101. package/.versions/0.0.6/.pi/extensions/package.json +9 -0
  102. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/README.md +201 -0
  103. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/config.ts +198 -0
  104. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  105. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/index.ts +248 -0
  106. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/package.json +6 -0
  107. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  108. package/.versions/0.0.6/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  109. package/.versions/0.0.6/.pi/harnesses/agent-hub/README.md +798 -0
  110. package/.versions/0.0.6/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  111. package/.versions/0.0.6/.pi/harnesses/agent-hub/artifacts.js +92 -0
  112. package/.versions/0.0.6/.pi/harnesses/agent-hub/backend-policy.js +153 -0
  113. package/.versions/0.0.6/.pi/harnesses/agent-hub/delegate.ts +386 -0
  114. package/.versions/0.0.6/.pi/harnesses/agent-hub/drift-watchdog.js +165 -0
  115. package/.versions/0.0.6/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  116. package/.versions/0.0.6/.pi/harnesses/agent-hub/footer.ts +29 -0
  117. package/.versions/0.0.6/.pi/harnesses/agent-hub/helpers.ts +214 -0
  118. package/.versions/0.0.6/.pi/harnesses/agent-hub/index.ts +8045 -0
  119. package/.versions/0.0.6/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  120. package/.versions/0.0.6/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  121. package/.versions/0.0.6/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  122. package/.versions/0.0.6/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  123. package/.versions/0.0.6/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  124. package/.versions/0.0.6/.pi/harnesses/agent-hub/monitor-session-bridge.ts +11 -0
  125. package/.versions/0.0.6/.pi/harnesses/agent-hub/package.json +7 -0
  126. package/.versions/0.0.6/.pi/harnesses/agent-hub/research-retention.js +34 -0
  127. package/.versions/0.0.6/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  128. package/.versions/0.0.6/.pi/harnesses/agent-hub/return-contract.js +215 -0
  129. package/.versions/0.0.6/.pi/harnesses/agent-hub/run-budget.js +155 -0
  130. package/.versions/0.0.6/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  131. package/.versions/0.0.6/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  132. package/.versions/0.0.6/.pi/harnesses/agent-hub/spawn.ts +246 -0
  133. package/.versions/0.0.6/.pi/harnesses/agent-hub/version.ts +18 -0
  134. package/.versions/0.0.6/.pi/harnesses/ask-user-remote/README.md +19 -0
  135. package/.versions/0.0.6/.pi/harnesses/ask-user-remote/index.ts +321 -0
  136. package/.versions/0.0.6/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  137. package/.versions/0.0.6/.pi/harnesses/coms/README.md +92 -0
  138. package/.versions/0.0.6/.pi/harnesses/coms/index.ts +1745 -0
  139. package/.versions/0.0.6/.pi/harnesses/coms/package.json +7 -0
  140. package/.versions/0.0.6/.pi/harnesses/coms/version.ts +18 -0
  141. package/.versions/0.0.6/.pi/harnesses/damage-control-continue/README.md +117 -0
  142. package/.versions/0.0.6/.pi/harnesses/damage-control-continue/index.ts +536 -0
  143. package/.versions/0.0.6/.pi/harnesses/damage-control-continue/package.json +7 -0
  144. package/.versions/0.0.6/.pi/harnesses/damage-control-continue/version.ts +18 -0
  145. package/.versions/0.0.6/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  146. package/.versions/0.0.6/.pi/harnesses/lib/herdr-client.ts +458 -0
  147. package/.versions/0.0.6/.pi/harnesses/lib/herdr-presence.ts +288 -0
  148. package/.versions/0.0.6/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  149. package/.versions/0.0.6/.pi/harnesses/lib/hermes-monitor-model.ts +9 -0
  150. package/.versions/0.0.6/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  151. package/.versions/0.0.6/.pi/harnesses/lib/hermes-monitor-socket.ts +118 -0
  152. package/.versions/0.0.6/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  153. package/.versions/0.0.6/.pi/harnesses/package-lock.json +35 -0
  154. package/.versions/0.0.6/.pi/harnesses/package.json +9 -0
  155. package/.versions/0.0.6/.pi/prompts/af-build.md +24 -0
  156. package/.versions/0.0.6/.pi/prompts/af-code-simplify.md +22 -0
  157. package/.versions/0.0.6/.pi/prompts/af-doctor-agent-fleet.md +15 -0
  158. package/.versions/0.0.6/.pi/prompts/af-plan.md +16 -0
  159. package/.versions/0.0.6/.pi/prompts/af-review.md +16 -0
  160. package/.versions/0.0.6/.pi/prompts/af-set-hermes-telegram.md +15 -0
  161. package/.versions/0.0.6/.pi/prompts/af-setup-agent-fleet.md +27 -0
  162. package/.versions/0.0.6/.pi/prompts/af-ship.md +17 -0
  163. package/.versions/0.0.6/.pi/prompts/af-spec.md +15 -0
  164. package/.versions/0.0.6/.pi/prompts/af-test.md +19 -0
  165. package/.versions/0.0.6/.pi/skills/bowser/SKILL.md +145 -0
  166. package/.versions/0.0.6/.version +1 -0
  167. package/.versions/0.0.6/agents/architect.md +23 -0
  168. package/.versions/0.0.6/agents/bowser.md +26 -0
  169. package/.versions/0.0.6/agents/builder.md +53 -0
  170. package/.versions/0.0.6/agents/code-reviewer.md +205 -0
  171. package/.versions/0.0.6/agents/deep-researcher.md +31 -0
  172. package/.versions/0.0.6/agents/documenter.md +18 -0
  173. package/.versions/0.0.6/agents/orchestrator.md +54 -0
  174. package/.versions/0.0.6/agents/plan-reviewer.md +60 -0
  175. package/.versions/0.0.6/agents/planner.md +69 -0
  176. package/.versions/0.0.6/agents/releaser.md +24 -0
  177. package/.versions/0.0.6/agents/researcher.md +28 -0
  178. package/.versions/0.0.6/agents/security-auditor.md +166 -0
  179. package/.versions/0.0.6/agents/test-engineer.md +151 -0
  180. package/.versions/0.0.6/agents/web-debugger.md +42 -0
  181. package/.versions/0.0.6/agents/web-performance-auditor.md +192 -0
  182. package/.versions/0.0.6/codex/CONDUCTOR.md +148 -0
  183. package/.versions/0.0.6/docs/ARCHITECTURE.md +210 -0
  184. package/.versions/0.0.6/docs/agent-fleet-setup.md +366 -0
  185. package/.versions/0.0.6/docs/claude-code-coms-bridge.md +103 -0
  186. package/.versions/0.0.6/docs/codex-remote-conductor.md +170 -0
  187. package/.versions/0.0.6/docs/coms-hermes-bridge.md +179 -0
  188. package/.versions/0.0.6/docs/getting-started.md +183 -0
  189. package/.versions/0.0.6/docs/npm-install.md +337 -0
  190. package/.versions/0.0.6/docs/opencode-setup.md +249 -0
  191. package/.versions/0.0.6/docs/pi-extensions.md +293 -0
  192. package/.versions/0.0.6/docs/pi-setup.md +476 -0
  193. package/.versions/0.0.6/docs/skill-anatomy.md +150 -0
  194. package/.versions/0.0.6/hermes/README.md +231 -0
  195. package/.versions/0.0.6/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  196. package/.versions/0.0.6/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  197. package/.versions/0.0.6/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +151 -0
  198. package/.versions/0.0.6/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  199. package/.versions/0.0.6/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  200. package/.versions/0.0.6/hermes/skills/hub-conductor/SKILL.md +84 -0
  201. package/.versions/0.0.6/hermes/skills/hub-liaison/SKILL.md +84 -0
  202. package/.versions/0.0.6/hooks/SIMPLIFY-IGNORE.md +90 -0
  203. package/.versions/0.0.6/hooks/coms-stop-hook.mjs +73 -0
  204. package/.versions/0.0.6/hooks/hooks.json +14 -0
  205. package/.versions/0.0.6/hooks/session-start.sh +74 -0
  206. package/.versions/0.0.6/hooks/simplify-ignore.sh +302 -0
  207. package/.versions/0.0.6/justfile +245 -0
  208. package/.versions/0.0.6/references/accessibility-checklist.md +160 -0
  209. package/.versions/0.0.6/references/definition-of-done.md +67 -0
  210. package/.versions/0.0.6/references/fleet-coordination-patterns.md +151 -0
  211. package/.versions/0.0.6/references/observability-checklist.md +91 -0
  212. package/.versions/0.0.6/references/orchestration-patterns.md +370 -0
  213. package/.versions/0.0.6/references/performance-checklist.md +153 -0
  214. package/.versions/0.0.6/references/prompting-patterns.md +380 -0
  215. package/.versions/0.0.6/references/security-checklist.md +179 -0
  216. package/.versions/0.0.6/references/testing-patterns.md +236 -0
  217. package/.versions/0.0.6/scripts/codex-conductor.ts +41 -0
  218. package/.versions/0.0.6/scripts/codex-remote-control.ts +167 -0
  219. package/.versions/0.0.6/scripts/coms-claude-bridge.ts +286 -0
  220. package/.versions/0.0.6/scripts/coms-cli.ts +484 -0
  221. package/.versions/0.0.6/scripts/coms-hermes-bridge.ts +413 -0
  222. package/.versions/0.0.6/scripts/fleet.ts +141 -0
  223. package/.versions/0.0.6/scripts/hermes-monitor-capability-runner.ts +25 -0
  224. package/.versions/0.0.6/scripts/hermes-monitor-scenario.ts +7 -0
  225. package/.versions/0.0.6/scripts/lib/claude-bridge-core.ts +100 -0
  226. package/.versions/0.0.6/scripts/lib/codex-conductor.ts +88 -0
  227. package/.versions/0.0.6/scripts/lib/codex-remote-control.ts +480 -0
  228. package/.versions/0.0.6/scripts/lib/coms-envelope.ts +539 -0
  229. package/.versions/0.0.6/scripts/lib/fake-herdr-server.ts +88 -0
  230. package/.versions/0.0.6/scripts/lib/fleet-command.ts +109 -0
  231. package/.versions/0.0.6/scripts/lib/herdr-layout.ts +263 -0
  232. package/.versions/0.0.6/scripts/lib/hermes-bridge-core.ts +241 -0
  233. package/.versions/0.0.6/scripts/lib/hermes-monitor-herdr.ts +2 -0
  234. package/.versions/0.0.6/scripts/lib/hermes-monitor-model.ts +3 -0
  235. package/.versions/0.0.6/scripts/lib/hermes-monitor-registry.ts +2 -0
  236. package/.versions/0.0.6/scripts/lib/hermes-monitor-socket.ts +2 -0
  237. package/.versions/0.0.6/scripts/lib/hermes-monitor-store.ts +2 -0
  238. package/.versions/0.0.6/scripts/lib/persona-banner.ts +62 -0
  239. package/.versions/0.0.6/scripts/lib/spawn-stagger.ts +101 -0
  240. package/.versions/0.0.6/scripts/lib/team-project.ts +191 -0
  241. package/.versions/0.0.6/scripts/lib/team-snapshot.ts +147 -0
  242. package/.versions/0.0.6/scripts/peer-banner.ts +40 -0
  243. package/.versions/0.0.6/scripts/team-snapshot.ts +237 -0
  244. package/.versions/0.0.6/scripts/team-up.ts +351 -0
  245. package/.versions/0.0.6/skills/_internal/grilling.md +11 -0
  246. package/.versions/0.0.6/skills/browser-testing-with-devtools/SKILL.md +352 -0
  247. package/.versions/0.0.6/skills/code-review-and-quality/SKILL.md +381 -0
  248. package/.versions/0.0.6/skills/compound-learning/SKILL.md +137 -0
  249. package/.versions/0.0.6/skills/context-engineering/SKILL.md +291 -0
  250. package/.versions/0.0.6/skills/deprecation-and-migration/SKILL.md +206 -0
  251. package/.versions/0.0.6/skills/designing-agents/SKILL.md +394 -0
  252. package/.versions/0.0.6/skills/designing-agents/pi-harness-authoring.md +222 -0
  253. package/.versions/0.0.6/skills/frontend-ui-engineering/SKILL.md +328 -0
  254. package/.versions/0.0.6/skills/git-workflow-and-versioning/SKILL.md +316 -0
  255. package/.versions/0.0.6/skills/guided-workspace-setup/SKILL.md +544 -0
  256. package/.versions/0.0.6/skills/guided-workspace-setup/companion-manifest.json +35 -0
  257. package/.versions/0.0.6/skills/idea-refine/SKILL.md +182 -0
  258. package/.versions/0.0.6/skills/idea-refine/examples.md +238 -0
  259. package/.versions/0.0.6/skills/idea-refine/frameworks.md +99 -0
  260. package/.versions/0.0.6/skills/idea-refine/refinement-criteria.md +113 -0
  261. package/.versions/0.0.6/skills/idea-refine/scripts/idea-refine.sh +15 -0
  262. package/.versions/0.0.6/skills/incremental-implementation/SKILL.md +287 -0
  263. package/.versions/0.0.6/skills/interview-me/SKILL.md +226 -0
  264. package/.versions/0.0.6/skills/orchestration-verification/SKILL.md +181 -0
  265. package/.versions/0.0.6/skills/peer-coms/SKILL.md +90 -0
  266. package/.versions/0.0.6/skills/performance-optimization/SKILL.md +350 -0
  267. package/.versions/0.0.6/skills/planning-and-task-breakdown/SKILL.md +236 -0
  268. package/.versions/0.0.6/skills/security-and-hardening/SKILL.md +461 -0
  269. package/.versions/0.0.6/skills/spec-driven-development/SKILL.md +245 -0
  270. package/.versions/0.0.6/skills/using-agent-skills/SKILL.md +199 -0
  271. package/.versions/0.0.6/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  272. package/.versions/0.0.6/vendor/agent-skills-upstream/LICENSE +21 -0
  273. package/.versions/0.0.6/vendor/agent-skills-upstream/README.md +11 -0
  274. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  275. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  276. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  277. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  278. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  279. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  280. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  281. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  282. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  283. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  284. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  285. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  286. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  287. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  288. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  289. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  290. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  291. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  292. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  293. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  294. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  295. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  296. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  297. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  298. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  299. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  300. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  301. package/.versions/0.0.6/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  302. package/.versions/0.0.7/.claude/commands/build.md +44 -0
  303. package/.versions/0.0.7/.claude/commands/code-simplify.md +22 -0
  304. package/.versions/0.0.7/.claude/commands/design-agent.md +14 -0
  305. package/.versions/0.0.7/.claude/commands/doctor-agent-fleet.md +17 -0
  306. package/.versions/0.0.7/.claude/commands/orchestrate.md +112 -0
  307. package/.versions/0.0.7/.claude/commands/plan.md +16 -0
  308. package/.versions/0.0.7/.claude/commands/prime.md +22 -0
  309. package/.versions/0.0.7/.claude/commands/review.md +16 -0
  310. package/.versions/0.0.7/.claude/commands/set-hermes-telegram.md +15 -0
  311. package/.versions/0.0.7/.claude/commands/set-hermes-watchdog.md +6 -0
  312. package/.versions/0.0.7/.claude/commands/setup-agent-fleet.md +25 -0
  313. package/.versions/0.0.7/.claude/commands/ship.md +72 -0
  314. package/.versions/0.0.7/.claude/commands/spec.md +15 -0
  315. package/.versions/0.0.7/.claude/commands/test.md +19 -0
  316. package/.versions/0.0.7/.claude/commands/webperf.md +32 -0
  317. package/.versions/0.0.7/.claude/orchestrate-teams.yaml +24 -0
  318. package/.versions/0.0.7/.opencode/commands/af-build.md +17 -0
  319. package/.versions/0.0.7/.opencode/commands/af-code-simplify.md +16 -0
  320. package/.versions/0.0.7/.opencode/commands/af-compound.md +16 -0
  321. package/.versions/0.0.7/.opencode/commands/af-design-agent.md +15 -0
  322. package/.versions/0.0.7/.opencode/commands/af-doctor-agent-fleet.md +17 -0
  323. package/.versions/0.0.7/.opencode/commands/af-orchestrate.md +112 -0
  324. package/.versions/0.0.7/.opencode/commands/af-plan.md +16 -0
  325. package/.versions/0.0.7/.opencode/commands/af-prime.md +22 -0
  326. package/.versions/0.0.7/.opencode/commands/af-review.md +15 -0
  327. package/.versions/0.0.7/.opencode/commands/af-set-hermes-telegram.md +15 -0
  328. package/.versions/0.0.7/.opencode/commands/af-set-hermes-watchdog.md +6 -0
  329. package/.versions/0.0.7/.opencode/commands/af-setup-agent-fleet.md +15 -0
  330. package/.versions/0.0.7/.opencode/commands/af-ship.md +16 -0
  331. package/.versions/0.0.7/.opencode/commands/af-spec.md +16 -0
  332. package/.versions/0.0.7/.opencode/commands/af-test.md +21 -0
  333. package/.versions/0.0.7/.opencode/commands/af-webperf.md +32 -0
  334. package/.versions/0.0.7/.opencode/orchestrate-teams.yaml +24 -0
  335. package/.versions/0.0.7/.pi/agents/dispatch-policy.yaml +32 -0
  336. package/.versions/0.0.7/.pi/agents/model-profiles.yaml +20 -0
  337. package/.versions/0.0.7/.pi/agents/peers.yaml +146 -0
  338. package/.versions/0.0.7/.pi/agents/teams.yaml +39 -0
  339. package/.versions/0.0.7/.pi/damage-control-rules.yaml +297 -0
  340. package/.versions/0.0.7/.pi/extensions/agent-fleet-update-check/README.md +58 -0
  341. package/.versions/0.0.7/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  342. package/.versions/0.0.7/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  343. package/.versions/0.0.7/.pi/extensions/btw/README.md +118 -0
  344. package/.versions/0.0.7/.pi/extensions/btw/index.ts +917 -0
  345. package/.versions/0.0.7/.pi/extensions/btw/package.json +6 -0
  346. package/.versions/0.0.7/.pi/extensions/btw/state.js +179 -0
  347. package/.versions/0.0.7/.pi/extensions/chrome-devtools-mcp/README.md +58 -0
  348. package/.versions/0.0.7/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  349. package/.versions/0.0.7/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  350. package/.versions/0.0.7/.pi/extensions/compact-and-continue/README.md +42 -0
  351. package/.versions/0.0.7/.pi/extensions/compact-and-continue/index.ts +120 -0
  352. package/.versions/0.0.7/.pi/extensions/compact-and-continue/package.json +6 -0
  353. package/.versions/0.0.7/.pi/extensions/mcp-bridge/README.md +46 -0
  354. package/.versions/0.0.7/.pi/extensions/mcp-bridge/index.ts +206 -0
  355. package/.versions/0.0.7/.pi/extensions/mcp-bridge/package.json +6 -0
  356. package/.versions/0.0.7/.pi/extensions/package-lock.json +1143 -0
  357. package/.versions/0.0.7/.pi/extensions/package.json +9 -0
  358. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/README.md +201 -0
  359. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/config.ts +198 -0
  360. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  361. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/index.ts +248 -0
  362. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/package.json +6 -0
  363. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  364. package/.versions/0.0.7/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  365. package/.versions/0.0.7/.pi/harnesses/agent-hub/README.md +857 -0
  366. package/.versions/0.0.7/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  367. package/.versions/0.0.7/.pi/harnesses/agent-hub/artifacts.js +146 -0
  368. package/.versions/0.0.7/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  369. package/.versions/0.0.7/.pi/harnesses/agent-hub/backend-policy.js +153 -0
  370. package/.versions/0.0.7/.pi/harnesses/agent-hub/context-window.js +106 -0
  371. package/.versions/0.0.7/.pi/harnesses/agent-hub/delegate.ts +435 -0
  372. package/.versions/0.0.7/.pi/harnesses/agent-hub/drift-watchdog.js +211 -0
  373. package/.versions/0.0.7/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  374. package/.versions/0.0.7/.pi/harnesses/agent-hub/footer.ts +29 -0
  375. package/.versions/0.0.7/.pi/harnesses/agent-hub/helpers.ts +248 -0
  376. package/.versions/0.0.7/.pi/harnesses/agent-hub/index.ts +8609 -0
  377. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  378. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  379. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  380. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  381. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  382. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  383. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  384. package/.versions/0.0.7/.pi/harnesses/agent-hub/monitor-session-bridge.ts +257 -0
  385. package/.versions/0.0.7/.pi/harnesses/agent-hub/package.json +7 -0
  386. package/.versions/0.0.7/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  387. package/.versions/0.0.7/.pi/harnesses/agent-hub/research-retention.js +34 -0
  388. package/.versions/0.0.7/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  389. package/.versions/0.0.7/.pi/harnesses/agent-hub/return-contract.js +293 -0
  390. package/.versions/0.0.7/.pi/harnesses/agent-hub/return-extract.js +75 -0
  391. package/.versions/0.0.7/.pi/harnesses/agent-hub/run-budget.js +181 -0
  392. package/.versions/0.0.7/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  393. package/.versions/0.0.7/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  394. package/.versions/0.0.7/.pi/harnesses/agent-hub/session-health.js +110 -0
  395. package/.versions/0.0.7/.pi/harnesses/agent-hub/spawn.ts +354 -0
  396. package/.versions/0.0.7/.pi/harnesses/agent-hub/spawned-peers.js +74 -0
  397. package/.versions/0.0.7/.pi/harnesses/agent-hub/version.ts +18 -0
  398. package/.versions/0.0.7/.pi/harnesses/ask-user-remote/README.md +19 -0
  399. package/.versions/0.0.7/.pi/harnesses/ask-user-remote/index.ts +321 -0
  400. package/.versions/0.0.7/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  401. package/.versions/0.0.7/.pi/harnesses/coms/README.md +93 -0
  402. package/.versions/0.0.7/.pi/harnesses/coms/index.ts +1767 -0
  403. package/.versions/0.0.7/.pi/harnesses/coms/package.json +7 -0
  404. package/.versions/0.0.7/.pi/harnesses/coms/version.ts +18 -0
  405. package/.versions/0.0.7/.pi/harnesses/damage-control-continue/README.md +117 -0
  406. package/.versions/0.0.7/.pi/harnesses/damage-control-continue/index.ts +536 -0
  407. package/.versions/0.0.7/.pi/harnesses/damage-control-continue/package.json +7 -0
  408. package/.versions/0.0.7/.pi/harnesses/damage-control-continue/version.ts +18 -0
  409. package/.versions/0.0.7/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  410. package/.versions/0.0.7/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  411. package/.versions/0.0.7/.pi/harnesses/lib/herdr-client.ts +463 -0
  412. package/.versions/0.0.7/.pi/harnesses/lib/herdr-presence.ts +399 -0
  413. package/.versions/0.0.7/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  414. package/.versions/0.0.7/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  415. package/.versions/0.0.7/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  416. package/.versions/0.0.7/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  417. package/.versions/0.0.7/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  418. package/.versions/0.0.7/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  419. package/.versions/0.0.7/.pi/harnesses/package-lock.json +35 -0
  420. package/.versions/0.0.7/.pi/harnesses/package.json +9 -0
  421. package/.versions/0.0.7/.pi/prompts/af-build.md +24 -0
  422. package/.versions/0.0.7/.pi/prompts/af-code-simplify.md +22 -0
  423. package/.versions/0.0.7/.pi/prompts/af-doctor-agent-fleet.md +15 -0
  424. package/.versions/0.0.7/.pi/prompts/af-plan.md +16 -0
  425. package/.versions/0.0.7/.pi/prompts/af-review.md +16 -0
  426. package/.versions/0.0.7/.pi/prompts/af-set-hermes-telegram.md +15 -0
  427. package/.versions/0.0.7/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  428. package/.versions/0.0.7/.pi/prompts/af-setup-agent-fleet.md +27 -0
  429. package/.versions/0.0.7/.pi/prompts/af-ship.md +17 -0
  430. package/.versions/0.0.7/.pi/prompts/af-spec.md +15 -0
  431. package/.versions/0.0.7/.pi/prompts/af-test.md +19 -0
  432. package/.versions/0.0.7/.pi/skills/bowser/SKILL.md +145 -0
  433. package/.versions/0.0.7/.version +1 -0
  434. package/.versions/0.0.7/agents/architect.md +23 -0
  435. package/.versions/0.0.7/agents/bowser.md +26 -0
  436. package/.versions/0.0.7/agents/builder.md +53 -0
  437. package/.versions/0.0.7/agents/code-reviewer.md +205 -0
  438. package/.versions/0.0.7/agents/deep-researcher.md +31 -0
  439. package/.versions/0.0.7/agents/documenter.md +18 -0
  440. package/.versions/0.0.7/agents/orchestrator.md +65 -0
  441. package/.versions/0.0.7/agents/plan-reviewer.md +60 -0
  442. package/.versions/0.0.7/agents/planner.md +69 -0
  443. package/.versions/0.0.7/agents/releaser.md +24 -0
  444. package/.versions/0.0.7/agents/researcher.md +28 -0
  445. package/.versions/0.0.7/agents/security-auditor.md +166 -0
  446. package/.versions/0.0.7/agents/test-engineer.md +151 -0
  447. package/.versions/0.0.7/agents/web-debugger.md +42 -0
  448. package/.versions/0.0.7/agents/web-performance-auditor.md +192 -0
  449. package/.versions/0.0.7/codex/CONDUCTOR.md +148 -0
  450. package/.versions/0.0.7/docs/ARCHITECTURE.md +262 -0
  451. package/.versions/0.0.7/docs/agent-fleet-setup.md +366 -0
  452. package/.versions/0.0.7/docs/claude-code-coms-bridge.md +109 -0
  453. package/.versions/0.0.7/docs/codex-remote-conductor.md +170 -0
  454. package/.versions/0.0.7/docs/coms-hermes-bridge.md +189 -0
  455. package/.versions/0.0.7/docs/getting-started.md +231 -0
  456. package/.versions/0.0.7/docs/npm-install.md +337 -0
  457. package/.versions/0.0.7/docs/opencode-setup.md +249 -0
  458. package/.versions/0.0.7/docs/pi-extensions.md +293 -0
  459. package/.versions/0.0.7/docs/pi-setup.md +476 -0
  460. package/.versions/0.0.7/docs/skill-anatomy.md +150 -0
  461. package/.versions/0.0.7/hermes/README.md +347 -0
  462. package/.versions/0.0.7/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  463. package/.versions/0.0.7/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  464. package/.versions/0.0.7/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  465. package/.versions/0.0.7/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  466. package/.versions/0.0.7/hermes/gates/gate-o-capability.md +8 -0
  467. package/.versions/0.0.7/hermes/gates/gate-o-validator-fixtures.json +1 -0
  468. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  469. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  470. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  471. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  472. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  473. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  474. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  475. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  476. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  477. package/.versions/0.0.7/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  478. package/.versions/0.0.7/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  479. package/.versions/0.0.7/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  480. package/.versions/0.0.7/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  481. package/.versions/0.0.7/hermes/skills/hub-conductor/SKILL.md +84 -0
  482. package/.versions/0.0.7/hermes/skills/hub-liaison/SKILL.md +84 -0
  483. package/.versions/0.0.7/hermes/skills/hub-watchdog/SKILL.md +76 -0
  484. package/.versions/0.0.7/hermes/skills/hub-watchdog/manifest.json +1 -0
  485. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  486. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  487. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  488. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  489. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  490. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  491. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  492. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  493. package/.versions/0.0.7/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  494. package/.versions/0.0.7/hermes/watchdog-tests/__init__.py +0 -0
  495. package/.versions/0.0.7/hooks/SIMPLIFY-IGNORE.md +90 -0
  496. package/.versions/0.0.7/hooks/coms-stop-hook.mjs +84 -0
  497. package/.versions/0.0.7/hooks/hooks.json +14 -0
  498. package/.versions/0.0.7/hooks/session-start.sh +74 -0
  499. package/.versions/0.0.7/hooks/simplify-ignore.sh +302 -0
  500. package/.versions/0.0.7/justfile +245 -0
  501. package/.versions/0.0.7/references/accessibility-checklist.md +160 -0
  502. package/.versions/0.0.7/references/definition-of-done.md +67 -0
  503. package/.versions/0.0.7/references/fleet-coordination-patterns.md +151 -0
  504. package/.versions/0.0.7/references/observability-checklist.md +91 -0
  505. package/.versions/0.0.7/references/orchestration-patterns.md +370 -0
  506. package/.versions/0.0.7/references/performance-checklist.md +153 -0
  507. package/.versions/0.0.7/references/prompting-patterns.md +380 -0
  508. package/.versions/0.0.7/references/security-checklist.md +179 -0
  509. package/.versions/0.0.7/references/testing-patterns.md +236 -0
  510. package/.versions/0.0.7/scripts/codex-conductor.ts +41 -0
  511. package/.versions/0.0.7/scripts/codex-remote-control.ts +167 -0
  512. package/.versions/0.0.7/scripts/coms-claude-bridge.ts +401 -0
  513. package/.versions/0.0.7/scripts/coms-cli.ts +484 -0
  514. package/.versions/0.0.7/scripts/coms-hermes-bridge.ts +413 -0
  515. package/.versions/0.0.7/scripts/fleet.ts +149 -0
  516. package/.versions/0.0.7/scripts/hermes-monitor-capability-runner.ts +25 -0
  517. package/.versions/0.0.7/scripts/hermes-monitor-scenario.ts +474 -0
  518. package/.versions/0.0.7/scripts/hermes-watchdog-capability-probe.ts +45 -0
  519. package/.versions/0.0.7/scripts/install-hermes-plugin.sh +180 -0
  520. package/.versions/0.0.7/scripts/lib/claude-bridge-core.ts +165 -0
  521. package/.versions/0.0.7/scripts/lib/codex-conductor.ts +88 -0
  522. package/.versions/0.0.7/scripts/lib/codex-remote-control.ts +480 -0
  523. package/.versions/0.0.7/scripts/lib/coms-envelope.ts +582 -0
  524. package/.versions/0.0.7/scripts/lib/fake-herdr-server.ts +88 -0
  525. package/.versions/0.0.7/scripts/lib/fleet-command.ts +109 -0
  526. package/.versions/0.0.7/scripts/lib/herdr-layout.ts +263 -0
  527. package/.versions/0.0.7/scripts/lib/hermes-bridge-core.ts +241 -0
  528. package/.versions/0.0.7/scripts/lib/hermes-monitor-events.ts +1 -0
  529. package/.versions/0.0.7/scripts/lib/hermes-monitor-herdr.ts +2 -0
  530. package/.versions/0.0.7/scripts/lib/hermes-monitor-model.ts +3 -0
  531. package/.versions/0.0.7/scripts/lib/hermes-monitor-registry.ts +2 -0
  532. package/.versions/0.0.7/scripts/lib/hermes-monitor-socket.ts +2 -0
  533. package/.versions/0.0.7/scripts/lib/hermes-monitor-store.ts +2 -0
  534. package/.versions/0.0.7/scripts/lib/monitor-env.ts +120 -0
  535. package/.versions/0.0.7/scripts/lib/persona-banner.ts +62 -0
  536. package/.versions/0.0.7/scripts/lib/spawn-stagger.ts +101 -0
  537. package/.versions/0.0.7/scripts/lib/team-project.ts +191 -0
  538. package/.versions/0.0.7/scripts/lib/team-snapshot.ts +147 -0
  539. package/.versions/0.0.7/scripts/peer-banner.ts +40 -0
  540. package/.versions/0.0.7/scripts/team-snapshot.ts +237 -0
  541. package/.versions/0.0.7/scripts/team-up.ts +360 -0
  542. package/.versions/0.0.7/skills/_internal/grilling.md +11 -0
  543. package/.versions/0.0.7/skills/browser-testing-with-devtools/SKILL.md +352 -0
  544. package/.versions/0.0.7/skills/code-review-and-quality/SKILL.md +381 -0
  545. package/.versions/0.0.7/skills/compound-learning/SKILL.md +137 -0
  546. package/.versions/0.0.7/skills/context-engineering/SKILL.md +291 -0
  547. package/.versions/0.0.7/skills/deprecation-and-migration/SKILL.md +206 -0
  548. package/.versions/0.0.7/skills/designing-agents/SKILL.md +394 -0
  549. package/.versions/0.0.7/skills/designing-agents/pi-harness-authoring.md +222 -0
  550. package/.versions/0.0.7/skills/frontend-ui-engineering/SKILL.md +328 -0
  551. package/.versions/0.0.7/skills/git-workflow-and-versioning/SKILL.md +316 -0
  552. package/.versions/0.0.7/skills/guided-workspace-setup/SKILL.md +544 -0
  553. package/.versions/0.0.7/skills/guided-workspace-setup/companion-manifest.json +35 -0
  554. package/.versions/0.0.7/skills/idea-refine/SKILL.md +182 -0
  555. package/.versions/0.0.7/skills/idea-refine/examples.md +238 -0
  556. package/.versions/0.0.7/skills/idea-refine/frameworks.md +99 -0
  557. package/.versions/0.0.7/skills/idea-refine/refinement-criteria.md +113 -0
  558. package/.versions/0.0.7/skills/idea-refine/scripts/idea-refine.sh +15 -0
  559. package/.versions/0.0.7/skills/incremental-implementation/SKILL.md +287 -0
  560. package/.versions/0.0.7/skills/interview-me/SKILL.md +226 -0
  561. package/.versions/0.0.7/skills/orchestration-verification/SKILL.md +181 -0
  562. package/.versions/0.0.7/skills/peer-coms/SKILL.md +90 -0
  563. package/.versions/0.0.7/skills/performance-optimization/SKILL.md +350 -0
  564. package/.versions/0.0.7/skills/planning-and-task-breakdown/SKILL.md +236 -0
  565. package/.versions/0.0.7/skills/security-and-hardening/SKILL.md +461 -0
  566. package/.versions/0.0.7/skills/spec-driven-development/SKILL.md +245 -0
  567. package/.versions/0.0.7/skills/using-agent-skills/SKILL.md +199 -0
  568. package/.versions/0.0.7/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  569. package/.versions/0.0.7/vendor/agent-skills-upstream/LICENSE +21 -0
  570. package/.versions/0.0.7/vendor/agent-skills-upstream/README.md +11 -0
  571. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  572. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  573. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  574. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  575. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  576. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  577. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  578. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  579. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  580. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  581. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  582. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  583. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  584. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  585. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  586. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  587. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  588. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  589. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  590. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  591. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  592. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  593. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  594. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  595. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  596. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  597. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  598. package/.versions/0.0.7/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  599. package/CHANGELOG.md +140 -0
  600. package/README.md +198 -40
  601. package/agents/code-reviewer.md +2 -2
  602. package/agents/documenter.md +1 -1
  603. package/agents/orchestrator.md +11 -0
  604. package/agents/plan-reviewer.md +1 -1
  605. package/agents/planner.md +1 -1
  606. package/agents/releaser.md +1 -1
  607. package/agents/security-auditor.md +1 -1
  608. package/bin/cli.js +60 -21
  609. package/bin/lib/bootstrap.js +16 -16
  610. package/bin/lib/doctor.js +1 -1
  611. package/bin/lib/hermes-profile-artifact.js +144 -0
  612. package/bin/lib/set-hermes-watchdog.js +173 -0
  613. package/bin/set-hermes-watchdog.js +26 -0
  614. package/docs/ARCHITECTURE.md +67 -15
  615. package/docs/agent-fleet-setup.md +13 -13
  616. package/docs/claude-code-coms-bridge.md +7 -1
  617. package/docs/coms-hermes-bridge.md +18 -8
  618. package/docs/getting-started.md +48 -0
  619. package/docs/hermes-watchdog-supervisor.md +140 -0
  620. package/docs/npm-install.md +21 -21
  621. package/docs/pi-extensions.md +7 -7
  622. package/docs/pi-setup.md +51 -47
  623. package/hermes/README.md +135 -19
  624. package/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  625. package/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  626. package/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  627. package/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  628. package/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  629. package/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  630. package/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  631. package/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  632. package/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  633. package/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  634. package/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  635. package/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  636. package/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  637. package/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  638. package/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  639. package/hermes/plugins/agent-fleet-monitor/dashboard/dist/index.js +10 -0
  640. package/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  641. package/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  642. package/hermes/skills/hub-watchdog/SKILL.md +76 -0
  643. package/hermes/skills/hub-watchdog/manifest.json +1 -0
  644. package/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  645. package/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  646. package/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  647. package/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  648. package/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  649. package/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  650. package/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  651. package/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  652. package/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  653. package/hooks/coms-stop-hook.mjs +12 -1
  654. package/package.json +11 -2
  655. package/references/fleet-coordination-patterns.md +2 -2
  656. package/scripts/coms-claude-bridge.ts +154 -39
  657. package/scripts/fleet.ts +9 -1
  658. package/scripts/hermes-watchdog-capability-probe.ts +45 -0
  659. package/scripts/lib/claude-bridge-core.ts +65 -0
  660. package/scripts/lib/coms-envelope.ts +44 -1
  661. package/scripts/lib/hermes-monitor-events.ts +1 -0
  662. package/scripts/lib/monitor-env.ts +120 -0
  663. package/scripts/team-snapshot.ts +1 -1
  664. package/scripts/team-up.ts +10 -1
  665. package/skills/browser-testing-with-devtools/SKILL.md +1 -1
  666. package/skills/compound-learning/SKILL.md +3 -3
  667. package/skills/guided-workspace-setup/SKILL.md +16 -14
  668. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-cap.test.py +0 -15
  669. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-discovery.test.py +0 -19
  670. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-envelope.test.py +0 -13
  671. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-forged-owner.test.py +0 -11
  672. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-lease-list.test.py +0 -9
  673. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-multihub.test.py +0 -17
  674. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-output.test.py +0 -34
  675. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter.test.py +0 -39
  676. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/plugin-api-validation.test.py +0 -12
  677. package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/review-live-wiring.red.test.py +0 -22
  678. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-cap.test.py +0 -15
  679. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-discovery.test.py +0 -19
  680. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-envelope.test.py +0 -13
  681. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-forged-owner.test.py +0 -11
  682. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-lease-list.test.py +0 -9
  683. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-multihub.test.py +0 -17
  684. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter-output.test.py +0 -34
  685. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/adapter.test.py +0 -39
  686. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/plugin-api-validation.test.py +0 -12
  687. package/.versions/0.0.5/hermes/plugins/agent-fleet-monitor/dashboard/review-live-wiring.red.test.py +0 -22
  688. /package/.pi/prompts/{build.md → af-build.md} +0 -0
  689. /package/.pi/prompts/{code-simplify.md → af-code-simplify.md} +0 -0
  690. /package/.pi/prompts/{plan.md → af-plan.md} +0 -0
  691. /package/.pi/prompts/{review.md → af-review.md} +0 -0
  692. /package/.pi/prompts/{set-hermes-telegram.md → af-set-hermes-telegram.md} +0 -0
  693. /package/.pi/prompts/{ship.md → af-ship.md} +0 -0
  694. /package/.pi/prompts/{spec.md → af-spec.md} +0 -0
  695. /package/.pi/prompts/{test.md → af-test.md} +0 -0
@@ -2,46 +2,46 @@
2
2
  * Agent Hub — Dispatcher orchestrator + embedded coms peer-to-peer layer
3
3
  *
4
4
  * The merged harness (plan: docs/plans/agent-hub-multi-agent-harness.md). It is
5
- * `agent-team` (dispatcher grid + per-agent model + kill/restart + /zoom +
5
+ * `agent-team` (dispatcher grid + per-agent model + kill/restart + /af-zoom +
6
6
  * read-only research helpers + dispatcher persona gate) with the `coms` P2P layer
7
7
  * EMBEDDED in the same extension — not stacked as a second `-e`, which would
8
8
  * double-register the --name/--purpose/... CLI flags and abort startup.
9
9
  *
10
10
  * So the dispatcher is ALSO a coms peer: it can use another long-lived peer as a
11
11
  * subagent (coms_send + coms_await), hand the whole session off to a peer
12
- * (/handoff), and be addressed by other peers as a subagent itself. If the coms
12
+ * (/af-handoff), and be addressed by other peers as a subagent itself. If the coms
13
13
  * endpoint fails to bind, the harness degrades to a coms-less dispatcher
14
14
  * (comsReady=false withholds the coms_* tools).
15
15
  *
16
16
  * Commands:
17
- * /agents-team — switch active team
18
- * /agents-list — list loaded agents
19
- * /agents-history — timeline of agent execution (durations + grand total)
20
- * /agent-model <persona>[.<role>] — switch a team or research persona's (or
17
+ * /af-agents-team — switch active team
18
+ * /af-agents-list — list loaded agents
19
+ * /af-agents-history — timeline of agent execution (durations + grand total)
20
+ * /af-agent-model <persona>[.<role>] — switch a team or research persona's (or
21
21
  * delegate sub-role's) model from its declared candidates
22
- * /agent-model-thinking <persona> — switch a team or research persona's thinking
22
+ * /af-agent-model-thinking <persona> — switch a team or research persona's thinking
23
23
  * level (off|minimal|low|medium|high|xhigh)
24
- * /models [profile] — apply a named model profile (.pi/agents/model-profiles.yaml)
25
- * /agent-models-substitute <source> <target> — swap one model across all personas
26
- * /dispatch-policy — show which members route to coms peers (.pi/agents/dispatch-policy.yaml)
27
- * /agents-kill <name|rN|all> — SIGTERM a frozen specialist (and its delegation
24
+ * /af-models [profile] — apply a named model profile (.pi/agents/model-profiles.yaml)
25
+ * /af-agent-models-substitute <source> <target> — swap one model across all personas
26
+ * /af-dispatch-policy — show which members route to coms peers (.pi/agents/dispatch-policy.yaml)
27
+ * /af-agents-kill <name|rN|all> — SIGTERM a frozen specialist (and its delegation
28
28
  * tree); on a research helper it kills AND removes the
29
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
30
+ * (aliases: /af-research-rm rN, /af-research-clear)
31
+ * /af-agents-restart <name|rN> — kill + re-run its last task fresh (research: must
32
32
  * be finished; runs on a fresh session)
33
- * /zoom <name|rN|child> — scrollable read-only view of an agent's stream
33
+ * /af-zoom <name|rN|child> — scrollable read-only view of an agent's stream
34
34
  * (team member, research helper rN, or delegate child id)
35
- * /research <task> — spawn a read-only research helper (@persona, --model)
36
- * /agents-cont rN ... — resume a finished research helper (alias: /research-cont)
35
+ * /af-research <task> — spawn a read-only research helper (@persona, --model)
36
+ * /af-agents-cont rN ... — resume a finished research helper (alias: /af-research-cont)
37
37
  *
38
38
  * Finished research helpers are auto-pruned: auto-research pipe helpers as soon
39
39
  * as they finish (findings persist as files under findings/), manual/persona
40
40
  * helpers beyond the `research-keep` most recent (default 4, overrides file).
41
- * /persona — select/reset the dispatcher persona
42
- * /handoff <peer> — hand the session off to a coms peer (summarized brief)
43
- * /coms — refresh the coms peer pool (--all / --project <name>)
44
- * /compound [focus] — end-of-session compound-learning pass: confirm this
41
+ * /af-persona — select/reset the dispatcher persona
42
+ * /af-handoff <peer> — hand the session off to a coms peer (summarized brief)
43
+ * /af-coms — refresh the coms peer pool (--all / --project <name>)
44
+ * /af-compound [focus] — end-of-session compound-learning pass: confirm this
45
45
  * session's lessons with the user, then dispatch the
46
46
  * documenter to land them in the project's rules/docs
47
47
  *
@@ -70,7 +70,7 @@ import {
70
70
  type AutocompleteItem, truncateToWidth, visibleWidth,
71
71
  } from "@mariozechner/pi-tui";
72
72
  import { spawn, type ChildProcess } from "child_process";
73
- import { spawnPiAgent, killPiTree, type PiRunControl, type Termination } from "./spawn.ts";
73
+ import { spawnPiAgent, spawnPiAgentWithModelFallback, killPiTree, type PiRunControl, type SpawnPiAgentCallbacks, type SpawnPiAgentOptions, type Termination } from "./spawn.ts";
74
74
  import { researchTerminationOutcome, researchWatchdogSpawnOptions } from "./research-watchdog.ts";
75
75
  import { renderHubFooterLeft } from "./footer.ts";
76
76
  import { HARNESS_VERSION, registerVersionStatus } from "./version.ts";
@@ -80,33 +80,42 @@ import { MonitorRegistry } from "../lib/hermes-monitor-registry.ts";
80
80
  import { MonitorStore } from "../lib/hermes-monitor-store.ts";
81
81
  import { createMonitorSessionBridge } from "./monitor-session-bridge.ts";
82
82
  import { MonitorRuntime } from "./monitor-runtime.ts";
83
+ import { MonitorEventJournal } from "../lib/hermes-monitor-events.ts";
84
+ import { MonitorInvokeJournal } from "./monitor-invoke-journal.ts";
85
+ import { createMonitorInvokeAdmission, createWatchdogFollowUpEnqueue } from "./monitor-invoke.ts";
83
86
  import { monitorReconcileEvidence, stableMonitorHubId } from "./monitor-recovery.ts";
84
87
  import {
85
88
  AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
86
89
  exemptionsFilePath, type AccessRequest,
87
90
  } 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";
91
+ import { applyModelOverride, clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
92
+ import { DEFAULT_HUB_MODE, DEFAULT_TASK_TIER, HUB_MODES, TASK_TIERS, budgetStatusLine, checkTurnBudget, contextOverflowDiagnostic, normalizeHubMode, normalizeTaskTier, resolveTurnBudget, shouldRecycleSession } from "./run-budget.js";
93
+ import { MAX_OPEN_ASSERTIONS, validateAssertionBatch } from "./assertion-ledger.js";
94
+ import { DEFAULT_PROVIDER_LIMITS, createProviderSemaphore, parseProviderLimits } from "./provider-semaphore.js";
95
+ import { PEER_READY_TIMEOUT_MS, peerReadyDelayMs, peerReadyVerdict, unaddressedPeerSweep } from "./spawned-peers.js";
96
+ import { contextPct, estimatePromptTokens, overWindowDiagnostic, resolveContextWindow, shouldRecycleBeforeSpawn } from "./context-window.js";
97
+ import { DEFAULT_WATCHDOG_SETTING, WATCHDOG_SETTINGS, buildJudgePrompt, createDriftMonitor, hubOwnedScopeGlobs, normalizeWatchdogSetting, parseJudgeVerdict, resolveWatchdogActive } from "./drift-watchdog.js";
98
+ import { forceQuarantineSession, isCorruptSessionExit, quarantineIfUnusable } from "./session-health.js";
99
+ import { EXTRACTION_DEADLINE_MS, EXTRACTION_MODEL, buildExtractionPrompt, extractionSessionName, shouldExtractReturn } from "./return-extract.js";
91
100
  import { artifactPreviewFromText, formatInputArtifactsSection, resolveArtifactPaths, ARTIFACT_KINDS } from "./artifacts.js";
92
- import { crossCheck, extractAssertionIds, parseStructuredReturn } from "./return-contract.js";
101
+ import { crossCheck, deliveryDisposition, extractAssertionIds, parseDeliveredReturn, parseStructuredReturn } from "./return-contract.js";
93
102
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
94
103
  import { validateEvidence } from "./evidence-rules.js";
95
104
  import { comsRequiredRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
96
105
  import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
97
106
  import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
98
107
  import { createAccessApprovalRouter } from "./access-approval.ts";
99
- import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
108
+ import { readdirSync, readFileSync, existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync, rmSync } from "fs";
100
109
  import {
101
- formatPeerStatus,
102
110
  HerdrAgentWatch,
103
111
  HerdrPresence,
104
112
  herdrPaneId,
105
113
  herdrPresenceAvailable,
106
- parsePeerName,
114
+ peerNameFrom,
107
115
  type HerdrAgentInfo,
108
116
  } from "../lib/herdr-presence.ts";
109
117
  import { herdr as herdrApi, herdrAvailable } from "../lib/herdr-client.ts";
118
+ import { buildLiveRegistryEntry, type ComsRegistryEntry } from "../lib/coms-registry-entry.ts";
110
119
  import { peerCommand } from "../../../scripts/lib/herdr-layout.ts";
111
120
  import { join, resolve } from "path";
112
121
  import * as net from "node:net";
@@ -123,7 +132,9 @@ interface AgentDef {
123
132
  description: string;
124
133
  tools: string;
125
134
  model?: string;
126
- // Allowed switch targets for /agent-model and model profiles (frontmatter
135
+ // Original frontmatter model retained when project/session overrides apply.
136
+ fallbackModel?: string;
137
+ // Allowed switch targets for /af-agent-model and model profiles (frontmatter
127
138
  // `models:` list). The default `model:` is implicitly a candidate too.
128
139
  models?: string[];
129
140
  // Mid-turn delegation (injected delegate tool): the sub-roles this persona
@@ -137,7 +148,7 @@ interface AgentDef {
137
148
  // surfaced once at session start.
138
149
  warnings?: string[];
139
150
  kind?: string;
140
- // Per-agent thinking level for `/zoom` debugging. A pi --thinking level
151
+ // Per-agent thinking level for `/af-zoom` debugging. A pi --thinking level
141
152
  // (off|minimal|low|medium|high|xhigh), default off. When non-off, thinking
142
153
  // deltas are captured into the zoom timeline.
143
154
  thinking?: string;
@@ -157,7 +168,7 @@ interface TimelineEntry {
157
168
 
158
169
  // A delegate child (or grandchild) of a dispatched specialist, reconstructed
159
170
  // from the JSONL events delegate.ts appends to the dispatch's delegation dir.
160
- // Satisfies Zoomable (def/status/timeline/zoomRender) so /zoom <child-id>
171
+ // Satisfies Zoomable (def/status/timeline/zoomRender) so /af-zoom <child-id>
161
172
  // opens the same overlay specialists get; `parent` is "root" for direct
162
173
  // children or another child's id for sub-sub-agents.
163
174
  interface DelegationChild {
@@ -175,7 +186,7 @@ interface DelegationChild {
175
186
  elapsed: number;
176
187
  timeline: TimelineEntry[];
177
188
  zoomRender?: (force?: boolean) => void;
178
- // The /agents-history node for this delegate child, set on its spawn event so
189
+ // The /af-agents-history node for this delegate child, set on its spawn event so
179
190
  // the exit event can close it. Lets a delegating specialist's row subtract the
180
191
  // time it spent awaiting its own sub-sub-agents.
181
192
  histEntry?: HistoryEntry;
@@ -186,6 +197,8 @@ interface InputArtifactPreview {
186
197
  path: string;
187
198
  displayPath: string;
188
199
  preview: string;
200
+ /** Set when the file was found under a different artifact kind than requested. */
201
+ resolvedFromKind?: string | null;
189
202
  }
190
203
 
191
204
  interface AgentState {
@@ -196,6 +209,10 @@ interface AgentState {
196
209
  elapsed: number;
197
210
  lastWork: string;
198
211
  contextPct: number;
212
+ // Last measured prompt size in tokens (input + cache reads + writes). Kept
213
+ // alongside contextPct because the pre-spawn guard needs the absolute number:
214
+ // a percentage cannot be compared against a window it was not divided by.
215
+ contextTokens: number;
199
216
  sessionFile: string | null;
200
217
  runCount: number;
201
218
  // Runs served by the CURRENT accumulated session (-c resume chain). Reset on
@@ -204,32 +221,32 @@ interface AgentState {
204
221
  timer?: ReturnType<typeof setInterval>;
205
222
  // Mid-turn delegation (delegate tool). Children parsed live from the event
206
223
  // file, keyed by child id; rendered as nested rows under the card and kept
207
- // after completion for post-hoc /zoom. Reset on each dispatch.
224
+ // after completion for post-hoc /af-zoom. Reset on each dispatch.
208
225
  delegations?: Map<string, DelegationChild>;
209
226
  delegationsWatcher?: { close(): void };
210
227
  // Kill / restart (Phase 2). The live child is stored so a frozen specialist
211
228
  // can be SIGTERM'd. `killedByOperator` tells the close handler the exit was an
212
229
  // operator kill (so it returns a "do not auto-retry" message instead of a
213
230
  // normal error); `restarting` distinguishes a kill-for-restart from a plain
214
- // kill; `onTerminate` lets /agents-restart await the kill before re-dispatching.
231
+ // kill; `onTerminate` lets /af-agents-restart await the kill before re-dispatching.
215
232
  proc?: ChildProcess;
216
233
  killedByOperator?: boolean;
217
234
  restarting?: boolean;
218
235
  onTerminate?: () => void;
219
236
  // Zoom timeline (Phase 3). A structured, persisted record of the specialist's
220
237
  // stream — coalesced assistant text, tool calls (name + args), and thinking
221
- // deltas when the persona opts in. `/zoom` renders this; it survives completion
238
+ // deltas when the persona opts in. `/af-zoom` renders this; it survives completion
222
239
  // so post-hoc zoom works without reading the session file. `zoomRender` is set
223
- // while a `/zoom` overlay is open so the stream parser can refresh it live
240
+ // while a `/af-zoom` overlay is open so the stream parser can refresh it live
224
241
  // (throttled; pass force=true for the final frame).
225
242
  timeline: TimelineEntry[];
226
243
  zoomRender?: (force?: boolean) => void;
227
- // The /agents-history node for the current dispatch, so delegate children parsed
244
+ // The /af-agents-history node for the current dispatch, so delegate children parsed
228
245
  // from the event file can attach to it as the root parent of their subtree.
229
246
  histEntry?: HistoryEntry;
230
247
  // Coms-backed dispatch (dispatch-policy.yaml): which backend served the last
231
- // run, the peer's model for the card badge, and the abandon hook /agents-kill
232
- // and /agents-restart use instead of a SIGTERM — the standing peer itself
248
+ // run, the peer's model for the card badge, and the abandon hook /af-agents-kill
249
+ // and /af-agents-restart use instead of a SIGTERM — the standing peer itself
233
250
  // cannot be killed from the hub, only the wait can be released.
234
251
  lastBackend?: "native" | "coms";
235
252
  comsPeerModel?: string;
@@ -242,8 +259,8 @@ interface AgentState {
242
259
  // construction: session files live under the same dir as team sessions and are wiped
243
260
  // on session_start; finished helpers are auto-pruned per the retention policy
244
261
  // (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`,
262
+ // the `research-keep` cap); `/af-agents-kill rN` (alias `/af-research-rm`) kills AND
263
+ // removes one by hand. Resumable via `/af-agents-cont` (alias `/af-research-cont`,
247
264
  // subcont-style, bumping turnCount) while retained.
248
265
  interface ResearchState {
249
266
  id: number;
@@ -267,7 +284,7 @@ interface ResearchState {
267
284
  zoomRender?: (force?: boolean) => void;
268
285
  }
269
286
 
270
- // The subset of state `/zoom` needs. Both AgentState (standing team) and ResearchState
287
+ // The subset of state `/af-zoom` needs. Both AgentState (standing team) and ResearchState
271
288
  // (read-only helpers) satisfy it, so the same ZoomUI overlay renders either one.
272
289
  interface Zoomable {
273
290
  def: { name: string };
@@ -276,10 +293,10 @@ interface Zoomable {
276
293
  zoomRender?: (force?: boolean) => void;
277
294
  }
278
295
 
279
- // One node in the /agents-history tree: an orchestrator (dispatcher) turn, a
296
+ // One node in the /af-agents-history tree: an orchestrator (dispatcher) turn, a
280
297
  // dispatched specialist, a research helper, or a delegate sub-sub-agent. `parent`
281
298
  // links a node to the one that launched it (null = top level — an orchestrator
282
- // turn, or a turn-less manual /research). `endedAt` is null while the node is still
299
+ // turn, or a turn-less manual /af-research). `endedAt` is null while the node is still
283
300
  // running, so the overlay can tick its duration live. Parallelism is derived at
284
301
  // render time from overlapping [startedAt, endedAt] ranges among siblings.
285
302
  type HistoryKind = "orchestrator" | "agent" | "research" | "delegate";
@@ -296,7 +313,7 @@ interface HistoryEntry {
296
313
  awaitIntervals?: Array<[number, number]>;
297
314
  }
298
315
 
299
- // Format a millisecond duration the way /agents-history shows it: plain seconds
316
+ // Format a millisecond duration the way /af-agents-history shows it: plain seconds
300
317
  // under a minute ("42sec"), m:ss above it ("10:20min" for 620s). Used for every
301
318
  // per-agent row and the footer total.
302
319
  function fmtDuration(ms: number): string {
@@ -398,7 +415,7 @@ function extractNeedsResearch(output: string): string[] {
398
415
  // doc folders. Specialists and research helpers read the
399
416
  // ones relevant to their task; context, not compliance.
400
417
  // research-keep: <n>|all — how many finished manual/persona research helpers
401
- // to retain for /agents-cont resume (LRU, default 4);
418
+ // to retain for /af-agents-cont resume (LRU, default 4);
402
419
  // "all" disables pruning. Auto-research pipe helpers
403
420
  // are always pruned as soon as they finish.
404
421
  // recon-search-timeout-s: <1..3600>|off — parent-side deadline for each
@@ -642,6 +659,8 @@ function parseModelProfilesYaml(raw: string): Record<string, Record<string, stri
642
659
  interface SubagentRole {
643
660
  model: string;
644
661
  tools?: string;
662
+ // Original role model retained across project/session overrides.
663
+ fallbackModel?: string;
645
664
  }
646
665
 
647
666
  // Inline forms of a subagents role value: `role: <model-spec>` shorthand or
@@ -768,7 +787,7 @@ function parseAgentFile(filePath: string): AgentDef | null {
768
787
  // ── Thinking level + timeline helpers (Phase 3) ──
769
788
 
770
789
  // pi --thinking levels, off→xhigh. Single source of truth for the validator, the
771
- // /agent-model-thinking picker, and the display badge.
790
+ // /af-agent-model-thinking picker, and the display badge.
772
791
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
773
792
  const VALID_THINKING_LEVELS = new Set<string>(THINKING_LEVELS);
774
793
 
@@ -1010,7 +1029,7 @@ class ZoomUI {
1010
1029
  }
1011
1030
  }
1012
1031
 
1013
- // Read-only scrollable overlay for /agents-history. Renders the execution log as a
1032
+ // Read-only scrollable overlay for /af-agents-history. Renders the execution log as a
1014
1033
  // timeline: orchestrator (dispatcher) turns at depth 0, the specialists they
1015
1034
  // dispatched indented beneath, and parallel siblings deeper still with a "│→"
1016
1035
  // connector. Every row shows a live duration; the footer carries the grand total.
@@ -1286,6 +1305,7 @@ interface PromptEnvelope extends Envelope {
1286
1305
  sender_cwd: string;
1287
1306
  conversation_id?: string | null;
1288
1307
  response_schema?: object | null;
1308
+ reply_timeout_ms?: number | null;
1289
1309
  }
1290
1310
 
1291
1311
  interface ResponseEnvelope extends Envelope {
@@ -1305,6 +1325,8 @@ interface AgentCard {
1305
1325
  color: string;
1306
1326
  context_used_pct: number;
1307
1327
  queue_depth: number;
1328
+ pane_id?: string | null;
1329
+ status?: "idle" | "working" | "booting";
1308
1330
  }
1309
1331
 
1310
1332
  interface Pong {
@@ -1313,24 +1335,10 @@ interface Pong {
1313
1335
  agent_card: AgentCard;
1314
1336
  }
1315
1337
 
1316
- interface RegistryEntry {
1317
- session_id: string;
1318
- name: string;
1319
- purpose: string;
1320
- model: string;
1321
- color: string;
1322
- pid: number;
1323
- endpoint: string;
1324
- cwd: string;
1325
- started_at: string;
1326
- explicit: boolean;
1327
- version: number;
1328
- // Live status snapshot — refreshed every KEEPALIVE_INTERVAL_MS by the heartbeat.
1329
- // Optional so older entries (pre-heartbeat-refresh) still parse cleanly.
1330
- context_used_pct?: number;
1331
- queue_depth?: number;
1332
- heartbeat_at?: string;
1333
- }
1338
+ // The registry shape and the heartbeat builder are shared with the standalone
1339
+ // coms harness — see ../lib/coms-registry-entry.ts. Both used to keep their own
1340
+ // copy of this literal, and both refreshed `started_at` every 30 seconds.
1341
+ type RegistryEntry = ComsRegistryEntry;
1334
1342
 
1335
1343
  interface PendingReply {
1336
1344
  resolve: (value: any) => void;
@@ -1769,6 +1777,8 @@ export default function (pi: ExtensionAPI) {
1769
1777
  model: string;
1770
1778
  endpoint: string;
1771
1779
  registryFile: string;
1780
+ // Set once, at registration. The heartbeat reads it; nothing rewrites it.
1781
+ started_at: string;
1772
1782
  } | null = null;
1773
1783
  const peerCards: Map<string, AgentCard & { staleCount: number }> = new Map();
1774
1784
  const pendingReplies: Map<string, PendingReply> = new Map();
@@ -1776,7 +1786,9 @@ export default function (pi: ExtensionAPI) {
1776
1786
  let server: net.Server | null = null;
1777
1787
  let monitorLifecycle: ReturnType<typeof createMonitorLifecycle> | null = null;
1778
1788
  let monitorHubId: string | null = null;
1789
+ let monitorTurnId: string | null = null;
1779
1790
  let monitorBridge: ReturnType<typeof createMonitorSessionBridge> | null = null;
1791
+ let monitorOwnerId: string | undefined;
1780
1792
  let pingTimer: NodeJS.Timeout | null = null;
1781
1793
  let keepaliveTimer: NodeJS.Timeout | null = null;
1782
1794
  // herdr presence backend (active when this session runs inside a herdr
@@ -1800,7 +1812,7 @@ export default function (pi: ExtensionAPI) {
1800
1812
  let comsPurposeExplicit = false;
1801
1813
 
1802
1814
  // ── Damage-control exemptions + access escalation state ──
1803
- // exemptionsFile is the session-scoped shared exemptions file: /allow
1815
+ // exemptionsFile is the session-scoped shared exemptions file: /af-allow
1804
1816
  // session grants (via the co-loaded damage-control-continue) and approved
1805
1817
  // escalations land here, and spawned children read it through the
1806
1818
  // AGENT_HUB_EXEMPTIONS_FILE env plumbing.
@@ -1822,7 +1834,7 @@ export default function (pi: ExtensionAPI) {
1822
1834
  // for "all"). Ephemeral auto-pipe helpers ignore the cap: pruned on finish.
1823
1835
  let researchKeep = DEFAULT_RESEARCH_KEEP;
1824
1836
 
1825
- // ── Execution history (/agents-history) ──────────
1837
+ // ── Execution history (/af-agents-history) ──────────
1826
1838
  // A tree of every dispatch: orchestrator (dispatcher) turns, the specialists they
1827
1839
  // dispatch, research helpers, and delegate sub-sub-agents. Orchestrator entries
1828
1840
  // are created lazily — only when a turn actually dispatches something — so
@@ -1850,7 +1862,7 @@ export default function (pi: ExtensionAPI) {
1850
1862
  }
1851
1863
 
1852
1864
  // Lazily open (and return) the orchestrator entry for the active turn. Returns
1853
- // null outside a turn (e.g. a manual /research), so that helper renders as a
1865
+ // null outside a turn (e.g. a manual /af-research), so that helper renders as a
1854
1866
  // top-level, turn-less row instead of attaching to a stale dispatcher entry.
1855
1867
  function ensureOrchestratorEntry(): HistoryEntry | null {
1856
1868
  if (!turnActive) return null;
@@ -1905,7 +1917,7 @@ export default function (pi: ExtensionAPI) {
1905
1917
  let teams: Record<string, string[]> = {};
1906
1918
  // Named model profiles from .pi/agents/model-profiles.yaml (validated at
1907
1919
  // session start) and the session-lifetime per-persona model overrides set by
1908
- // /agent-model and /models (lowercase persona name → pi model spec). Overrides
1920
+ // /af-agent-model and /af-models (lowercase persona name → pi model spec). Overrides
1909
1921
  // reset on session_start; profiles make re-applying cheap.
1910
1922
  let modelProfiles: Record<string, Record<string, string>> = {};
1911
1923
  // Backend routing policy (.pi/agents/dispatch-policy.yaml): per dispatch, a
@@ -1921,24 +1933,24 @@ export default function (pi: ExtensionAPI) {
1921
1933
  const comsMissNotified = new Set<string>();
1922
1934
  const modelOverrides = new Map<string, string>();
1923
1935
  // Session-lifetime per-persona thinking-level overrides set by
1924
- // /agent-model-thinking (lowercase persona name → pi --thinking level). Wins
1936
+ // /af-agent-model-thinking (lowercase persona name → pi --thinking level). Wins
1925
1937
  // over the persona's frontmatter `thinking:`; resets on session_start; takes
1926
- // effect on the persona's next dispatch (/agents-restart applies it now).
1938
+ // effect on the persona's next dispatch (/af-agents-restart applies it now).
1927
1939
  const thinkingOverrides = new Map<string, string>();
1928
1940
  // Session-lifetime model overrides for delegate sub-roles, set by
1929
- // /agent-model <persona>.<role>. Keyed "<persona>.<role>" (lowercase); applied
1941
+ // /af-agent-model <persona>.<role>. Keyed "<persona>.<role>" (lowercase); applied
1930
1942
  // when the dispatch serializes AGENT_HUB_DELEGATE_CONFIG, so nested children
1931
- // inherit them. Resets on session_start. /models profiles never touch these.
1943
+ // inherit them. Resets on session_start. /af-models profiles never touch these.
1932
1944
  const subagentModelOverrides = new Map<string, string>();
1933
1945
  let activeTeamName = "";
1934
1946
  let gridCols = 2;
1935
1947
  // View mode toggled by Alt+A: "dashboard" = full bordered card grid above the
1936
1948
  // editor; "compact" = one line per *running* agent (name · context · state)
1937
- // rendered BELOW the editor, just above the footer. Idle/done agents are hidden
1938
- // in compact mode, so an idle session shows nothing but the prompt + footer.
1939
- let viewMode: "dashboard" | "compact" = "dashboard";
1949
+ // rendered BELOW the editor, just above the footer. Compact is the default;
1950
+ // idle/done agents are hidden so an idle session shows only the prompt + footer.
1951
+ let viewMode: "dashboard" | "compact" = "compact";
1940
1952
  // Compact-view agent switcher: the key of the marked subagent (lowercase persona
1941
- // name for team specialists, `rN` for research helpers — matching /zoom
1953
+ // name for team specialists, `rN` for research helpers — matching /af-zoom
1942
1954
  // resolution), or null when nothing is marked. main is never listed (it is the
1943
1955
  // session under the input box). Alt+]/Alt+[ move it; Alt+\ zooms it.
1944
1956
  let markedAgent: string | null = null;
@@ -1946,6 +1958,36 @@ export default function (pi: ExtensionAPI) {
1946
1958
  let widgetCtx: any;
1947
1959
  let sessionDir = "";
1948
1960
  let contextWindow = 0;
1961
+ // Per-provider in-flight cap for the hub's OWN spawns (specialists and
1962
+ // research helpers, which the dispatcher can start in parallel). Delegate
1963
+ // children are gated by the same policy inside their parent's process. The
1964
+ // drift judge and the return extractor are deliberately NOT gated: both run
1965
+ // while a specialist holds a permit, so queueing them behind that specialist
1966
+ // would stall the very watchdog that is supposed to stop it.
1967
+ const providerSemaphore = createProviderSemaphore({
1968
+ ...DEFAULT_PROVIDER_LIMITS,
1969
+ ...parseProviderLimits(process.env.AGENT_HUB_PROVIDER_LIMITS),
1970
+ });
1971
+ /**
1972
+ * pi's model registry as a plain lookup — the documented source for every
1973
+ * model's window, and the same one the dispatcher's own window comes from.
1974
+ */
1975
+ function modelWindowLookup(ctx: any): (provider: string, modelId: string) => any {
1976
+ return (provider, modelId) => ctx?.modelRegistry?.find?.(provider, modelId);
1977
+ }
1978
+
1979
+ /** Say so when a run is about to wait on a provider permit, not just hang. */
1980
+ function notifyProviderQueue(model: string, label: string, ctx: any): void {
1981
+ const cap = providerSemaphore.limitFor(model);
1982
+ if (cap == null || providerSemaphore.inFlight(model) < cap) return;
1983
+ const ahead = providerSemaphore.queued(model) + 1;
1984
+ ctx?.ui?.notify(
1985
+ `${label}: queued — ${cap} requests already in flight on this provider (${ahead} waiting). ` +
1986
+ "Raise or disable the cap with AGENT_HUB_PROVIDER_LIMITS (e.g. custom=4, custom=off).",
1987
+ "info",
1988
+ );
1989
+ }
1990
+
1949
1991
  let activeWritableDispatches = 0;
1950
1992
  let writableOverlapCounter = 0;
1951
1993
  let pendingHandoff: { target: string; token: string } | null = null;
@@ -2005,7 +2047,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2005
2047
  // whole-run bound is separate: the turn budget's agentTurnMs (run-budget.js).
2006
2048
  let reconSearchTimeoutMs: number | null = 120_000;
2007
2049
  // ── Execution mode & per-turn budgets (run-budget.js) ──
2008
- // hubMode: overrides-file default, switchable live via /hub-mode (session-
2050
+ // hubMode: overrides-file default, switchable live via /af-hub-mode (session-
2009
2051
  // lifetime). Budgets are per USER TURN: counters reset in before_agent_start,
2010
2052
  // so exhaustion means "stop, summarize, ask" and the next user message opens
2011
2053
  // a fresh window. currentTurnStartedAt (above) doubles as the wall-clock base.
@@ -2018,11 +2060,11 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2018
2060
  // assumes DEFAULT_TASK_TIER outside strict mode. Caps = min(mode, tier).
2019
2061
  let turnTaskTier: string | null = null;
2020
2062
  // Duplicate-dispatch guard: fingerprints of (agent, task) already dispatched
2021
- // THIS turn. Auto-research resumes and /agents-restart call dispatchAgent
2063
+ // THIS turn. Auto-research resumes and /af-agents-restart call dispatchAgent
2022
2064
  // directly, so only real dispatcher tool calls are guarded.
2023
2065
  const turnDispatchFingerprints = new Set<string>();
2024
2066
  // ── Drift watchdog (drift-watchdog.js) ──
2025
- // Hub-wide setting from the overrides file, live-switchable via /watchdog;
2067
+ // Hub-wide setting from the overrides file, live-switchable via /af-watchdog;
2026
2068
  // per-agent overrides ("on"/"off") win over it; a dispatch_agent `watchdog`
2027
2069
  // param wins over both.
2028
2070
  let watchdogSetting: string = DEFAULT_WATCHDOG_SETTING;
@@ -2036,7 +2078,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2036
2078
  widgetCtx?.ui?.setStatus("hub-mode", budgetStatusLine(hubMode, { dispatches: turnDispatchCount, research: turnResearchCount }, currentBudget(), turnTaskTier));
2037
2079
  } catch {}
2038
2080
  }
2039
- // ── Per-turn cost report (/hub-report) ──
2081
+ // ── Per-turn cost report (/af-hub-report) ──
2040
2082
  interface TurnReport {
2041
2083
  startedAt: number;
2042
2084
  tier: string | null;
@@ -2069,6 +2111,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2069
2111
  id: string; // A1, A2, …
2070
2112
  tag: string; // test | runtime-ui | code-grep | manual
2071
2113
  text: string; // one checkable pass condition
2114
+ source: string; // where it came from — plan/spec line, user request, finding id
2072
2115
  status: AssertionStatus;
2073
2116
  evidence?: string; // named evidence for proven / failed
2074
2117
  }
@@ -2095,7 +2138,8 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2095
2138
  function renderAssertionLedgerLines(): string[] {
2096
2139
  return assertions.map(a => {
2097
2140
  const ev = a.evidence ? ` — evidence: ${a.evidence}` : "";
2098
- return `${a.id} [${a.tag}] ${a.status.toUpperCase()}: ${a.text}${ev}`;
2141
+ const src = a.source ? ` ⇐ ${a.source}` : "";
2142
+ return `${a.id} [${a.tag}] ${a.status.toUpperCase()}: ${a.text}${src}${ev}`;
2099
2143
  });
2100
2144
  }
2101
2145
 
@@ -2140,7 +2184,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2140
2184
  }
2141
2185
 
2142
2186
  // The raw thinking value a persona would dispatch with right now: session
2143
- // override (/agent-model-thinking) → frontmatter `thinking:`. Pass through
2187
+ // override (/af-agent-model-thinking) → frontmatter `thinking:`. Pass through
2144
2188
  // resolveThinkingLevel before use to get a valid pi --thinking level.
2145
2189
  function resolvedThinking(def: AgentDef): string | undefined {
2146
2190
  return thinkingOverrides.get(def.name.toLowerCase()) ?? def.thinking;
@@ -2148,7 +2192,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2148
2192
 
2149
2193
  // Resolve a model/thinking-switchable persona def by its (lowercased) name:
2150
2194
  // a live team member's def first, then a research persona (researcher /
2151
- // deep-researcher). Lets /agent-model and /agent-model-thinking target
2195
+ // deep-researcher). Lets /af-agent-model and /af-agent-model-thinking target
2152
2196
  // research helpers exactly like standard team members — the override maps
2153
2197
  // are keyed by name, so the switch is honored on the helper's next spawn.
2154
2198
  function switchablePersonaDef(name: string): AgentDef | undefined {
@@ -2212,11 +2256,16 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2212
2256
  return `\n\n⚠ Scope advisory: changed outside declared scope: ${scopeViolations.outOfScope.join(", ")}. Review these paths and decide whether to accept them or explicitly order cleanup; the hub did not revert anything.${overlap}`;
2213
2257
  }
2214
2258
 
2215
- function writeReturnArtifact(agentKey: string, runCount: number, output: string): string {
2259
+ /**
2260
+ * Persist a run's output. `kind` is "returns" for a run that completed and
2261
+ * "failures" for one that errored or timed out — an error stub filed as a
2262
+ * return reads as a specialist verdict and is acted on as one.
2263
+ */
2264
+ function writeRunArtifact(agentKey: string, runCount: number, output: string, kind: "returns" | "failures" = "returns"): string {
2216
2265
  const root = ensureArtifactsLayout();
2217
- const returnsDir = safePathWithin(root, "returns");
2218
- mkdirSync(returnsDir, { recursive: true });
2219
- const file = safePathWithin(returnsDir, `${agentKey}-run${runCount}.md`);
2266
+ const dir = safePathWithin(root, kind);
2267
+ mkdirSync(dir, { recursive: true });
2268
+ const file = safePathWithin(dir, `${agentKey}-run${runCount}.md`);
2220
2269
  writeFileSync(file, output, "utf-8");
2221
2270
  return file;
2222
2271
  }
@@ -2285,7 +2334,10 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2285
2334
  lines.push(`${key}:`);
2286
2335
  for (const entry of entries) {
2287
2336
  const evidence = entry.evidence ? ` — evidence: ${entry.evidence}` : "";
2288
- lines.push(`- ${entry.id}: ${entry.note || "(no note)"}${evidence}`);
2337
+ // Line-form verdicts carry evidence and no separate note; printing
2338
+ // "(no note)" next to real evidence is noise, not information.
2339
+ const note = entry.note || (entry.evidence ? "" : "(no note)");
2340
+ lines.push(`- ${entry.id}${note ? `: ${note}` : ""}${evidence}`);
2289
2341
  }
2290
2342
  }
2291
2343
  for (const key of ["changed_files", "tests_run", "open_risks", "requires_user_decision"]) {
@@ -2376,9 +2428,33 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2376
2428
  }
2377
2429
  }
2378
2430
 
2379
- function freshAgentState(def: AgentDef): AgentState {
2380
- const key = safeAgentKey(def.name);
2381
- const sessionFile = safePathWithin(sessionDir, `${key}.json`);
2431
+ // Only the first record decides whether pi will accept a session file, and these
2432
+ // files reach megabytes (one observed at 2.1 MB) — so read a head slice, not the
2433
+ // whole thing. This check runs on every dispatch and every team activation.
2434
+ const SESSION_HEAD_BYTES = 64 * 1024;
2435
+ function readSessionHead(file: string): string {
2436
+ const fd = fs.openSync(file, "r");
2437
+ try {
2438
+ const buf = Buffer.alloc(SESSION_HEAD_BYTES);
2439
+ const read = fs.readSync(fd, buf, 0, SESSION_HEAD_BYTES, 0);
2440
+ return buf.subarray(0, read).toString("utf-8");
2441
+ } finally {
2442
+ fs.closeSync(fd);
2443
+ }
2444
+ }
2445
+ const sessionHealthIo = { existsSync, readFileSync: readSessionHead, renameSync };
2446
+
2447
+ // Would the persona's on-disk session file survive contact with pi? A corrupt
2448
+ // one must never be adopted: doing so is what made every `builder` dispatch
2449
+ // fail in ~1s, and re-adding the agent re-adopted the same bad file, so
2450
+ // drop + add looked like a recovery that could not work.
2451
+ function adoptableSessionFile(def: AgentDef): { file: string | null; quarantined: string | null; reason: string | null } {
2452
+ const sessionFile = safePathWithin(sessionDir, `${safeAgentKey(def.name)}.json`);
2453
+ const health = quarantineIfUnusable(sessionFile, sessionHealthIo);
2454
+ return { file: health.usable ? sessionFile : null, quarantined: health.quarantined, reason: health.reason };
2455
+ }
2456
+
2457
+ function freshAgentState(def: AgentDef, adoption = adoptableSessionFile(def)): AgentState {
2382
2458
  return {
2383
2459
  def,
2384
2460
  status: "idle",
@@ -2387,7 +2463,8 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2387
2463
  elapsed: 0,
2388
2464
  lastWork: "",
2389
2465
  contextPct: 0,
2390
- sessionFile: existsSync(sessionFile) ? sessionFile : null,
2466
+ contextTokens: 0,
2467
+ sessionFile: adoption.file,
2391
2468
  runCount: 0,
2392
2469
  runsSinceFresh: 0,
2393
2470
  timeline: [],
@@ -2415,7 +2492,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2415
2492
  recomputeGrid();
2416
2493
  }
2417
2494
 
2418
- // ── Dynamic roster (add/drop/save; /agents-add, /agents-drop, team_adjust) ──
2495
+ // ── Dynamic roster (add/drop/save; /af-agents-add, /af-agents-drop, team_adjust) ──
2419
2496
  // The system prompt is rebuilt every turn from agentStates, so a roster
2420
2497
  // change takes effect on the dispatcher's next turn with no restart.
2421
2498
 
@@ -2429,10 +2506,14 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2429
2506
  if (agentStates.has(def.name.toLowerCase())) {
2430
2507
  return { ok: false, message: `${displayName(def.name)} is already in the active team` };
2431
2508
  }
2432
- agentStates.set(def.name.toLowerCase(), freshAgentState(def));
2509
+ const adoption = adoptableSessionFile(def);
2510
+ agentStates.set(def.name.toLowerCase(), freshAgentState(def, adoption));
2433
2511
  recomputeGrid();
2434
2512
  updateWidget();
2435
- return { ok: true, message: `${displayName(def.name)} added to the active team` };
2513
+ const quarantineNote = adoption.quarantined
2514
+ ? ` — its previous session file was unusable (${adoption.reason}) and was quarantined to ${adoption.quarantined}; it starts clean`
2515
+ : "";
2516
+ return { ok: true, message: `${displayName(def.name)} added to the active team${quarantineNote}` };
2436
2517
  }
2437
2518
 
2438
2519
  function rosterDrop(name: string): { ok: boolean; message: string } {
@@ -2442,7 +2523,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2442
2523
  return { ok: false, message: `"${name}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ") || "empty"})` };
2443
2524
  }
2444
2525
  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` };
2526
+ return { ok: false, message: `${displayName(state.def.name)} is running — wait for it to finish or /af-agents-kill it first` };
2446
2527
  }
2447
2528
  if (agentStates.size <= 1) {
2448
2529
  return { ok: false, message: `${displayName(state.def.name)} is the last team member — add a replacement before dropping it` };
@@ -2450,7 +2531,20 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2450
2531
  agentStates.delete(key);
2451
2532
  recomputeGrid();
2452
2533
  updateWidget();
2453
- return { ok: true, message: `${displayName(state.def.name)} dropped from the active team (its session file is kept for re-adding)` };
2534
+ // Promise a reusable session file only when pi would actually accept it.
2535
+ // The old unconditional "kept for re-adding" is what made a corrupt file
2536
+ // look re-addable: the dispatcher dropped the agent, added it back, and got
2537
+ // the same instant failures.
2538
+ const health = quarantineIfUnusable(
2539
+ safePathWithin(sessionDir, `${safeAgentKey(state.def.name)}.json`),
2540
+ sessionHealthIo,
2541
+ );
2542
+ const fileNote = health.usable
2543
+ ? " (its session file is kept for re-adding)"
2544
+ : health.quarantined
2545
+ ? ` (its session file was unusable — ${health.reason} — and was quarantined to ${health.quarantined}; re-adding starts clean)`
2546
+ : " (it has no session file; re-adding starts clean)";
2547
+ return { ok: true, message: `${displayName(state.def.name)} dropped from the active team${fileNote}` };
2454
2548
  }
2455
2549
 
2456
2550
  // ── Grid Rendering ───────────────────────────
@@ -2813,7 +2907,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2813
2907
  // one line each — idle/done agents are omitted.
2814
2908
  // Ordered list of switchable subagents for the compact-view marker: running team
2815
2909
  // specialists then running research helpers. main is the session under the input
2816
- // box, so it is never listed. Each entry's `key` matches /zoom resolution
2910
+ // box, so it is never listed. Each entry's `key` matches /af-zoom resolution
2817
2911
  // (lowercase persona name for team, `rN` for research), so Alt+\ can resolve it.
2818
2912
  function switchableAgents(): { key: string; name: string; ctx: number; ctxWarn: boolean; model: string; status: { color: string; text: string } }[] {
2819
2913
  return [
@@ -2869,7 +2963,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2869
2963
  // delegate.ts (running inside the specialist) appends JSONL events to
2870
2964
  // <sessionDir>/delegations/<agentKey>/events.jsonl. The hub tails that file
2871
2965
  // (fs.watch for responsiveness + a 1s poll fallback) and rebuilds child
2872
- // states for the nested card rows, /zoom, and the spend rollup.
2966
+ // states for the nested card rows, /af-zoom, and the spend rollup.
2873
2967
 
2874
2968
  function formatTokens(n: number): string {
2875
2969
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
@@ -2887,7 +2981,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2887
2981
  if (e.t === "spawn") {
2888
2982
  const startedAt = e.ts || Date.now();
2889
2983
  const parentId = typeof e.parent === "string" ? e.parent : "root";
2890
- // Attach to the /agents-history tree: a "root" child hangs off the
2984
+ // Attach to the /af-agents-history tree: a "root" child hangs off the
2891
2985
  // specialist's own dispatch node; a deeper grandchild hangs off the
2892
2986
  // already-recorded parent child. Falls back to the specialist node.
2893
2987
  const parentEntry = parentId !== "root"
@@ -2923,6 +3017,16 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2923
3017
  }
2924
3018
  }
2925
3019
  child.zoomRender?.();
3020
+ } else if (e.t === "model_fallback") {
3021
+ child.model = e.to || child.model;
3022
+ child.lastWork = `model fallback: ${e.from || "override"} → ${e.to || "original"}`;
3023
+ child.timeline.push({
3024
+ kind: "text",
3025
+ title: "Model fallback",
3026
+ content: `${e.from || "override"} failed before work began; retrying with ${e.to || "original"}. ${e.reason || ""}`.trim(),
3027
+ timestamp: Date.now(),
3028
+ });
3029
+ child.zoomRender?.();
2926
3030
  } else if (e.t === "tool") {
2927
3031
  child.toolCount++;
2928
3032
  child.timeline.push({
@@ -3011,7 +3115,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
3011
3115
  ctx: any,
3012
3116
  inputArtifacts: InputArtifactPreview[],
3013
3117
  scopeGlobs: string[],
3014
- ): Promise<{ output: string; exitCode: number; elapsed: number; abandoned?: boolean } | null> {
3118
+ ): Promise<{ output: string; exitCode: number; elapsed: number; abandoned?: boolean; pending?: boolean } | null> {
3015
3119
  const peer = resolveTarget(peerName);
3016
3120
  if (!peer || !identity) {
3017
3121
  if (allowNativeFallback) return null;
@@ -3052,6 +3156,7 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3052
3156
  prompt,
3053
3157
  conversation_id: null,
3054
3158
  response_schema: null,
3159
+ reply_timeout_ms: timeoutMs,
3055
3160
  };
3056
3161
  try {
3057
3162
  await sendEnvelope(peer.endpoint, env);
@@ -3072,12 +3177,10 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3072
3177
  rejectFn = rej;
3073
3178
  });
3074
3179
  const entry: PendingReply = { resolve: resolveFn, reject: rejectFn, timer: null, promise, target_name: peer.name, created_at: nowIso() };
3075
- entry.timer = setTimeout(() => {
3076
- if (entry.result) return;
3077
- entry.result = { error: "timeout" };
3078
- try { entry.resolve(entry.result); } catch { /* ignore */ }
3079
- }, timeoutMs);
3080
- try { (entry.timer as any).unref?.(); } catch { /* ignore */ }
3180
+ const timeoutPromise = new Promise<{ error: string }>((resolve) => {
3181
+ entry.timer = setTimeout(() => resolve({ error: "timeout" }), timeoutMs);
3182
+ try { (entry.timer as any).unref?.(); } catch { /* ignore */ }
3183
+ });
3081
3184
  pendingReplies.set(msg_id, entry);
3082
3185
  try {
3083
3186
  pi.appendEntry("coms-log", { event: "outbound_prompt", msg_id, target: peer.name, hops: env.hops, dispatched_as: state.def.name });
@@ -3085,7 +3188,7 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3085
3188
  // best-effort
3086
3189
  }
3087
3190
 
3088
- // /agents-kill and /agents-restart on a coms-backed run only abandon the
3191
+ // /af-agents-kill and /af-agents-restart on a coms-backed run only abandon the
3089
3192
  // wait — the standing peer keeps running its turn in its own pane.
3090
3193
  let abandoned = false;
3091
3194
  const abortPromise = new Promise<{ error: string }>(res => {
@@ -3094,13 +3197,15 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3094
3197
  res({ error: "abandoned" });
3095
3198
  };
3096
3199
  });
3097
- const outcome = await Promise.race([entry.promise, abortPromise]);
3200
+ const outcome = await Promise.race([entry.promise, abortPromise, timeoutPromise]);
3098
3201
  state.comsAbort = undefined;
3099
3202
  if (entry.timer) {
3100
3203
  try { clearTimeout(entry.timer); } catch { /* ignore */ }
3101
3204
  entry.timer = null;
3102
3205
  }
3103
- pendingReplies.delete(msg_id);
3206
+ // A timeout leaves the correlation entry live: the peer may still finish,
3207
+ // and coms_get/coms_await must be able to collect that late response.
3208
+ if (outcome.error !== "timeout") pendingReplies.delete(msg_id);
3104
3209
 
3105
3210
  // Refresh the context badge from the peer's registry heartbeat.
3106
3211
  const after = resolveTarget(peer.name);
@@ -3115,11 +3220,17 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3115
3220
  };
3116
3221
  }
3117
3222
  const err = outcome.error;
3223
+ if (err === "timeout") {
3224
+ return {
3225
+ output: `coms dispatch pending after ${Math.round(timeoutMs / 1000)}s (msg_id ${msg_id}). The peer may still complete; use coms_get/coms_await with this msg_id instead of re-dispatching.`,
3226
+ exitCode: 1,
3227
+ elapsed: 0,
3228
+ pending: true,
3229
+ };
3230
+ }
3118
3231
  if (err) {
3119
3232
  return {
3120
- output: err === "timeout"
3121
- ? `coms peer "${peer.name}" did not reply within ${Math.round(timeoutMs / 1000)}s. The peer may still be working in its pane — check it before re-dispatching.`
3122
- : `coms peer "${peer.name}" returned an error: ${err}`,
3233
+ output: `coms peer "${peer.name}" returned an error: ${err}`,
3123
3234
  exitCode: 1,
3124
3235
  elapsed: 0,
3125
3236
  };
@@ -3137,7 +3248,15 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3137
3248
  // runs WHILE the specialist keeps working; only a negative verdict stops the
3138
3249
  // run. Judge failures fail open — a broken judge must never kill good work.
3139
3250
  async function runDriftJudge(
3140
- input: { agentLabel: string; agentKey: string; task: string; scopeGlobs: string[]; trail: string[]; violation: { rule: string; detail: string } },
3251
+ input: {
3252
+ agentLabel: string;
3253
+ agentKey: string;
3254
+ task: string;
3255
+ scopeGlobs: string[];
3256
+ hubOwnedGlobs: string[];
3257
+ trail: string[];
3258
+ violation: { rule: string; terminal?: boolean; detail: string };
3259
+ },
3141
3260
  ctx: any,
3142
3261
  ): Promise<{ verdict: string; reason: string } | null> {
3143
3262
  const researcherDef = allAgentDefs.find(d => d.name.toLowerCase() === "researcher");
@@ -3153,7 +3272,14 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3153
3272
  thinking: "off",
3154
3273
  appendSystemPrompt: "You are a strict, terse runtime watchdog. Answer with exactly one VERDICT line.",
3155
3274
  sessionFile: judgeSession,
3156
- prompt: buildJudgePrompt({ agent: input.agentLabel, task: input.task, scopeGlobs: input.scopeGlobs, trail: input.trail, violation: input.violation }),
3275
+ prompt: buildJudgePrompt({
3276
+ agent: input.agentLabel,
3277
+ task: input.task,
3278
+ scopeGlobs: input.scopeGlobs,
3279
+ hubOwnedGlobs: input.hubOwnedGlobs,
3280
+ trail: input.trail,
3281
+ violation: input.violation,
3282
+ }),
3157
3283
  detached: true,
3158
3284
  turnDeadlineMs: 60_000,
3159
3285
  });
@@ -3166,6 +3292,35 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3166
3292
  }
3167
3293
  }
3168
3294
 
3295
+ // One cheap read-only pass that restates an already-written report in the
3296
+ // structured schema. Runs only when nothing parsed and assertions were tracked
3297
+ // (shouldExtractReturn): the alternative is discarding a whole run's evidence
3298
+ // over a formatting miss. Bounded — one attempt, own deadline, own throwaway
3299
+ // session, never counted against the turn budget — and the caller labels the
3300
+ // result so extracted evidence never passes for declared evidence.
3301
+ async function runReturnExtraction(returnPath: string, assertionIds: string[], _ctx: any): Promise<any | null> {
3302
+ const extractSession = safePathWithin(sessionDir, extractionSessionName(returnPath));
3303
+ try { unlinkSync(extractSession); } catch {}
3304
+ try {
3305
+ const res = await spawnPiAgent({
3306
+ model: EXTRACTION_MODEL,
3307
+ tools: "read",
3308
+ thinking: "off",
3309
+ appendSystemPrompt: "You restate an existing report in a fixed format. You never judge the work and never invent evidence.",
3310
+ sessionFile: extractSession,
3311
+ prompt: buildExtractionPrompt({ returnPath, assertionIds }),
3312
+ detached: true,
3313
+ turnDeadlineMs: EXTRACTION_DEADLINE_MS,
3314
+ });
3315
+ if (res.spawnError || res.exitCode !== 0) return null;
3316
+ return parseStructuredReturn(res.output);
3317
+ } catch {
3318
+ return null;
3319
+ } finally {
3320
+ try { unlinkSync(extractSession); } catch {}
3321
+ }
3322
+ }
3323
+
3169
3324
  async function dispatchAgent(
3170
3325
  agentName: string,
3171
3326
  task: string,
@@ -3173,7 +3328,15 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3173
3328
  inputArtifacts: InputArtifactPreview[] = [],
3174
3329
  scopeGlobs: string[] = [],
3175
3330
  watchdogParam?: boolean,
3176
- ): Promise<{ output: string; exitCode: number; elapsed: number; billed?: number; out?: number }> {
3331
+ ): Promise<{
3332
+ output: string;
3333
+ exitCode: number;
3334
+ elapsed: number;
3335
+ billed?: number;
3336
+ out?: number;
3337
+ sessionReset?: { reason: string; quarantined: string | null; retried: boolean } | null;
3338
+ pending?: boolean;
3339
+ }> {
3177
3340
  const key = normalizeAgentInput(agentName);
3178
3341
  const state = agentStates.get(key);
3179
3342
  if (!state) {
@@ -3211,7 +3374,9 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3211
3374
  const agentKey = safeAgentKey(state.def.name);
3212
3375
  const runNumber = state.runCount;
3213
3376
  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);
3377
+ const monitorStart = monitorTurnId
3378
+ ? monitorBridge?.startChild({ key: monitorKey, id: `run-${agentKey}-${state.runCount}`, generation: 1, parentId: monitorTurnId, specialist: agentKey }, process.env)
3379
+ : undefined;
3215
3380
  const startTime = Date.now();
3216
3381
  state.timer = setInterval(() => {
3217
3382
  state.elapsed = Date.now() - startTime;
@@ -3224,8 +3389,12 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3224
3389
  // at any point. A coms-preferring member with a live same-name pool peer
3225
3390
  // is served by that peer; everything downstream (return contract, ASK_USER,
3226
3391
  // research pipe, history) consumes the same result shape either way.
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"));
3392
+ const finishRun = async (output: string, exitCode: number, opts?: { idle?: boolean; pending?: boolean; notice?: string }) => {
3393
+ await monitorStart?.then(task => monitorBridge?.finalizeChildFor(
3394
+ task,
3395
+ output,
3396
+ opts?.pending ? "blocked" : exitCode === 0 ? "completed" : "failed",
3397
+ ));
3229
3398
  clearInterval(state.timer);
3230
3399
  state.elapsed = Date.now() - startTime;
3231
3400
  state.status = opts?.idle ? "idle" : exitCode === 0 ? "done" : "error";
@@ -3240,7 +3409,7 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3240
3409
  const onTerminate = state.onTerminate;
3241
3410
  state.onTerminate = undefined;
3242
3411
  onTerminate?.();
3243
- return { output, exitCode, elapsed: state.elapsed };
3412
+ return { output, exitCode, elapsed: state.elapsed, ...(opts?.pending ? { pending: true } : {}) };
3244
3413
  };
3245
3414
 
3246
3415
  const personaKey = state.def.name.toLowerCase();
@@ -3273,10 +3442,13 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3273
3442
  if (comsRes) {
3274
3443
  histEntry.name = `${displayName(state.def.name)} (coms)`;
3275
3444
  return finishRun(comsRes.output, comsRes.exitCode, {
3276
- idle: comsRes.abandoned,
3445
+ idle: comsRes.abandoned || comsRes.pending,
3446
+ pending: comsRes.pending,
3277
3447
  notice: comsRes.abandoned
3278
3448
  ? `${displayName(state.def.name)} coms dispatch abandoned (the peer pane keeps running)`
3279
- : `${displayName(state.def.name)} ${comsRes.exitCode === 0 ? "done" : "error"} in ${Math.round((Date.now() - startTime) / 1000)}s (coms peer)`,
3449
+ : comsRes.pending
3450
+ ? `${displayName(state.def.name)} coms dispatch is pending (the peer pane keeps running)`
3451
+ : `${displayName(state.def.name)} ${comsRes.exitCode === 0 ? "done" : "error"} in ${Math.round((Date.now() - startTime) / 1000)}s (coms peer)`,
3280
3452
  });
3281
3453
  }
3282
3454
  // Envelope undeliverable + fallback allowed — continue as a plain native dispatch.
@@ -3284,13 +3456,19 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3284
3456
  state.lastBackend = "native";
3285
3457
  state.comsPeerModel = undefined;
3286
3458
 
3287
- // Per-agent model: a session override (/agent-model, /models) wins;
3459
+ // Per-agent model: a session override (/af-agent-model, /af-models) wins;
3288
3460
  // otherwise the persona's frontmatter `model:` (a full pi spec, e.g.
3289
3461
  // anthropic/claude-opus-4-7). Falls back to the dispatcher's model.
3290
3462
  const model = resolvedModel(state.def)
3291
3463
  ?? (ctx.model
3292
3464
  ? `${ctx.model.provider}/${ctx.model.id}`
3293
3465
  : "openrouter/google/gemini-3-flash-preview");
3466
+ const originalModelFallback = fallbackModelFor(state.def, model);
3467
+
3468
+ // THIS specialist's window, not the dispatcher's. Measuring a 49k local
3469
+ // model against a hosted model's window is what produced readings like
3470
+ // "315%" that nobody could act on.
3471
+ const agentWindow = resolveContextWindow(model, { lookup: modelWindowLookup(ctx), fallbackWindow: contextWindow });
3294
3472
 
3295
3473
  // Session file for this agent
3296
3474
  const agentSessionFile = safePathWithin(sessionDir, `${agentKey}.json`);
@@ -3307,10 +3485,42 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
3307
3485
  state.sessionFile = null;
3308
3486
  state.runsSinceFresh = 0;
3309
3487
  state.contextPct = 0;
3488
+ state.contextTokens = 0;
3310
3489
  sessionRecycled = true;
3311
3490
  turnReport.recycles++;
3312
3491
  sessionTotals.recycles++;
3313
3492
  ctx.ui.notify(`${displayName(state.def.name)}: session recycled (stale context) — starting fresh`, "info");
3493
+ } else {
3494
+ // The reading recycling cannot act on: a fresh session already over a
3495
+ // full window. Surfaced so a mis-resolved contextWindow stays
3496
+ // distinguishable from a genuine single-run overflow.
3497
+ const overflow = contextOverflowDiagnostic(state.runsSinceFresh, state.contextPct, {
3498
+ agent: displayName(state.def.name),
3499
+ model: resolvedModel(state.def) ?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "unknown model"),
3500
+ });
3501
+ if (overflow) ctx.ui.notify(overflow, "warning");
3502
+ }
3503
+
3504
+ // Session health preflight: `--session <file>` is passed on EVERY run, resume
3505
+ // or not, so a single corrupt file bricks the persona — later dispatches die
3506
+ // in ~1s with no output. Neither drop + re-add nor /af-agents-restart could
3507
+ // recover it: both only clear the in-memory pointer while the bad file stays
3508
+ // on disk and keeps reaching pi. So this check is unconditional, not gated on
3509
+ // an intended resume — move the file aside and let the run start clean.
3510
+ let sessionReset: { reason: string; quarantined: string | null; retried: boolean } | null = null;
3511
+ {
3512
+ const health = quarantineIfUnusable(agentSessionFile, sessionHealthIo);
3513
+ if (!health.usable && health.reason) {
3514
+ sessionReset = { reason: health.reason, quarantined: health.quarantined, retried: false };
3515
+ state.sessionFile = null;
3516
+ state.runsSinceFresh = 0;
3517
+ state.contextPct = 0;
3518
+ state.contextTokens = 0;
3519
+ ctx.ui.notify(
3520
+ `${displayName(state.def.name)}: unusable session file quarantined (${health.reason}) — starting fresh`,
3521
+ "warning",
3522
+ );
3523
+ }
3314
3524
  }
3315
3525
 
3316
3526
  // Clarification protocol — every specialist learns to bubble up questions
@@ -3354,13 +3564,13 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3354
3564
  // declared roles/budgets serialized into AGENT_HUB_DELEGATE_CONFIG. The
3355
3565
  // hub pre-creates and tails the dispatch's delegation event dir for the
3356
3566
  // nested card rows. Personas without `subagents:` spawn exactly as before.
3357
- // Effective roles: each role's model replaced by its /agent-model
3567
+ // Effective roles: each role's model replaced by its /af-agent-model
3358
3568
  // "<persona>.<role>" session override when one exists. Serialized into the
3359
3569
  // delegate config, so nested children inherit the switch for free.
3360
3570
  const subagentRoles = state.def.subagents && Object.keys(state.def.subagents).length > 0
3361
3571
  ? Object.fromEntries(Object.entries(state.def.subagents).map(([role, r]) => {
3362
3572
  const override = subagentModelOverrides.get(`${personaKey}.${role.toLowerCase()}`);
3363
- return [role, override ? { ...r, model: override } : r];
3573
+ return [role, override ? applyModelOverride(r, override) : r];
3364
3574
  }))
3365
3575
  : null;
3366
3576
  // Fast mode is a single-specialist path: no nested delegation trees.
@@ -3416,51 +3626,92 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3416
3626
  const appendedSystemPrompt = state.def.systemPrompt + clarificationProtocol + rulesProtocol + docsProtocol + delegationProtocol + deliverableProtocol;
3417
3627
 
3418
3628
  // Per-agent thinking: the persona's `thinking:` frontmatter (or a
3419
- // /agent-model-thinking session override) sets the pi --thinking reasoning
3420
- // level. Non-off also enables thinking deltas in the JSON stream so `/zoom`
3629
+ // /af-agent-model-thinking session override) sets the pi --thinking reasoning
3630
+ // level. Non-off also enables thinking deltas in the JSON stream so `/af-zoom`
3421
3631
  // can show the reasoning.
3422
3632
  const thinkingLevel = resolveThinkingLevel(resolvedThinking(state.def));
3423
3633
  const wantThinking = thinkingLevel !== "off";
3424
3634
 
3425
3635
  // ── Drift watchdog: layer-1 rules on the live stream, judge on escalation ──
3426
- // Precedence: dispatch param > per-agent /watchdog override > hub setting.
3636
+ // Precedence: dispatch param > per-agent /af-watchdog override > hub setting.
3427
3637
  const watchdogArmed = resolveWatchdogActive(watchdogParam, watchdogAgentOverrides.get(key), watchdogSetting);
3428
- const driftMonitor = watchdogArmed ? createDriftMonitor({ scopeGlobs }) : null;
3638
+ // The hub ORDERS every specialist to write its deliverable under the session
3639
+ // artifacts tree, which no dispatcher `scope:` ever lists — so those paths are
3640
+ // implicitly in scope. Both path forms: the specialist may use either.
3641
+ const hubOwnedGlobs = hubOwnedScopeGlobs(sessionDir, path.relative(ctx.cwd || process.cwd(), sessionDir));
3642
+ const driftMonitor = watchdogArmed ? createDriftMonitor({ scopeGlobs, allowGlobs: hubOwnedGlobs }) : null;
3429
3643
  let driftControl: PiRunControl | undefined;
3430
3644
  let driftStop: { rule: string; detail: string; verdict: string; reason: string } | null = null;
3645
+ // Advisory signals (scope) that the judge called drift: reported to the
3646
+ // dispatcher, never fatal. The post-run scope gate reverts nothing, so the
3647
+ // live rule watching the same thing must not kill either.
3648
+ const driftAdvisories: { rule: string; detail: string; verdict: string; reason: string }[] = [];
3431
3649
  let judgeBusy = false;
3432
3650
  let judgeCooldownUntil = 0;
3433
- const escalateDrift = (violation: { rule: string; detail: string }) => {
3651
+ const escalateDrift = (violation: { rule: string; terminal?: boolean; detail: string }) => {
3434
3652
  if (!driftMonitor || judgeBusy || driftStop || Date.now() < judgeCooldownUntil) return;
3435
3653
  judgeBusy = true;
3436
3654
  void runDriftJudge(
3437
- { agentLabel: displayName(state.def.name), agentKey, task, scopeGlobs, trail: driftMonitor.trail(), violation },
3655
+ { agentLabel: displayName(state.def.name), agentKey, task, scopeGlobs, hubOwnedGlobs, trail: driftMonitor.trail(), violation },
3438
3656
  ctx,
3439
3657
  ).then(v => {
3440
3658
  judgeBusy = false;
3441
3659
  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");
3660
+ if (!v || (v.verdict !== "drifting" && v.verdict !== "stuck")) return;
3661
+ if (violation.terminal === false) {
3662
+ driftAdvisories.push({ rule: violation.rule, detail: violation.detail, verdict: v.verdict, reason: v.reason });
3663
+ return;
3445
3664
  }
3665
+ driftStop = { rule: violation.rule, detail: violation.detail, verdict: v.verdict, reason: v.reason };
3666
+ driftControl?.terminate("drift_stop");
3446
3667
  }).catch(() => { judgeBusy = false; });
3447
3668
  };
3448
3669
 
3449
3670
  // Spawn via the shared helper — first run creates the session, subsequent
3450
3671
  // runs resume it (-c). Stream events drive the card + zoom timeline.
3451
- // `detached` puts the specialist in its own process group so /agents-kill
3672
+ // `detached` puts the specialist in its own process group so /af-agents-kill
3452
3673
  // can SIGTERM the whole delegation tree (killPiTree).
3453
3674
  let fullText = "";
3454
3675
  let runBilled = 0;
3455
3676
  let runOut = 0;
3456
- const res = await spawnPiAgent({
3677
+ let overWindowWarned = false;
3678
+ const runPrompt = appendDeclaredScope(appendInputArtifacts(task, inputArtifacts), scopeGlobs);
3679
+
3680
+ // Pre-spawn overflow guard. The threshold check above runs on the PREVIOUS
3681
+ // run's percentage; this one asks whether THIS prompt still fits before we
3682
+ // pay for it. Recycling after the run is what made the post-mortem's
3683
+ // warnings land 985s of billed work too late.
3684
+ if (state.sessionFile && !sessionRecycled) {
3685
+ const overflow = shouldRecycleBeforeSpawn({
3686
+ priorTokens: state.contextTokens,
3687
+ promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(appendedSystemPrompt),
3688
+ window: agentWindow.window,
3689
+ });
3690
+ if (overflow) {
3691
+ try { unlinkSync(agentSessionFile); } catch {}
3692
+ state.sessionFile = null;
3693
+ state.runsSinceFresh = 0;
3694
+ state.contextPct = 0;
3695
+ state.contextTokens = 0;
3696
+ sessionRecycled = true;
3697
+ turnReport.recycles++;
3698
+ sessionTotals.recycles++;
3699
+ ctx.ui.notify(
3700
+ `${displayName(state.def.name)}: session recycled before spawn — ${overflow.message}. ` +
3701
+ "Resuming would have overflowed the window mid-run; the task text and artifact paths carry the state.",
3702
+ "info",
3703
+ );
3704
+ }
3705
+ }
3706
+
3707
+ const spawnOptions: SpawnPiAgentOptions = {
3457
3708
  model,
3458
3709
  tools: effectiveTools,
3459
3710
  thinking: thinkingLevel,
3460
3711
  appendSystemPrompt: appendedSystemPrompt,
3461
3712
  sessionFile: agentSessionFile,
3462
3713
  resume: !!state.sessionFile,
3463
- prompt: appendDeclaredScope(appendInputArtifacts(task, inputArtifacts), scopeGlobs),
3714
+ prompt: runPrompt,
3464
3715
  extensions,
3465
3716
  env: { ...guardrailEnv(agentKey), ...(delegateEnv || {}) },
3466
3717
  detached: true,
@@ -3469,8 +3720,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3469
3720
  ...(RESEARCHER_PERSONAS.has(personaKey) ? { toolWatchdog: { timeoutMs: reconSearchTimeoutMs } } : {}),
3470
3721
  // Whole-run deadline from the active mode's budget (null in strict mode).
3471
3722
  turnDeadlineMs: turnBudget.agentTurnMs,
3472
- }, {
3723
+ };
3724
+ const spawnCallbacks: SpawnPiAgentCallbacks = {
3473
3725
  onProcess: (p) => { state.proc = p; void monitorStart?.then(task => monitorBridge?.registerOwnedProcessFor(task, p)); },
3726
+ onModelFallback: ({ from, to, reason }) => {
3727
+ state.lastWork = `model fallback: ${shortModel(from)} → ${shortModel(to)}`;
3728
+ ctx.ui.notify(`${displayName(state.def.name)}: overridden model ${from} failed before work began; retrying with persona model ${to} (${reason})`, "warning");
3729
+ updateWidget();
3730
+ },
3474
3731
  ...(driftMonitor ? { onControl: (c: PiRunControl) => { driftControl = c; } } : {}),
3475
3732
  onTextDelta: (delta) => {
3476
3733
  void monitorStart?.then(task => monitorBridge?.appendOutputFor(task, delta));
@@ -3509,21 +3766,75 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3509
3766
  runBilled += (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
3510
3767
  runOut += usage.output || 0;
3511
3768
  }
3512
- if (contextWindow > 0) {
3769
+ if (agentWindow.window > 0) {
3513
3770
  // Real context = fresh input + cache reads + cache writes. Counting
3514
3771
  // usage.input alone showed 1–20% while tens of thousands of cached
3515
3772
  // 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;
3773
+ state.contextTokens = (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
3774
+ state.contextPct = contextPct(usage, agentWindow.window);
3775
+ // Once per run: a reading over a full window is either a wrong
3776
+ // window or a real overflow, and the source line is what tells
3777
+ // them apart. Silent 315% readings are how this went unfixed.
3778
+ if (state.contextPct >= 100 && !overWindowWarned) {
3779
+ overWindowWarned = true;
3780
+ ctx.ui.notify(
3781
+ overWindowDiagnostic({
3782
+ agent: displayName(state.def.name),
3783
+ model,
3784
+ pct: state.contextPct,
3785
+ window: agentWindow.window,
3786
+ source: agentWindow.source,
3787
+ }),
3788
+ "warning",
3789
+ );
3790
+ }
3517
3791
  updateWidget();
3518
3792
  }
3519
3793
  },
3794
+ };
3795
+ notifyProviderQueue(model, displayName(state.def.name), ctx);
3796
+ // One permit for the whole dispatch, corrupt-session retry included: the
3797
+ // retry is the same run starting over, not a second request to schedule.
3798
+ const res = await providerSemaphore.run(model, async () => {
3799
+ let r = await spawnPiAgentWithModelFallback(spawnOptions, originalModelFallback, spawnCallbacks);
3800
+
3801
+ // Post-hoc corrupt-session detection: the preflight cannot model every
3802
+ // reason pi refuses a session file. This signature — non-zero exit, no
3803
+ // output at all, "not a valid pi session" on stderr — means the run never
3804
+ // started, so exactly one retry on a clean session is safe and cannot
3805
+ // duplicate work. Any other failure stays a failure.
3806
+ if (!r.spawnError && isCorruptSessionExit({ code: r.exitCode, output: r.output, stderr: r.stderr })) {
3807
+ const quarantine = forceQuarantineSession(agentSessionFile, sessionHealthIo);
3808
+ state.sessionFile = null;
3809
+ state.runsSinceFresh = 0;
3810
+ state.contextPct = 0;
3811
+ state.contextTokens = 0;
3812
+ sessionReset = {
3813
+ reason: quarantine.ok ? "pi rejected the session file" : quarantine.error!,
3814
+ quarantined: quarantine.quarantined,
3815
+ retried: quarantine.ok,
3816
+ };
3817
+ if (quarantine.ok) {
3818
+ ctx.ui.notify(
3819
+ `${displayName(state.def.name)}: pi rejected the session file — quarantined, retrying once from a clean session`,
3820
+ "warning",
3821
+ );
3822
+ r = await spawnPiAgentWithModelFallback({ ...spawnOptions, resume: false }, originalModelFallback, spawnCallbacks);
3823
+ } else {
3824
+ ctx.ui.notify(
3825
+ `${displayName(state.def.name)}: pi rejected the session file, but it could not be quarantined — clean retry refused (${quarantine.error})`,
3826
+ "error",
3827
+ );
3828
+ }
3829
+ }
3830
+ return r;
3520
3831
  });
3521
3832
 
3522
3833
  clearInterval(state.timer);
3523
3834
  state.elapsed = Date.now() - startTime;
3524
3835
  state.proc = undefined;
3525
3836
  // Stop tailing the delegation event file (one final drain inside close,
3526
- // so trailing exit/usage events land). Child states stay for /zoom.
3837
+ // so trailing exit/usage events land). Child states stay for /af-zoom.
3527
3838
  state.delegationsWatcher?.close();
3528
3839
  state.delegationsWatcher = undefined;
3529
3840
 
@@ -3580,7 +3891,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3580
3891
  ? `was stopped by the drift watchdog. Rule "${driftStop?.rule || "unknown"}" fired (${driftStop?.detail || "no detail"}); ` +
3581
3892
  `judge verdict ${(driftStop?.verdict || "drifting").toUpperCase()}: ${driftStop?.reason || "(no reason given)"}. ` +
3582
3893
  `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`
3894
+ `If you believe the watchdog is wrong, tell the user; they can disable it with /af-watchdog ${key} off`
3584
3895
  : "was cancelled by its caller";
3585
3896
  return {
3586
3897
  output: `${reason}: agent ${displayName(state.def.name)} ${explanation}; terminationConfirmed=${res.termination.confirmed}.` +
@@ -3592,14 +3903,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3592
3903
  };
3593
3904
  }
3594
3905
 
3595
- // Operator kill (Phase 2). The exit was a SIGTERM from /agents-kill or
3596
- // /agents-restart, not a real completion: free the card (status → idle),
3906
+ // Operator kill (Phase 2). The exit was a SIGTERM from /af-agents-kill or
3907
+ // /af-agents-restart, not a real completion: free the card (status → idle),
3597
3908
  // fire any restart waiter, and return a message that tells the dispatcher
3598
- // LLM not to auto-retry. /agents-restart handles the fresh re-dispatch.
3909
+ // LLM not to auto-retry. /af-agents-restart handles the fresh re-dispatch.
3599
3910
  if (state.killedByOperator) {
3600
3911
  await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, "operator killed run", "cancelled"));
3601
3912
  // !! (not `=== true`): TS otherwise narrows the field to the `false`
3602
- // assigned during setup — the concurrent /agents-restart mutation that
3913
+ // assigned during setup — the concurrent /af-agents-restart mutation that
3603
3914
  // makes this true is invisible to the checker across the await.
3604
3915
  const wasRestart = !!state.restarting;
3605
3916
  state.killedByOperator = false;
@@ -3642,7 +3953,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3642
3953
  );
3643
3954
 
3644
3955
  // Let a restart waiter proceed even when the agent finished naturally
3645
- // between the operator's /agents-restart and the kill landing.
3956
+ // between the operator's /af-agents-restart and the kill landing.
3646
3957
  const onTerminate = state.onTerminate;
3647
3958
  state.onTerminate = undefined;
3648
3959
  onTerminate?.();
@@ -3651,6 +3962,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3651
3962
  // (e.g. a bad --model spec or a provider whose API key isn't configured)
3652
3963
  // reach the dispatcher as a readable message instead of an empty result.
3653
3964
  let output = full;
3965
+ if (res.modelFallback) {
3966
+ output = `(ℹ model fallback: ${res.modelFallback.from} failed before work began; retried once with original persona model ${res.modelFallback.to}.)\n\n${output}`;
3967
+ }
3654
3968
  if (code !== 0) {
3655
3969
  const errText = res.stderr.trim();
3656
3970
  const tail = errText.length > 1500 ? "...\n" + errText.slice(-1500) : errText;
@@ -3662,6 +3976,21 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3662
3976
  if (sessionRecycled) {
3663
3977
  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
3978
  }
3979
+ if (driftAdvisories.length > 0) {
3980
+ output += `\n\n⚠ Drift advisory (run NOT stopped): ` +
3981
+ driftAdvisories.map(a => `rule "${a.rule}" — ${a.detail}; judge said ${a.verdict.toUpperCase()}: ${a.reason || "(no reason)"}`).join(" | ") +
3982
+ `\nReview whether the work still serves the task; nothing was reverted and nothing was killed.`;
3983
+ }
3984
+ if (sessionReset) {
3985
+ // Named explicitly so a reset never reads as "the specialist failed" —
3986
+ // that misreading is what turned a broken file into a dropped persona.
3987
+ const resetSummary = sessionReset.retried
3988
+ ? `was unusable and was quarantined${sessionReset.quarantined ? ` to ${sessionReset.quarantined}` : ""} (${sessionReset.reason}). This run started from a clean session after one automatic retry — the agent has no memory of earlier dispatches, and this is NOT a reason to drop it from the team.`
3989
+ : sessionReset.quarantined
3990
+ ? `was unusable and was quarantined to ${sessionReset.quarantined} (${sessionReset.reason}) before the run. This run started from a clean session — the agent has no memory of earlier dispatches.`
3991
+ : `was rejected by pi but could not be quarantined (${sessionReset.reason}). No clean retry was attempted; fix the file permissions/path before retrying.`;
3992
+ output = `(⚠ ${displayName(state.def.name)}'s session file ${resetSummary})\n\n${output}`;
3993
+ }
3665
3994
 
3666
3995
  return {
3667
3996
  output,
@@ -3669,6 +3998,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3669
3998
  elapsed: state.elapsed,
3670
3999
  billed: runBilled,
3671
4000
  out: runOut,
4001
+ sessionReset,
3672
4002
  };
3673
4003
  }
3674
4004
 
@@ -3690,7 +4020,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3690
4020
  }
3691
4021
 
3692
4022
  // Resolve the model for a research helper: an explicit --model wins, then the
3693
- // persona's resolved model (session override via /agent-model → frontmatter
4023
+ // persona's resolved model (session override via /af-agent-model → frontmatter
3694
4024
  // default), then the dispatcher's model (the default for anon helpers).
3695
4025
  function resolveResearchModel(def: AgentDef, explicit: string | undefined, ctx: any): string {
3696
4026
  if (explicit) return explicit;
@@ -3726,7 +4056,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3726
4056
  // handles are never resumed) and finished durable helpers beyond the
3727
4057
  // `research-keep` most recent — so the research row doesn't grow without
3728
4058
  // bound. Running helpers are untouched; ids stay monotonic (no handle reuse).
3729
- // /agents-history is unaffected: the timeline holds its own entries.
4059
+ // /af-agents-history is unaffected: the timeline holds its own entries.
3730
4060
  function pruneResearch() {
3731
4061
  const ids = selectResearchPrunable(Array.from(researchStates.values()), researchKeep);
3732
4062
  if (ids.length === 0) return;
@@ -3751,7 +4081,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3751
4081
  // Spawn (or resume) a read-only research helper. Mirrors dispatchAgent's stream
3752
4082
  // handling but is forced read-only (RESEARCH_TOOLS), drives the research widget, and
3753
4083
  // resolves with the findings — the CALLER decides what to do with them (the
3754
- // spawn_research tool returns them inline; the /research command delivers a follow-up).
4084
+ // spawn_research tool returns them inline; the /af-research command delivers a follow-up).
3755
4085
  async function spawnResearch(
3756
4086
  state: ResearchState,
3757
4087
  prompt: string,
@@ -3785,7 +4115,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3785
4115
 
3786
4116
  // READ-ONLY by construction: RESEARCH_TOOLS only, regardless of persona frontmatter.
3787
4117
  let fullText = "";
3788
- const res = await spawnPiAgent({
4118
+ const researchWindow = resolveContextWindow(state.model, { lookup: modelWindowLookup(ctx), fallbackWindow: contextWindow });
4119
+ notifyProviderQueue(state.model, `Research r${state.id}`, ctx);
4120
+ const res = await providerSemaphore.run(state.model, () => spawnPiAgentWithModelFallback({
3789
4121
  model: state.model,
3790
4122
  tools: RESEARCH_TOOLS,
3791
4123
  thinking: thinkingLevel,
@@ -3804,8 +4136,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3804
4136
  ...researchWatchdogSpawnOptions(reconSearchTimeoutMs, signal),
3805
4137
  // Whole-run deadline from the active mode's budget (null in strict mode).
3806
4138
  turnDeadlineMs: currentBudget().agentTurnMs,
3807
- }, {
4139
+ }, fallbackModelFor(state.def, state.model), {
3808
4140
  onProcess: (p) => { state.proc = p; },
4141
+ onModelFallback: ({ from, to, reason }) => {
4142
+ state.lastWork = `model fallback: ${shortModel(from)} → ${shortModel(to)}`;
4143
+ ctx.ui.notify(`Research r${state.id}: overridden model ${from} failed before work began; retrying with persona model ${to} (${reason})`, "warning");
4144
+ updateResearchWidget();
4145
+ },
3809
4146
  onTextDelta: (delta) => {
3810
4147
  fullText += delta;
3811
4148
  state.lastWork = fullText.split("\n").filter((l: string) => l.trim()).pop() || "";
@@ -3830,13 +4167,18 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3830
4167
  state.zoomRender?.();
3831
4168
  },
3832
4169
  onUsage: (usage) => {
3833
- if (contextWindow > 0) {
3834
- // Same context truth as dispatchAgent: include cache reads/writes.
3835
- state.contextPct = (((usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0)) / contextWindow) * 100;
4170
+ if (researchWindow.window > 0) {
4171
+ // Same context truth as dispatchAgent: include cache reads/writes,
4172
+ // measured against THIS helper's window rather than the dispatcher's.
4173
+ state.contextPct = contextPct(usage, researchWindow.window);
3836
4174
  updateResearchWidget();
3837
4175
  }
3838
4176
  },
3839
- });
4177
+ }, {
4178
+ // Read-only by construction (RESEARCH_TOOLS), so a provider failure
4179
+ // mid-run is recoverable: re-running a reader repeats nothing.
4180
+ midRun: isReadOnlyToolList(RESEARCH_TOOLS),
4181
+ }));
3840
4182
 
3841
4183
  clearInterval(state.timer);
3842
4184
  state.elapsed = Date.now() - startTime;
@@ -3879,7 +4221,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3879
4221
  };
3880
4222
  }
3881
4223
 
3882
- // Operator kill (via /agents-kill rN|all or its research-* aliases).
4224
+ // Operator kill (via /af-agents-kill rN|all or its research-* aliases).
3883
4225
  // Resolve gracefully so a spawn_research tool call awaiting this helper
3884
4226
  // doesn't hang.
3885
4227
  if (state.killedByOperator) {
@@ -3913,6 +4255,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3913
4255
  );
3914
4256
 
3915
4257
  let output = full;
4258
+ if (res.modelFallback) {
4259
+ output = `(ℹ model fallback: ${res.modelFallback.from} failed before work began; retried once with original persona model ${res.modelFallback.to}.)\n\n${output}`;
4260
+ }
3916
4261
  if (code !== 0) {
3917
4262
  const errText = res.stderr.trim();
3918
4263
  const tail = errText.length > 1500 ? "...\n" + errText.slice(-1500) : errText;
@@ -3925,7 +4270,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3925
4270
  return { output, exitCode: code ?? 1, elapsed: state.elapsed };
3926
4271
  }
3927
4272
 
3928
- // Deliver a /research result back to the dispatcher as a follow-up turn (the human
4273
+ // Deliver a /af-research result back to the dispatcher as a follow-up turn (the human
3929
4274
  // kicked it off via slash command, so there is no awaiting tool call to return to).
3930
4275
  function deliverResearchFollowUp(state: ResearchState, result: { output: string; exitCode: number; elapsed: number }) {
3931
4276
  const truncated = result.output.length > 8000
@@ -4054,6 +4399,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4054
4399
  color: ident?.color ?? "#36F9F6",
4055
4400
  context_used_pct: pct,
4056
4401
  queue_depth: inboundQueue.size,
4402
+ pane_id: herdrPaneId() ?? null,
4403
+ status: turnState === "working" || inboundQueue.size > 0 ? "working" : "idle",
4057
4404
  };
4058
4405
  const pong: Pong = { type: "pong", msg_id: env.msg_id, agent_card: card };
4059
4406
  try {
@@ -4141,22 +4488,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4141
4488
  if (!identity) return;
4142
4489
  try {
4143
4490
  const ctx = currentCtx;
4144
- const live: RegistryEntry = {
4145
- session_id: identity.session_id,
4146
- name: identity.name,
4147
- purpose: identity.purpose,
4148
- model: ctx?.model?.id ?? identity.model,
4149
- color: identity.color,
4491
+ const live: RegistryEntry = buildLiveRegistryEntry(identity, {
4492
+ now: nowIso(),
4150
4493
  pid: process.pid,
4151
- endpoint: identity.endpoint,
4152
- cwd: identity.cwd,
4153
- started_at: nowIso(),
4154
- explicit: identity.explicit,
4155
- version: 1,
4156
- context_used_pct: Math.round(ctx?.getContextUsage()?.percent ?? 0),
4157
- queue_depth: inboundQueue.size,
4158
- heartbeat_at: nowIso(),
4159
- };
4494
+ model: ctx?.model?.id,
4495
+ contextUsedPct: ctx?.getContextUsage()?.percent,
4496
+ queueDepth: inboundQueue.size,
4497
+ });
4160
4498
  writeRegistryAtomic(live, identity.project);
4161
4499
  } catch {
4162
4500
  // best-effort
@@ -4403,10 +4741,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4403
4741
 
4404
4742
  // The peers currently in scope — exactly what the coms pool widget shows: live
4405
4743
  // (pruned) registry entries in the displayed project (displayProject, or the home
4406
- // project; "*" only when the human widened via /coms --project *), excluding self
4407
- // and — unless /coms --all set includeExplicit — explicit peers. This is the
4744
+ // project; "*" only when the human widened via /af-coms --project *), excluding self
4745
+ // and — unless /af-coms --all set includeExplicit — explicit peers. This is the
4408
4746
  // SECURITY BOUNDARY for every coms op: list, send, and handoff resolve only within
4409
- // it. Widening it is a deliberate human action via /coms, never something the LLM
4747
+ // it. Widening it is a deliberate human action via /af-coms, never something the LLM
4410
4748
  // can do on its own. Single source of truth — reused by the widget refresh, the
4411
4749
  // handoff completions, coms_list, and resolveTarget so they can never diverge.
4412
4750
  function peersInScope(): RegistryEntry[] {
@@ -4419,8 +4757,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4419
4757
  }
4420
4758
 
4421
4759
  // Join herdr's live pane states back to the coms registry: a herdr agent
4422
- // whose custom_status leads with a peer name maps to that peer's registry
4423
- // entry (which carries the full card the 32-char custom_status cannot).
4760
+ // that advertises a coms peer name maps to that peer's registry entry
4761
+ // (which carries the full card a pane annotation has no room for).
4424
4762
  // Pool-scope semantics are preserved — only entries from peersInScope()
4425
4763
  // become cards; peers outside herdr panes stay visible as registry-only
4426
4764
  // "pending" rows exactly like an unpinged peer in the files backend.
@@ -4428,7 +4766,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4428
4766
  if (!identity) return;
4429
4767
  const liveNames = new Set<string>();
4430
4768
  for (const a of agents) {
4431
- const peerName = parsePeerName(a.custom_status as string | undefined);
4769
+ const peerName = peerNameFrom(a);
4432
4770
  if (peerName) liveNames.add(peerName);
4433
4771
  }
4434
4772
  let changed = false;
@@ -4467,7 +4805,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4467
4805
  // Scoped to the connected pool only (peersInScope): you can reach exactly the
4468
4806
  // peers the widget shows. Match by name first (preferred, human-facing), then by
4469
4807
  // session_id. A peer outside the current scope is intentionally NOT resolved — the
4470
- // human must widen scope via /coms --project / --all first. This closes the old
4808
+ // human must widen scope via /af-coms --project / --all first. This closes the old
4471
4809
  // cross-project leak where a name match fell through to scanning every project.
4472
4810
  const scope = peersInScope();
4473
4811
  const byName = scope.find((e) => e.name === target);
@@ -4486,7 +4824,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4486
4824
  task: Type.String({ description: "Task description for the agent to execute" }),
4487
4825
  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." }))),
4488
4826
  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)." })),
4827
+ watchdog: Type.Optional(Type.Boolean({ description: "Force the drift watchdog on/off for THIS dispatch (default: per-agent /af-watchdog override, then the hub-wide setting)." })),
4490
4828
  }),
4491
4829
 
4492
4830
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
@@ -4530,6 +4868,24 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4530
4868
  details: { agent, task, status: "duplicate_refused", elapsed: 0, exitCode: 1, fullOutput: "" },
4531
4869
  };
4532
4870
  }
4871
+ // Input artifacts resolve BEFORE the dispatch is counted. Validation used to
4872
+ // run after the increment, so four "Artifact not found" typos each burned a
4873
+ // real budget slot — and the turn budget was exhausted three times in the
4874
+ // same session. A path the hub cannot resolve is a pre-flight error: nothing
4875
+ // was spawned, so nothing should be charged.
4876
+ let inputArtifacts: InputArtifactPreview[];
4877
+ try {
4878
+ inputArtifacts = loadInputArtifacts(artifacts, ctx);
4879
+ } catch (err: any) {
4880
+ return {
4881
+ content: [{
4882
+ type: "text",
4883
+ text: `⚠ Dispatch NOT sent and NOT counted against the turn budget — input artifact could not be resolved:\n` +
4884
+ `${err?.message || err}\n\nFix the path and dispatch again.`,
4885
+ }],
4886
+ details: { agent, task, status: "artifact_preflight_failed", elapsed: 0, exitCode: 1, fullOutput: "" },
4887
+ };
4888
+ }
4533
4889
  turnDispatchCount++;
4534
4890
  sessionTotals.dispatches++;
4535
4891
  updateModeStatus();
@@ -4547,7 +4903,6 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4547
4903
  }
4548
4904
 
4549
4905
  const dispatchedAssertionIds = extractAssertionIds(task);
4550
- const inputArtifacts = loadInputArtifacts(artifacts, ctx);
4551
4906
  const scopeGlobs = (scope || []).map(s => String(s).trim()).filter(Boolean);
4552
4907
  const stateForScope = agentStates.get(agent.toLowerCase());
4553
4908
  const agentCanWrite = !!stateForScope && hasWriteCapability(stateForScope.def.tools);
@@ -4623,14 +4978,46 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4623
4978
  }
4624
4979
  }
4625
4980
 
4626
- const parsedReturn = parseStructuredReturn(result.output);
4627
- const contractNotices = crossCheck(parsedReturn, dispatchedAssertionIds);
4981
+ const disposition = deliveryDisposition(result.exitCode, result.pending === true);
4982
+ const pendingDelivery = disposition.pending;
4983
+ const delivered = disposition.delivered;
4984
+ let { parsed: parsedReturn, notices: contractNotices } = parseDeliveredReturn(
4985
+ result.output,
4986
+ dispatchedAssertionIds,
4987
+ delivered,
4988
+ );
4628
4989
  const shouldUseDigest = dispatchedAssertionIds.length > 0 || !!parsedReturn;
4629
4990
  const state = agentStates.get(agent.toLowerCase());
4630
4991
  const agentKey = safeAgentKey(state?.def.name ?? agent);
4631
- const returnPath = shouldUseDigest
4632
- ? writeReturnArtifact(agentKey, state?.runCount ?? 0, result.output)
4992
+ // A failed run delivered no result. Its output — a coms error, a
4993
+ // timeout stub, a truncated crash — goes to failures/, never returns/:
4994
+ // a return path is read as "the specialist answered", and one 142-byte
4995
+ // error stub filed as a return cost a 103s dispatch investigating a
4996
+ // review that had actually succeeded.
4997
+ const runArtifactPath = disposition.artifactKind && (shouldUseDigest || !delivered)
4998
+ ? writeRunArtifact(agentKey, state?.runCount ?? 0, result.output, disposition.artifactKind)
4633
4999
  : null;
5000
+ const returnPath = delivered ? runArtifactPath : null;
5001
+ const failurePath = delivered ? null : runArtifactPath;
5002
+
5003
+ // Nothing parsed but assertions were tracked: give the report one cheap
5004
+ // read-only pass before writing the whole run off as unproven. Never on
5005
+ // a failure — there is no report to extract from.
5006
+ let returnExtracted = false;
5007
+ if (returnPath && shouldExtractReturn(parsedReturn, dispatchedAssertionIds)) {
5008
+ if (onUpdate) {
5009
+ onUpdate({
5010
+ content: [{ type: "text", text: `${agent} returned no structured block — extracting it from the report...` }],
5011
+ details: { agent, task, status: "extracting_return" },
5012
+ });
5013
+ }
5014
+ const recovered = await runReturnExtraction(returnPath, dispatchedAssertionIds, ctx);
5015
+ if (recovered) {
5016
+ parsedReturn = recovered;
5017
+ contractNotices = crossCheck(recovered, dispatchedAssertionIds);
5018
+ returnExtracted = true;
5019
+ }
5020
+ }
4634
5021
 
4635
5022
  const truncated = result.output.length > 8000
4636
5023
  ? result.output.slice(0, 8000) + "\n\n... [truncated]"
@@ -4639,7 +5026,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4639
5026
  // Extract bubble-up questions emitted via the clarification protocol.
4640
5027
  const questions = extractAskUserQuestions(result.output);
4641
5028
 
4642
- const status = result.exitCode === 0 ? "done" : "error";
5029
+ const status = disposition.status;
4643
5030
  // Record the fingerprint only for completed or watchdog/deadline-stopped
4644
5031
  // runs — those must not be repeated unchanged. A failed spawn or plain
4645
5032
  // error stays retryable (the failure may be transient).
@@ -4668,17 +5055,43 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4668
5055
  : "";
4669
5056
 
4670
5057
  const returnPathNotice = returnPath ? `\n\nFull specialist output: ${returnPath}` : "";
5058
+ // Named as a delivery failure, not a result: the run did not answer.
5059
+ // Whether the work itself succeeded is unknown from here — a lost coms
5060
+ // reply looks identical to a crash, and treating the stub as a verdict
5061
+ // is what turned a successful review into a re-investigation.
5062
+ const pendingNotice = pendingDelivery
5063
+ ? `\n\n⏳ DELIVERY PENDING — no result or assertion evidence is available yet, and no return/failure artifact was written. Use the msg_id above with coms_get/coms_await; do not re-dispatch.`
5064
+ : "";
5065
+ const failurePathNotice = failurePath
5066
+ ? `\n\n⚠ DELIVERY FAILURE (exit ${result.exitCode}) — no specialist result was returned. ` +
5067
+ `The error output is at ${failurePath}; it is NOT a return and carries no assertion evidence. ` +
5068
+ "The work may or may not have happened — check the artifacts the task was supposed to produce before re-dispatching."
5069
+ : "";
5070
+ // Tell the dispatcher which path actually held the file, so the next
5071
+ // dispatch names it directly instead of guessing the kind again.
5072
+ const corrected = inputArtifacts.filter(a => a.resolvedFromKind);
5073
+ const artifactKindNotice = corrected.length > 0
5074
+ ? `\n\nℹ Artifact path corrected: ${corrected.map(a => `"${a.input}" → ${a.displayPath}`).join("; ")}. ` +
5075
+ `Use the corrected path from now on.`
5076
+ : "";
4671
5077
  const contextNotice = state && contextPressure(state.contextPct)
4672
- ? `\n\n⚠ ${displayName(state.def.name)} context at ${Math.ceil(state.contextPct)}% — consider /agents-restart ${state.def.name} (state lives in the artifacts/ledger, a restart is cheap).`
5078
+ ? `\n\n⚠ ${displayName(state.def.name)} context at ${Math.ceil(state.contextPct)}% — consider /af-agents-restart ${state.def.name} (state lives in the artifacts/ledger, a restart is cheap).`
4673
5079
  : "";
4674
5080
  const scopeNotice = scopeNoticeText(scopeViolations);
4675
5081
  const contractNotice = contractNoticeText(contractNotices);
5082
+ // An extracted block is labelled every time it is shown: it was restated
5083
+ // by a cheap pass, not declared by the specialist, and it must never be
5084
+ // mistaken for first-hand evidence when gating on it.
5085
+ const extractionNotice = returnExtracted
5086
+ ? `ℹ The specialist declared no structured return. The block below was EXTRACTED from its report ` +
5087
+ `by a cheap read-only pass — weaker than a declared return. Verify the named evidence before you gate on it.`
5088
+ : "";
4676
5089
  const digest = shouldUseDigest
4677
- ? [structuredReturnDigest(parsedReturn) || "Structured return: (none parsed)", contractNotice].filter(Boolean).join("\n\n")
5090
+ ? [extractionNotice, structuredReturnDigest(parsedReturn) || "Structured return: (none parsed)", contractNotice].filter(Boolean).join("\n\n")
4678
5091
  : truncated;
4679
5092
 
4680
5093
  return {
4681
- content: [{ type: "text", text: `${summary}${questionsNotice}${researchNotice}${budgetNotice}${returnPathNotice}${contextNotice}${scopeNotice}\n\n${digest}` }],
5094
+ content: [{ type: "text", text: `${summary}${questionsNotice}${researchNotice}${budgetNotice}${returnPathNotice}${pendingNotice}${failurePathNotice}${artifactKindNotice}${contextNotice}${scopeNotice}\n\n${digest}` }],
4682
5095
  details: {
4683
5096
  agent,
4684
5097
  task,
@@ -4687,12 +5100,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4687
5100
  exitCode: result.exitCode,
4688
5101
  fullOutput: result.output,
4689
5102
  structuredReturn: parsedReturn,
5103
+ returnExtracted,
5104
+ pending: pendingDelivery,
4690
5105
  returnPath,
5106
+ failurePath,
4691
5107
  contractNotices,
4692
5108
  questions,
4693
5109
  researchRounds,
4694
5110
  scopeViolations,
4695
- artifacts: inputArtifacts.map(a => ({ path: a.path, displayPath: a.displayPath, preview: a.preview })),
5111
+ sessionReset: result.sessionReset ?? null,
5112
+ artifacts: inputArtifacts.map(a => ({ path: a.path, displayPath: a.displayPath, preview: a.preview, resolvedFromKind: a.resolvedFromKind ?? null })),
4696
5113
  },
4697
5114
  };
4698
5115
  } catch (err: any) {
@@ -4777,7 +5194,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4777
5194
  const { task, persona, model, artifacts } = params as { task: string; persona?: string; model?: string; artifacts?: string[] };
4778
5195
 
4779
5196
  // Turn-budget gate (dispatcher-initiated research only — the auto-research
4780
- // pipe and the /research command are exempt).
5197
+ // pipe and the /af-research command are exempt).
4781
5198
  const budgetRefusal = checkTurnBudget(
4782
5199
  "research",
4783
5200
  { dispatches: turnDispatchCount, research: turnResearchCount },
@@ -4793,11 +5210,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4793
5210
  details: { status: "budget_refused", reason: budgetRefusal.reason },
4794
5211
  };
4795
5212
  }
4796
- turnResearchCount++;
4797
- turnReport.research++;
4798
- sessionTotals.research++;
4799
- updateModeStatus();
4800
-
5213
+ // Pre-flight BEFORE the research slot is spent — same rule as dispatch_agent:
5214
+ // an unknown persona or an unresolvable artifact path never reached a helper,
5215
+ // so it must not be charged against the turn budget.
4801
5216
  let def: AgentDef;
4802
5217
  let isPersona = false;
4803
5218
  if (persona) {
@@ -4805,7 +5220,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4805
5220
  if (!found) {
4806
5221
  const available = researchPersonas.map(d => d.name).join(", ") || "(none defined)";
4807
5222
  return {
4808
- content: [{ type: "text", text: `No research persona "${persona}". Available: ${available}. Omit \`persona\` for an ad-hoc helper.` }],
5223
+ content: [{ type: "text", text: `No research persona "${persona}". Available: ${available}. Omit \`persona\` for an ad-hoc helper. (Not counted against the turn budget.)` }],
4809
5224
  details: { status: "error" },
4810
5225
  };
4811
5226
  }
@@ -4816,7 +5231,25 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4816
5231
  }
4817
5232
 
4818
5233
  const resolvedModel = resolveResearchModel(def, isPersona ? undefined : model, ctx);
4819
- const inputArtifacts = loadInputArtifacts(artifacts, ctx);
5234
+ let inputArtifacts: InputArtifactPreview[];
5235
+ try {
5236
+ inputArtifacts = loadInputArtifacts(artifacts, ctx);
5237
+ } catch (err: any) {
5238
+ return {
5239
+ content: [{
5240
+ type: "text",
5241
+ text: `⚠ Research NOT spawned and NOT counted against the turn budget — input artifact could not be resolved:\n` +
5242
+ `${err?.message || err}\n\nFix the path and try again.`,
5243
+ }],
5244
+ details: { status: "artifact_preflight_failed" },
5245
+ };
5246
+ }
5247
+
5248
+ turnResearchCount++;
5249
+ turnReport.research++;
5250
+ sessionTotals.research++;
5251
+ updateModeStatus();
5252
+
4820
5253
  const state = createResearchState(def, isPersona, resolvedModel);
4821
5254
  updateResearchWidget();
4822
5255
 
@@ -4848,7 +5281,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4848
5281
  exitCode: result.exitCode,
4849
5282
  fullOutput: result.output,
4850
5283
  termination: result.termination,
4851
- artifacts: inputArtifacts.map(a => ({ path: a.path, displayPath: a.displayPath, preview: a.preview })),
5284
+ artifacts: inputArtifacts.map(a => ({ path: a.path, displayPath: a.displayPath, preview: a.preview, resolvedFromKind: a.resolvedFromKind ?? null })),
4852
5285
  },
4853
5286
  };
4854
5287
  } catch (err: any) {
@@ -4952,7 +5385,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4952
5385
  name: "team_adjust",
4953
5386
  label: "Team Adjust",
4954
5387
  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.",
5388
+ "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 /af-agents-add /af-agents-drop.",
4956
5389
  parameters: Type.Object({
4957
5390
  action: Type.String({ description: "add | drop" }),
4958
5391
  agent: Type.String({ description: "Persona name (case-insensitive), e.g. security-auditor" }),
@@ -4963,7 +5396,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4963
5396
  const act = String(action || "").trim().toLowerCase();
4964
5397
  if (hubMode === "fast") {
4965
5398
  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." }],
5399
+ 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 /af-hub-mode standard if the task outgrew fast mode." }],
4967
5400
  details: { status: "refused" },
4968
5401
  };
4969
5402
  }
@@ -4972,7 +5405,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4972
5405
  }
4973
5406
  if (act === "add" && agentStates.size >= TEAM_ADJUST_ROSTER_CAP) {
4974
5407
  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.` }],
5408
+ content: [{ type: "text" as const, text: `Roster cap reached (${TEAM_ADJUST_ROSTER_CAP}) — drop an unused member first, or ask the user to /af-agents-add manually.` }],
4976
5409
  details: { status: "refused" },
4977
5410
  };
4978
5411
  }
@@ -5005,31 +5438,36 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5005
5438
  name: "set_assertions",
5006
5439
  label: "Set Assertions",
5007
5440
  description:
5008
- "Record the acceptance-assertion ledger for the current task (the Verification Contract). Call this BEFORE dispatching a builder, with one checkable assertion per requirement, and again to REBUILD the whole ledger on a 'wrong again' regression reset (it replaces any existing list). Each assertion needs an id (A1, A2, …), a verification tag (test | runtime-ui | code-grep | manual), and one pass condition. See skills/orchestration-verification/SKILL.md for the format. The ledger is persisted and its status is shown to the human; it does not block dispatch.",
5441
+ `Record the acceptance-assertion ledger for the current task (the Verification Contract). Call this BEFORE dispatching a builder, with one checkable assertion per requirement, and again to REBUILD the whole ledger on a 'wrong again' regression reset (it replaces any existing list). Each assertion needs an id (A1, A2, …), a verification tag (test | runtime-ui | code-grep | manual), one pass condition, and a source naming where the requirement comes from. Keep at most ${MAX_OPEN_ASSERTIONS} open at a time — declare later batches when they start. See skills/orchestration-verification/SKILL.md for the format. The ledger is persisted and its status is shown to the human; it does not block dispatch.`,
5009
5442
  parameters: Type.Object({
5010
5443
  assertions: Type.Array(
5011
5444
  Type.Object({
5012
5445
  id: Type.String({ description: "Stable id, e.g. A1, A2 — referenced verbatim in dispatches and returns." }),
5013
5446
  tag: Type.String({ description: "How it will be proven: test | runtime-ui | code-grep | manual." }),
5014
5447
  text: Type.String({ description: "One checkable pass condition (split compound requirements into separate assertions)." }),
5448
+ source: Type.String({ description: "Where this requirement comes from — \"PLAN-x.md:585-595\", \"user request\", \"review finding F3\". Required: a specialist asked to prove the assertion must be able to read its origin instead of asking." }),
5015
5449
  }),
5016
- { description: "The full assertion list — replaces any existing ledger." },
5450
+ { description: `The full assertion list — replaces any existing ledger. Soft cap ${MAX_OPEN_ASSERTIONS} per batch.` },
5017
5451
  ),
5018
5452
  }),
5019
- async execute(_callId, params, _signal, _onUpdate, _ctx) {
5020
- const input = (params as { assertions: Array<{ id: string; tag: string; text: string }> }).assertions || [];
5021
- assertions = input.map(a => ({
5022
- id: String(a.id).trim(),
5023
- tag: String(a.tag).trim(),
5024
- text: String(a.text).trim(),
5025
- status: "open" as AssertionStatus,
5026
- }));
5453
+ async execute(_callId, params, _signal, _onUpdate, ctx) {
5454
+ const input = (params as { assertions: Array<{ id: string; tag: string; text: string; source?: string }> }).assertions;
5455
+ const verdict = validateAssertionBatch(input);
5456
+ if (!verdict.ok) {
5457
+ return {
5458
+ content: [{ type: "text" as const, text: verdict.refusal! }],
5459
+ details: { status: "rejected", reason: "missing-source" },
5460
+ };
5461
+ }
5462
+ assertions = verdict.assertions.map(a => ({ ...a, status: "open" as AssertionStatus }));
5027
5463
  persistAssertions();
5028
5464
  updateAssertionStatus();
5465
+ if (verdict.warning) ctx.ui.notify(verdict.warning, "warning");
5029
5466
  const ids = assertions.map(a => a.id).join(", ") || "(none)";
5467
+ const head = `Ledger set: ${assertions.length} assertion(s) open — ${ids}. Pass the relevant ones verbatim into each dispatch and advance only on proven.`;
5030
5468
  return {
5031
- content: [{ type: "text" as const, text: `Ledger set: ${assertions.length} assertion(s) open — ${ids}. Pass the relevant ones verbatim into each dispatch and advance only on proven.` }],
5032
- details: { count: assertions.length },
5469
+ content: [{ type: "text" as const, text: verdict.warning ? `${head}\n\n${verdict.warning}` : head }],
5470
+ details: { count: assertions.length, capWarning: Boolean(verdict.warning) },
5033
5471
  };
5034
5472
  },
5035
5473
  renderCall(args, theme) {
@@ -5141,11 +5579,12 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5141
5579
  label: "Coms List",
5142
5580
  description:
5143
5581
  "List the peer agents in your current coms pool — the ones shown in the pool widget. Returns " +
5144
- "names, models, and live context-window usage. Discovery is scoped to what the human displays " +
5145
- "via /coms; you CANNOT widen it to other projects or reveal --explicit peers yourself.",
5582
+ "names, models, live context-window usage, pane_id, and status (idle | working | booting). " +
5583
+ "Check status before sending instead of polling the pane. Discovery is scoped to what the human " +
5584
+ "displays via /af-coms; you CANNOT widen it to other projects or reveal --explicit peers yourself.",
5146
5585
  parameters: Type.Object({
5147
- project: Type.Optional(Type.String({ description: "Narrow to a project WITHIN the current pool scope. Cannot widen beyond what /coms displays — a widening request is ignored." })),
5148
- include_explicit: Type.Optional(Type.Boolean({ description: "Only narrows: pass false to hide explicit peers. Cannot reveal them unless the human ran /coms --all." })),
5586
+ project: Type.Optional(Type.String({ description: "Narrow to a project WITHIN the current pool scope. Cannot widen beyond what /af-coms displays — a widening request is ignored." })),
5587
+ include_explicit: Type.Optional(Type.Boolean({ description: "Only narrows: pass false to hide explicit peers. Cannot reveal them unless the human ran /af-coms --all." })),
5149
5588
  }),
5150
5589
  async execute(_callId, params) {
5151
5590
  if (!identity) {
@@ -5155,9 +5594,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5155
5594
  };
5156
5595
  }
5157
5596
  // Clamp discovery to the human-set pool scope (displayProject + includeExplicit,
5158
- // driven by /coms). The LLM's project/include_explicit may NARROW within that
5597
+ // driven by /af-coms). The LLM's project/include_explicit may NARROW within that
5159
5598
  // scope but can never widen it — cross-project or explicit discovery requires a
5160
- // deliberate /coms --project / --all from the human. So coms_list returns exactly
5599
+ // deliberate /af-coms --project / --all from the human. So coms_list returns exactly
5161
5600
  // the pool, the same boundary coms_send enforces.
5162
5601
  const scopeProject = displayProject ?? identity.project;
5163
5602
  let projects: string[];
@@ -5169,7 +5608,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5169
5608
  if (params.project && params.project !== scopeProject) widened = true;
5170
5609
  }
5171
5610
  // include_explicit may only narrow (turn OFF); it cannot reveal explicit peers
5172
- // unless the human already did via /coms --all.
5611
+ // unless the human already did via /af-coms --all.
5173
5612
  const includeExp = includeExplicit && params.include_explicit !== false;
5174
5613
  if (params.include_explicit === true && !includeExplicit) widened = true;
5175
5614
 
@@ -5197,6 +5636,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5197
5636
  project: c.project,
5198
5637
  alive: pong != null,
5199
5638
  context_used_pct: pong ? pong.context_used_pct : null,
5639
+ pane_id: pong?.pane_id ?? null,
5640
+ status: pong?.status ?? null,
5641
+ queue_depth: pong ? pong.queue_depth : null,
5200
5642
  color: c.entry.color,
5201
5643
  };
5202
5644
  });
@@ -5204,7 +5646,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5204
5646
  const notice = widened
5205
5647
  ? `\n\n(Discovery is scoped to "${scopeProject}"${includeExplicit ? "" : ", explicit peers hidden"}. ` +
5206
5648
  `Widening to other projects or revealing --explicit peers is a human action via ` +
5207
- `/coms --project <name> or /coms --all.)`
5649
+ `/af-coms --project <name> or /af-coms --all.)`
5208
5650
  : "";
5209
5651
 
5210
5652
  const lines = agents.length === 0
@@ -5212,7 +5654,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5212
5654
  : agents.map((a) => {
5213
5655
  const ctxStr = a.context_used_pct != null ? ` ${a.context_used_pct}%` : " ?%";
5214
5656
  const live = a.alive ? "●" : "✗";
5215
- return `${live} ${a.name} (${a.model})${ctxStr}${a.purpose ? ` — ${a.purpose}` : ""}`;
5657
+ const state = a.alive ? (a.status ?? "unknown") : "unreachable";
5658
+ return `${live} ${a.name} (${a.model})${ctxStr} [${state}${a.pane_id ? ` pane ${a.pane_id}` : ""}]${a.purpose ? ` — ${a.purpose}` : ""}`;
5216
5659
  }).join("\n");
5217
5660
 
5218
5661
  return {
@@ -5238,7 +5681,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5238
5681
  const rows = agents.map((a) => {
5239
5682
  const dot = a.alive ? theme.fg("success", "●") : theme.fg("error", "✗");
5240
5683
  const pct = a.context_used_pct != null ? `${a.context_used_pct}%` : "?%";
5241
- return `${dot} ${theme.fg("accent", a.name)} ${theme.fg("dim", a.model)} ${theme.fg("warning", pct)}`;
5684
+ const state = a.alive ? (a.status ?? "unknown") : "unreachable";
5685
+ const stateFg = state === "idle" ? "success" : state === "working" ? "warning" : "dim";
5686
+ return `${dot} ${theme.fg("accent", a.name)} ${theme.fg("dim", a.model)} ${theme.fg("warning", pct)} ` +
5687
+ `${theme.fg(stateFg as any, state)}${a.pane_id ? theme.fg("dim", ` ${a.pane_id}`) : ""}`;
5242
5688
  }).join("\n");
5243
5689
  return new Text(header + "\n" + rows, 0, 0);
5244
5690
  },
@@ -5252,11 +5698,12 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5252
5698
  "Use coms_get (non-blocking) or coms_await (blocking) with the msg_id to retrieve the response. " +
5253
5699
  "Throws if the receiver is unreachable or rejects the envelope.",
5254
5700
  parameters: Type.Object({
5255
- target: Type.String({ description: "Peer name (preferred) or session_id — must be a peer currently in your coms pool (shown in the widget). Out-of-pool targets are refused; ask the human to widen scope with /coms --project or /coms --all." }),
5701
+ target: Type.String({ description: "Peer name (preferred) or session_id — must be a peer currently in your coms pool (shown in the widget). Out-of-pool targets are refused; ask the human to widen scope with /af-coms --project or /af-coms --all." }),
5256
5702
  prompt: Type.String({ description: "The prompt to send." }),
5257
- handoff_token: Type.Optional(Type.String({ description: "Internal /handoff token. Only include when the /handoff follow-up explicitly gives you one; it authorizes the machine-appended ledger/artifact appendix." })),
5703
+ handoff_token: Type.Optional(Type.String({ description: "Internal /af-handoff token. Only include when the /af-handoff follow-up explicitly gives you one; it authorizes the machine-appended ledger/artifact appendix." })),
5258
5704
  conversation_id: Type.Optional(Type.String()),
5259
5705
  response_schema: Type.Optional(Type.Any({ description: "Optional JSON Schema describing the expected response shape." })),
5706
+ reply_timeout_ms: Type.Optional(Type.Number({ description: "Receiver-side reply deadline in ms; pass the same budget used for coms_await. Clamped by the receiver." })),
5260
5707
  }),
5261
5708
  async execute(_callId, params) {
5262
5709
  if (!identity) {
@@ -5271,7 +5718,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5271
5718
  throw new Error(
5272
5719
  `coms: no connected peer "${params.target}" in your pool (project ${scope}). ` +
5273
5720
  `Only peers shown in the coms pool are reachable. If you expected this peer, ask the ` +
5274
- `human to widen scope with /coms --project <name> or /coms --all, then retry.`,
5721
+ `human to widen scope with /af-coms --project <name> or /af-coms --all, then retry.`,
5275
5722
  );
5276
5723
  }
5277
5724
  const hops = currentInbound ? currentInbound.hops + 1 : 0;
@@ -5301,10 +5748,12 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5301
5748
  prompt: outboundPrompt,
5302
5749
  conversation_id: params.conversation_id ?? null,
5303
5750
  response_schema: (params.response_schema as object | undefined) ?? null,
5751
+ reply_timeout_ms: params.reply_timeout_ms ?? null,
5304
5752
  };
5305
5753
 
5306
5754
  // Send the envelope synchronously and wait for the receiver's ack.
5307
5755
  await sendEnvelope(target.endpoint, env);
5756
+ markPeerAddressed(target.name);
5308
5757
  if (handoffAppendAuthorized) pendingHandoff = null;
5309
5758
 
5310
5759
  // Register a pending entry whose promise the receiver-side handleResponse
@@ -5323,13 +5772,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5323
5772
  target_name: target.name,
5324
5773
  created_at: nowIso(),
5325
5774
  };
5326
- entry.timer = setTimeout(() => {
5327
- if (entry.result) return;
5328
- entry.result = { error: "timeout" };
5329
- try { entry.resolve(entry.result); } catch { /* ignore */ }
5330
- }, TIMEOUT_MS);
5331
- // Don't keep the event loop alive solely for this timer.
5332
- try { (entry.timer as any).unref?.(); } catch { /* ignore */ }
5775
+ // A local wait deadline does not convert unfinished remote work into an
5776
+ // error. Keep the entry pending so a later await can collect the response.
5333
5777
  pendingReplies.set(msg_id, entry);
5334
5778
 
5335
5779
  try {
@@ -5449,10 +5893,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5449
5893
  });
5450
5894
 
5451
5895
  const winner = await Promise.race([entry.promise, timed]);
5896
+ if ((winner as any).error === "timeout") {
5897
+ return {
5898
+ content: [{ type: "text" as const, text: "coms_await: pending — wait budget exhausted; the peer may still complete" }],
5899
+ details: { status: "pending" },
5900
+ };
5901
+ }
5452
5902
  if ((winner as any).error) {
5453
5903
  return {
5454
5904
  content: [{ type: "text" as const, text: `coms_await: error — ${(winner as any).error}` }],
5455
- details: { error: (winner as any).error },
5905
+ details: { status: "error", error: (winner as any).error },
5456
5906
  };
5457
5907
  }
5458
5908
  const resp = (winner as any).response;
@@ -5471,6 +5921,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5471
5921
  renderResult(result, _options, theme) {
5472
5922
  const d = result.details as any;
5473
5923
  if (d?.error) return new Text(theme.fg("error", `✗ ${d.error}`), 0, 0);
5924
+ if (d?.status === "pending") return new Text(theme.fg("warning", "⏳ pending"), 0, 0);
5474
5925
  return new Text(theme.fg("success", "✓ response received"), 0, 0);
5475
5926
  },
5476
5927
  });
@@ -5488,11 +5939,35 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5488
5939
 
5489
5940
  let herdrFleetReady = false;
5490
5941
 
5942
+ // Peers this hub spawned, and whether anyone ever sent to them. A spawned
5943
+ // coms peer boots idle and waits — spawning it delivers no work, so an
5944
+ // unaddressed one is an empty pane holding a model session.
5945
+ const hubSpawnedPeers = new Map<string, { name: string; paneId: string | null; addressed: boolean }>();
5946
+ const markPeerAddressed = (name: string) => {
5947
+ const entry = hubSpawnedPeers.get(String(name || "").toLowerCase());
5948
+ if (entry) entry.addressed = true;
5949
+ };
5950
+
5951
+ /** Bounded wait for a spawned peer to register in the coms pool. */
5952
+ async function waitForPeerRegistration(name: string, timeoutMs = PEER_READY_TIMEOUT_MS): Promise<{ found: boolean; waitedMs: number }> {
5953
+ const wanted = String(name).toLowerCase();
5954
+ const started = Date.now();
5955
+ for (let attempt = 0; ; attempt++) {
5956
+ const live = comsReady && identity ? peersInScope() : [];
5957
+ if (live.some(e => e.name.toLowerCase() === wanted)) {
5958
+ return { found: true, waitedMs: Date.now() - started };
5959
+ }
5960
+ const remaining = timeoutMs - (Date.now() - started);
5961
+ if (remaining <= 0) return { found: false, waitedMs: Date.now() - started };
5962
+ await new Promise(r => setTimeout(r, Math.min(peerReadyDelayMs(attempt), remaining)));
5963
+ }
5964
+ }
5965
+
5491
5966
  pi.registerTool({
5492
5967
  name: "herdr_spawn_peer",
5493
5968
  label: "Herdr Spawn Peer",
5494
5969
  description:
5495
- "Spawn a pane in the CURRENT herdr workspace: either a peers.yaml-style coms peer (persona [+ name/model], launched via `just _peer`) or a raw command pane. Returns the new pane_id. Use for standing up an extra worker/watcher next to this session; peers become addressable via coms_send once booted.",
5970
+ "Spawn a pane in the CURRENT herdr workspace: either a peers.yaml-style coms peer (persona [+ name/model], launched via `just _peer`) or a raw command pane. A persona peer boots IDLE and does nothing until you coms_send to it — spawning delivers no work. The call waits (bounded) for the peer to register and returns `peer_ready` plus its coms name, or `peer_ready: false` with the wait stated. Spawn one only immediately before the first message you will send it; a peer that receives no work is named in the session digest.",
5496
5971
  parameters: Type.Object({
5497
5972
  persona: Type.Optional(Type.String({ description: "Persona under agents/ (e.g. researcher). Omit for a raw command pane." })),
5498
5973
  name: Type.String({ description: "Pane label; for persona peers also the coms peer name." }),
@@ -5525,9 +6000,21 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5525
6000
  focus: false,
5526
6001
  });
5527
6002
  try { await herdrApi.paneRename(pane.pane_id, params.name); } catch { /* cosmetic */ }
6003
+ // A raw command pane is not a coms peer — nothing to wait for and
6004
+ // nothing to sweep. A persona peer is only useful once addressable,
6005
+ // so report that verdict instead of a bare pane id.
6006
+ if (!params.persona) {
6007
+ return {
6008
+ content: [{ type: "text" as const, text: `spawned pane ${pane.pane_id} (${params.name}): ${argv.join(" ")}` }],
6009
+ details: { pane_id: pane.pane_id, name: params.name },
6010
+ };
6011
+ }
6012
+ hubSpawnedPeers.set(params.name.toLowerCase(), { name: params.name, paneId: pane.pane_id, addressed: false });
6013
+ const { found, waitedMs } = await waitForPeerRegistration(params.name);
6014
+ const verdict = peerReadyVerdict({ name: params.name, paneId: pane.pane_id, found, waitedMs });
5528
6015
  return {
5529
- content: [{ type: "text" as const, text: `spawned pane ${pane.pane_id} (${params.name}): ${argv.join(" ")}` }],
5530
- details: { pane_id: pane.pane_id, name: params.name },
6016
+ content: [{ type: "text" as const, text: `spawned pane ${pane.pane_id} (${params.name}): ${argv.join(" ")}\n\n${verdict.message}` }],
6017
+ details: { pane_id: pane.pane_id, name: params.name, ...verdict },
5531
6018
  };
5532
6019
  } catch (err) {
5533
6020
  const m = err instanceof Error ? err.message : String(err);
@@ -5700,7 +6187,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5700
6187
 
5701
6188
  // ── Commands ─────────────────────────────────
5702
6189
 
5703
- pi.registerCommand("agents-team", {
6190
+ pi.registerCommand("af-agents-team", {
5704
6191
  description: "Select a team to work with",
5705
6192
  handler: async (_args, ctx) => {
5706
6193
  widgetCtx = ctx;
@@ -5727,7 +6214,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5727
6214
  },
5728
6215
  });
5729
6216
 
5730
- pi.registerCommand("agents-list", {
6217
+ pi.registerCommand("af-agents-list", {
5731
6218
  description: "List all loaded agents",
5732
6219
  handler: async (_args, _ctx) => {
5733
6220
  widgetCtx = _ctx;
@@ -5753,7 +6240,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5753
6240
  },
5754
6241
  });
5755
6242
 
5756
- // Open the read-only /agents-history overlay. Mirrors openZoom's chrome and adds
6243
+ // Open the read-only /af-agents-history overlay. Mirrors openZoom's chrome and adds
5757
6244
  // a 1s tick so running durations advance live; `historyRender` lets a new
5758
6245
  // dispatch refresh the panel the instant it starts/ends.
5759
6246
  async function openHistory(ctx: any): Promise<void> {
@@ -5779,7 +6266,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5779
6266
  historyRender = null;
5780
6267
  }
5781
6268
 
5782
- pi.registerCommand("agents-history", {
6269
+ pi.registerCommand("af-agents-history", {
5783
6270
  description: "Timeline of agent execution — orchestrator turns, dispatches, research helpers, durations, and a grand total",
5784
6271
  handler: async (_args, ctx) => {
5785
6272
  widgetCtx = ctx;
@@ -5787,11 +6274,11 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5787
6274
  },
5788
6275
  });
5789
6276
 
5790
- // ── /hub-mode: execution mode (fast|standard|strict) ──
6277
+ // ── /af-hub-mode: execution mode (fast|standard|strict) ──
5791
6278
  // Session-lifetime switch over the overrides-file default. Budgets bind on
5792
6279
  // the NEXT tool call (counters are per user turn and keep running); the
5793
6280
  // dispatcher prompt rebuilds with the new mode on the next turn.
5794
- pi.registerCommand("hub-mode", {
6281
+ pi.registerCommand("af-hub-mode", {
5795
6282
  description: "Show or set the execution mode: fast (single specialist) | standard (batched, default) | strict (full Verification Contract)",
5796
6283
  handler: async (args, ctx) => {
5797
6284
  widgetCtx = ctx;
@@ -5801,7 +6288,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5801
6288
  const cap = (n: number | null) => (n == null ? "∞" : String(n));
5802
6289
  ctx.ui.notify(
5803
6290
  `Execution mode: ${hubMode}\nThis turn: ${turnDispatchCount}/${cap(b.maxDispatches)} dispatches, ` +
5804
- `${turnResearchCount}/${cap(b.maxResearch)} research\nSwitch with /hub-mode ${HUB_MODES.join("|")}`,
6291
+ `${turnResearchCount}/${cap(b.maxResearch)} research\nSwitch with /af-hub-mode ${HUB_MODES.join("|")}`,
5805
6292
  "info",
5806
6293
  );
5807
6294
  return;
@@ -5817,8 +6304,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5817
6304
  },
5818
6305
  });
5819
6306
 
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",
6307
+ pi.registerCommand("af-watchdog", {
6308
+ description: "Drift watchdog: /af-watchdog [on|off|auto] hub-wide, /af-watchdog <agent> [on|off|clear] per agent, no args to show",
5822
6309
  handler: async (args, ctx) => {
5823
6310
  widgetCtx = ctx;
5824
6311
  const parts = (args || "").trim().split(/\s+/).filter(Boolean);
@@ -5829,7 +6316,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5829
6316
  ctx.ui.notify(
5830
6317
  `Drift watchdog: ${watchdogSetting} (hub-wide)\nPer-agent overrides: ${perAgent}\n` +
5831
6318
  `Judge model: ${watchdogJudgeModel || "(researcher persona's, else dispatcher's)"}\n` +
5832
- `Usage: /watchdog on|off|auto — or /watchdog <agent> on|off|clear`,
6319
+ `Usage: /af-watchdog on|off|auto — or /af-watchdog <agent> on|off|clear`,
5833
6320
  "info",
5834
6321
  );
5835
6322
  return;
@@ -5837,7 +6324,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5837
6324
  if (parts.length === 1) {
5838
6325
  const setting = normalizeWatchdogSetting(parts[0]);
5839
6326
  if (!setting) {
5840
- ctx.ui.notify(`Unknown setting "${parts[0]}" — expected one of: ${WATCHDOG_SETTINGS.join(", ")} (or /watchdog <agent> on|off|clear)`, "error");
6327
+ ctx.ui.notify(`Unknown setting "${parts[0]}" — expected one of: ${WATCHDOG_SETTINGS.join(", ")} (or /af-watchdog <agent> on|off|clear)`, "error");
5841
6328
  return;
5842
6329
  }
5843
6330
  watchdogSetting = setting;
@@ -5864,8 +6351,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5864
6351
  },
5865
6352
  });
5866
6353
 
5867
- pi.registerCommand("agents-add", {
5868
- description: "Add persona(s) to the active team without switching teams: /agents-add <name> [<name>…]",
6354
+ pi.registerCommand("af-agents-add", {
6355
+ description: "Add persona(s) to the active team without switching teams: /af-agents-add <name> [<name>…]",
5869
6356
  handler: async (args, ctx) => {
5870
6357
  widgetCtx = ctx;
5871
6358
  const names = (args || "").trim().split(/\s+/).filter(Boolean);
@@ -5873,7 +6360,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5873
6360
  const available = allAgentDefs
5874
6361
  .filter(d => !agentStates.has(d.name.toLowerCase()))
5875
6362
  .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");
6363
+ ctx.ui.notify(`Usage: /af-agents-add <persona> [<persona>…]\nNot in the team yet: ${available}`, "info");
5877
6364
  return;
5878
6365
  }
5879
6366
  const results = names.map(n => rosterAdd(n));
@@ -5883,13 +6370,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5883
6370
  },
5884
6371
  });
5885
6372
 
5886
- pi.registerCommand("agents-drop", {
5887
- description: "Drop persona(s) from the active team: /agents-drop <name> [<name>…]",
6373
+ pi.registerCommand("af-agents-drop", {
6374
+ description: "Drop persona(s) from the active team: /af-agents-drop <name> [<name>…]",
5888
6375
  handler: async (args, ctx) => {
5889
6376
  widgetCtx = ctx;
5890
6377
  const names = (args || "").trim().split(/\s+/).filter(Boolean);
5891
6378
  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");
6379
+ ctx.ui.notify(`Usage: /af-agents-drop <persona> [<persona>…]\nActive team: ${Array.from(agentStates.values()).map(s => s.def.name).join(", ")}`, "info");
5893
6380
  return;
5894
6381
  }
5895
6382
  const results = names.map(n => rosterDrop(n));
@@ -5899,13 +6386,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5899
6386
  },
5900
6387
  });
5901
6388
 
5902
- pi.registerCommand("agents-save", {
5903
- description: "Persist the CURRENT roster as a named team in .pi/agents/teams.yaml: /agents-save <team-name>",
6389
+ pi.registerCommand("af-agents-save", {
6390
+ description: "Persist the CURRENT roster as a named team in .pi/agents/teams.yaml: /af-agents-save <team-name>",
5904
6391
  handler: async (args, ctx) => {
5905
6392
  widgetCtx = ctx;
5906
6393
  const name = (args || "").trim();
5907
6394
  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");
6395
+ ctx.ui.notify("Usage: /af-agents-save <team-name> (letters, digits, hyphens, underscores)", "error");
5909
6396
  return;
5910
6397
  }
5911
6398
  const members = Array.from(agentStates.values()).map(s => s.def.name);
@@ -5930,7 +6417,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5930
6417
  },
5931
6418
  });
5932
6419
 
5933
- pi.registerCommand("hub-report", {
6420
+ pi.registerCommand("af-hub-report", {
5934
6421
  description: "Per-turn cost report: dispatches, research, tokens, recycles, drift stops (last turn + session totals)",
5935
6422
  handler: async (_args, ctx) => {
5936
6423
  widgetCtx = ctx;
@@ -5955,6 +6442,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5955
6442
  `${fmtTok(sessionTotals.billed)} billed / ${fmtTok(sessionTotals.out)} out · ${sessionTotals.recycles} recycle(s) · ` +
5956
6443
  `${sessionTotals.driftStops} drift stop(s) · ${sessionTotals.refusals} refusal(s)`,
5957
6444
  );
6445
+ // A spawned peer that never received work is a running pane nobody is
6446
+ // using — the digest is where it stops being invisible.
6447
+ const sweep = unaddressedPeerSweep(Array.from(hubSpawnedPeers.values()));
6448
+ if (sweep) lines.push(sweep.message);
5958
6449
  ctx.ui.notify(lines.join("\n\n"), "info");
5959
6450
  },
5960
6451
  });
@@ -5976,7 +6467,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5976
6467
  });
5977
6468
 
5978
6469
  // Compact-view agent switcher. Alt+] / Alt+[ move the marker through the running
5979
- // subagents; Alt+\ zooms the marked one (same overlay as /zoom). main is never a
6470
+ // subagents; Alt+\ zooms the marked one (same overlay as /af-zoom). main is never a
5980
6471
  // target — it is the session under the input, which always takes typed prompts.
5981
6472
  // Keys verified free of pi's reserved editor bindings (keybindings.d.ts): alt+up/
5982
6473
  // down/left/right and ctrl+] / ctrl+alt+] are reserved, but alt+[ / alt+] / alt+\
@@ -6054,7 +6545,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6054
6545
  return null;
6055
6546
  }
6056
6547
 
6057
- // Completions for /zoom: team member names, research handles (rN), and
6548
+ // Completions for /af-zoom: team member names, research handles (rN), and
6058
6549
  // delegate child ids nested under their parent specialist.
6059
6550
  const zoomCompletions = (prefix: string): AutocompleteItem[] | null => {
6060
6551
  const teamItems = Array.from(agentStates.values()).map(s => ({
@@ -6077,7 +6568,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6077
6568
  return filtered.length > 0 ? filtered : items;
6078
6569
  };
6079
6570
 
6080
- // Open the read-only zoom overlay over a live timeline. Shared by /zoom and the
6571
+ // Open the read-only zoom overlay over a live timeline. Shared by /af-zoom and the
6081
6572
  // compact-view Alt+\ switcher. While open, `target.zoomRender` lets the stream
6082
6573
  // parser refresh it on new events (throttled to ~12fps; force=true pushes the
6083
6574
  // final frame on completion).
@@ -6106,8 +6597,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6106
6597
  target.zoomRender = undefined;
6107
6598
  }
6108
6599
 
6109
- pi.registerCommand("zoom", {
6110
- description: "Scrollable read-only view of an agent's stream: /zoom <name|rN>",
6600
+ pi.registerCommand("af-zoom", {
6601
+ description: "Scrollable read-only view of an agent's stream: /af-zoom <name|rN>",
6111
6602
  getArgumentCompletions: zoomCompletions,
6112
6603
  handler: async (args, ctx) => {
6113
6604
  widgetCtx = ctx;
@@ -6127,14 +6618,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6127
6618
  const childKnown = Array.from(agentStates.values())
6128
6619
  .flatMap(s => Array.from(s.delegations?.keys() || [])).join(", ");
6129
6620
  const known = [teamKnown, researchKnown, childKnown].filter(Boolean).join(", ");
6130
- ctx.ui.notify(`Usage: /zoom <name|rN|child-id>. Known: ${known || "none"}`, "error");
6621
+ ctx.ui.notify(`Usage: /af-zoom <name|rN|child-id>. Known: ${known || "none"}`, "error");
6131
6622
  return;
6132
6623
  }
6133
6624
  await openZoom(target, ctx);
6134
6625
  },
6135
6626
  });
6136
6627
 
6137
- // Completions for /agent-model: persona names plus a `persona.role` entry per
6628
+ // Completions for /af-agent-model: persona names plus a `persona.role` entry per
6138
6629
  // declared delegate sub-role, labeled with the model currently in effect.
6139
6630
  const agentModelCompletions = (prefix: string): AutocompleteItem[] | null => {
6140
6631
  const personaItems = Array.from(agentStates.values()).map(s => ({
@@ -6162,14 +6653,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6162
6653
  return filtered.length > 0 ? filtered : items;
6163
6654
  };
6164
6655
 
6165
- // /agent-model <persona>[.<role>] — switch a persona's model among its
6656
+ // /af-agent-model <persona>[.<role>] — switch a persona's model among its
6166
6657
  // declared candidates (frontmatter `model:` + `models:`), or a delegate
6167
6658
  // sub-role's model among its declared default + the parent persona's
6168
6659
  // candidates. Session-lifetime: the choice resets on session_start and takes
6169
- // effect on the persona's NEXT dispatch (/agents-restart applies it
6660
+ // effect on the persona's NEXT dispatch (/af-agents-restart applies it
6170
6661
  // immediately). Nothing outside the declared lists is ever selectable.
6171
- pi.registerCommand("agent-model", {
6172
- description: "Switch a persona's or sub-role's model from its declared candidates: /agent-model <persona>[.<role>]",
6662
+ pi.registerCommand("af-agent-model", {
6663
+ description: "Switch a persona's or sub-role's model from its declared candidates: /af-agent-model <persona>[.<role>]",
6173
6664
  getArgumentCompletions: agentModelCompletions,
6174
6665
  handler: async (args, ctx) => {
6175
6666
  widgetCtx = ctx;
@@ -6233,7 +6724,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6233
6724
  ...Array.from(agentStates.values()).map(s => s.def.name),
6234
6725
  ...researchPersonas.map(d => d.name),
6235
6726
  ].join(", ");
6236
- ctx.ui.notify(`Usage: /agent-model <persona>[.<role>]. Known: ${known || "none"}`, "error");
6727
+ ctx.ui.notify(`Usage: /af-agent-model <persona>[.<role>]. Known: ${known || "none"}`, "error");
6237
6728
  return;
6238
6729
  }
6239
6730
  if (!def.models || def.models.length === 0) {
@@ -6272,8 +6763,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6272
6763
  // Research helpers spawn fresh each time, so the switch lands on their
6273
6764
  // next spawn; team members apply on next dispatch (restartable now).
6274
6765
  const applyHint = (def.kind || "").toLowerCase() === "research"
6275
- ? "applies on next /research or spawn_research"
6276
- : `applies on next dispatch; /agents-restart ${def.name} to apply now`;
6766
+ ? "applies on next /af-research or spawn_research"
6767
+ : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
6277
6768
  ctx.ui.notify(`${displayName(def.name)} → ${picked} (${applyHint})`, "success");
6278
6769
  if ((dispatchPolicy.substitutions[name]?.prefer ?? dispatchPolicy.default) === "coms") {
6279
6770
  ctx.ui.notify(
@@ -6284,7 +6775,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6284
6775
  },
6285
6776
  });
6286
6777
 
6287
- // Completions for /agent-model-thinking: persona names labeled with the
6778
+ // Completions for /af-agent-model-thinking: persona names labeled with the
6288
6779
  // thinking level currently in effect.
6289
6780
  const agentThinkingCompletions = (prefix: string): AutocompleteItem[] | null => {
6290
6781
  const items = [
@@ -6302,13 +6793,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6302
6793
  return filtered.length > 0 ? filtered : items;
6303
6794
  };
6304
6795
 
6305
- // /agent-model-thinking <persona> — switch a persona's reasoning effort among
6796
+ // /af-agent-model-thinking <persona> — switch a persona's reasoning effort among
6306
6797
  // pi's --thinking levels (off|minimal|low|medium|high|xhigh). Session-lifetime:
6307
6798
  // the choice resets on session_start and takes effect on the persona's NEXT
6308
- // dispatch (/agents-restart applies it immediately). Selecting the frontmatter
6799
+ // dispatch (/af-agents-restart applies it immediately). Selecting the frontmatter
6309
6800
  // default clears the override.
6310
- pi.registerCommand("agent-model-thinking", {
6311
- description: "Switch a persona's thinking level from pi's --thinking levels: /agent-model-thinking <persona>",
6801
+ pi.registerCommand("af-agent-model-thinking", {
6802
+ description: "Switch a persona's thinking level from pi's --thinking levels: /af-agent-model-thinking <persona>",
6312
6803
  getArgumentCompletions: agentThinkingCompletions,
6313
6804
  handler: async (args, ctx) => {
6314
6805
  widgetCtx = ctx;
@@ -6320,7 +6811,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6320
6811
  ...Array.from(agentStates.values()).map(s => s.def.name),
6321
6812
  ...researchPersonas.map(d => d.name),
6322
6813
  ].join(", ");
6323
- ctx.ui.notify(`Usage: /agent-model-thinking <persona>. Known: ${known || "none"}`, "error");
6814
+ ctx.ui.notify(`Usage: /af-agent-model-thinking <persona>. Known: ${known || "none"}`, "error");
6324
6815
  return;
6325
6816
  }
6326
6817
  const defaultLevel = resolveThinkingLevel(def.thinking);
@@ -6346,13 +6837,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6346
6837
  // Research helpers spawn fresh each time, so the switch lands on their
6347
6838
  // next spawn; team members apply on next dispatch (restartable now).
6348
6839
  const applyHint = (def.kind || "").toLowerCase() === "research"
6349
- ? "applies on next /research or spawn_research"
6350
- : `applies on next dispatch; /agents-restart ${def.name} to apply now`;
6840
+ ? "applies on next /af-research or spawn_research"
6841
+ : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
6351
6842
  ctx.ui.notify(`${displayName(def.name)} thinking → ${picked} (${applyHint})`, "success");
6352
6843
  },
6353
6844
  });
6354
6845
 
6355
- // Completions for /models: profile names with their persona → model summary.
6846
+ // Completions for /af-models: profile names with their persona → model summary.
6356
6847
  const modelProfileCompletions = (prefix: string): AutocompleteItem[] | null => {
6357
6848
  const items = Object.entries(modelProfiles).map(([name, entries]) => ({
6358
6849
  value: name,
@@ -6363,10 +6854,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6363
6854
  return filtered.length > 0 ? filtered : items;
6364
6855
  };
6365
6856
 
6366
- // /models [profile] — apply a named model profile (a validated macro over the
6367
- // personas' declared candidates). Bare /models opens a picker.
6368
- pi.registerCommand("models", {
6369
- description: "Apply a model profile to the team: /models [profile]",
6857
+ // /af-models [profile] — apply a named model profile (a validated macro over the
6858
+ // personas' declared candidates). Bare /af-models opens a picker.
6859
+ pi.registerCommand("af-models", {
6860
+ description: "Apply a model profile to the team: /af-models [profile]",
6370
6861
  getArgumentCompletions: modelProfileCompletions,
6371
6862
  handler: async (args, ctx) => {
6372
6863
  widgetCtx = ctx;
@@ -6403,7 +6894,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6403
6894
  });
6404
6895
 
6405
6896
  // All known model strings across every persona (allowedModels union), deduped
6406
- // preserving first-seen order. Used for /agent-models-substitute autocomplete.
6897
+ // preserving first-seen order. Used for /af-agent-models-substitute autocomplete.
6407
6898
  function allKnownModels(): string[] {
6408
6899
  const seen = new Set<string>();
6409
6900
  const out: string[] = [];
@@ -6415,7 +6906,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6415
6906
  return out;
6416
6907
  }
6417
6908
 
6418
- // Completions for /agent-models-substitute: a flat list of known models.
6909
+ // Completions for /af-agent-models-substitute: a flat list of known models.
6419
6910
  // Free text allowed too — we just suggest, never restrict, so ad-hoc targets
6420
6911
  // (e.g. a model a persona does not declare) still produce a clean "skipped"
6421
6912
  // report at apply time.
@@ -6427,22 +6918,22 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6427
6918
  return filtered.length > 0 ? filtered : items;
6428
6919
  };
6429
6920
 
6430
- // /agent-models-substitute <source> <target> — replace one model across all
6921
+ // /af-agent-models-substitute <source> <target> — replace one model across all
6431
6922
  // personas (team members + research + orchestrator; never the dispatcher).
6432
6923
  // Per-persona validity: target must be in that persona's allowedModels.
6433
- // Applies session-lifetime (same lifetime as /agent-model); takes effect on
6434
- // the persona's NEXT dispatch (/agents-restart applies it immediately).
6924
+ // Applies session-lifetime (same lifetime as /af-agent-model); takes effect on
6925
+ // the persona's NEXT dispatch (/af-agents-restart applies it immediately).
6435
6926
  // One-step flow: dry-run summary is shown up front, then the swap is
6436
6927
  // applied unconditionally — the operator runs the command to commit.
6437
- pi.registerCommand("agent-models-substitute", {
6438
- description: "Replace one model across all personas: /agent-models-substitute <source> <target>",
6928
+ pi.registerCommand("af-agent-models-substitute", {
6929
+ description: "Replace one model across all personas: /af-agent-models-substitute <source> <target>",
6439
6930
  getArgumentCompletions: substituteCompletions,
6440
6931
  handler: async (args, ctx) => {
6441
6932
  widgetCtx = ctx;
6442
6933
  const tokens = (args || "").trim().split(/\s+/).filter(Boolean);
6443
6934
  if (tokens.length !== 2) {
6444
6935
  ctx.ui.notify(
6445
- `Usage: /agent-models-substitute <source> <target>. ` +
6936
+ `Usage: /af-agent-models-substitute <source> <target>. ` +
6446
6937
  `Both must be model specs (e.g. openai-codex/gpt-5.3-codex-spark).`,
6447
6938
  "error",
6448
6939
  );
@@ -6468,7 +6959,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6468
6959
  continue;
6469
6960
  }
6470
6961
  if (!allowedModels(def).includes(target)) {
6471
- skipped.push({ def, reason: `target ${target} not in declared candidates (model:/models: in ${def.file})` });
6962
+ skipped.push({ def, reason: `target ${target} not in declared candidates (model:/af-models: in ${def.file})` });
6472
6963
  continue;
6473
6964
  }
6474
6965
  matches.push({ def, current });
@@ -6488,7 +6979,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6488
6979
  // Apply: for every match, if the persona's frontmatter default IS the
6489
6980
  // target, clear any existing override (so it tracks frontmatter
6490
6981
  // updates); otherwise record target in modelOverrides. Mirrors
6491
- // /agent-model and /models.
6982
+ // /af-agent-model and /af-models.
6492
6983
  const applied: string[] = [];
6493
6984
  for (const { def } of matches) {
6494
6985
  const key = def.name.toLowerCase();
@@ -6505,14 +6996,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6505
6996
  `Substitution ${source} → ${target}:`,
6506
6997
  ` Affected: ${applied.length}${applied.length ? ` (${applied.join(", ")})` : ""}`,
6507
6998
  ` Skipped: ${skipped.length}${skipped.length ? ` (${skipDetails.join("; ")})` : ""}`,
6508
- ` Applies on next dispatch (/agents-restart to apply now).`,
6999
+ ` Applies on next dispatch (/af-agents-restart to apply now).`,
6509
7000
  ].join("\n");
6510
7001
  updateWidget();
6511
7002
  ctx.ui.notify(summary, applied.length > 0 ? "success" : "info");
6512
7003
  },
6513
7004
  });
6514
7005
 
6515
- // Completions for /research: research-persona names prefixed with @.
7006
+ // Completions for /af-research: research-persona names prefixed with @.
6516
7007
  const researchPersonaCompletions = (prefix: string): AutocompleteItem[] | null => {
6517
7008
  const items = researchPersonas.map(d => ({
6518
7009
  value: `@${d.name}`,
@@ -6524,10 +7015,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6524
7015
  return filtered.length > 0 ? filtered : items;
6525
7016
  };
6526
7017
 
6527
- // /research [@persona] [--model <spec>] <task> — spawn a read-only helper. Fire-and-
7018
+ // /af-research [@persona] [--model <spec>] <task> — spawn a read-only helper. Fire-and-
6528
7019
  // forget: the result is delivered to the dispatcher as a follow-up turn.
6529
- pi.registerCommand("research", {
6530
- description: "Spawn a read-only research helper: /research [@persona] [--model <spec>] <task>",
7020
+ pi.registerCommand("af-research", {
7021
+ description: "Spawn a read-only research helper: /af-research [@persona] [--model <spec>] <task>",
6531
7022
  getArgumentCompletions: researchPersonaCompletions,
6532
7023
  handler: async (args, ctx) => {
6533
7024
  widgetCtx = ctx;
@@ -6557,7 +7048,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6557
7048
 
6558
7049
  const task = rest;
6559
7050
  if (!task) {
6560
- ctx.ui.notify("Usage: /research [@persona] [--model <spec>] <task>", "error");
7051
+ ctx.ui.notify("Usage: /af-research [@persona] [--model <spec>] <task>", "error");
6561
7052
  return;
6562
7053
  }
6563
7054
 
@@ -6599,28 +7090,28 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6599
7090
 
6600
7091
  // ── Unified subagent commands ────────────────
6601
7092
  // Team specialists are addressed by persona name, research helpers by their rN
6602
- // handle — one command family covers both (mirroring /zoom's target resolution).
7093
+ // handle — one command family covers both (mirroring /af-zoom's target resolution).
6603
7094
  // The research-* commands remain as aliases of their agents-* counterparts.
6604
7095
 
6605
- // Resume a finished helper on its existing session. Shared by /agents-cont and
6606
- // its /research-cont alias.
7096
+ // Resume a finished helper on its existing session. Shared by /af-agents-cont and
7097
+ // its /af-research-cont alias.
6607
7098
  const researchContHandler = async (args: string | undefined, ctx: any) => {
6608
7099
  widgetCtx = ctx;
6609
7100
  const trimmed = (args ?? "").trim();
6610
7101
  const sp = trimmed.indexOf(" ");
6611
7102
  if (sp === -1) {
6612
- ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
7103
+ ctx.ui.notify("Usage: /af-agents-cont rN <prompt>", "error");
6613
7104
  return;
6614
7105
  }
6615
7106
  const rid = parseResearchHandle(trimmed.slice(0, sp));
6616
7107
  const prompt = trimmed.slice(sp + 1).trim();
6617
7108
  const state = rid != null ? researchStates.get(rid) : undefined;
6618
7109
  if (!state) {
6619
- ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
7110
+ ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /af-research to start one.`, "error");
6620
7111
  return;
6621
7112
  }
6622
7113
  if (!prompt) {
6623
- ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
7114
+ ctx.ui.notify("Usage: /af-agents-cont rN <prompt>", "error");
6624
7115
  return;
6625
7116
  }
6626
7117
  if (state.status === "running") {
@@ -6633,14 +7124,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6633
7124
  spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
6634
7125
  };
6635
7126
 
6636
- pi.registerCommand("agents-cont", {
6637
- description: "Continue a finished research helper: /agents-cont rN <prompt>",
7127
+ pi.registerCommand("af-agents-cont", {
7128
+ description: "Continue a finished research helper: /af-agents-cont rN <prompt>",
6638
7129
  getArgumentCompletions: researchHandleCompletions,
6639
7130
  handler: researchContHandler,
6640
7131
  });
6641
7132
 
6642
- pi.registerCommand("research-cont", {
6643
- description: "Continue a finished research helper (alias of /agents-cont): /research-cont rN <prompt>",
7133
+ pi.registerCommand("af-research-cont", {
7134
+ description: "Continue a finished research helper (alias of /af-agents-cont): /af-research-cont rN <prompt>",
6644
7135
  getArgumentCompletions: researchHandleCompletions,
6645
7136
  handler: researchContHandler,
6646
7137
  });
@@ -6660,7 +7151,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6660
7151
  updateResearchWidget();
6661
7152
  }
6662
7153
 
6663
- // Remove all helpers (SIGTERM any running). Shared by /agents-kill all and /research-clear.
7154
+ // Remove all helpers (SIGTERM any running). Shared by /af-agents-kill all and /af-research-clear.
6664
7155
  function clearResearchHelpers(ctx: any) {
6665
7156
  let killed = 0;
6666
7157
  const total = researchStates.size;
@@ -6681,32 +7172,32 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6681
7172
  ctx.ui.notify(msg, total === 0 ? "info" : "success");
6682
7173
  }
6683
7174
 
6684
- // /research-rm — alias of /agents-kill rN (kill on a research handle removes).
6685
- pi.registerCommand("research-rm", {
6686
- description: "Remove a research helper (alias of /agents-kill rN): /research-rm rN",
7175
+ // /af-research-rm — alias of /af-agents-kill rN (kill on a research handle removes).
7176
+ pi.registerCommand("af-research-rm", {
7177
+ description: "Remove a research helper (alias of /af-agents-kill rN): /af-research-rm rN",
6687
7178
  getArgumentCompletions: researchHandleCompletions,
6688
7179
  handler: async (args, ctx) => {
6689
7180
  widgetCtx = ctx;
6690
7181
  const rid = parseResearchHandle((args ?? "").trim());
6691
7182
  const state = rid != null ? researchStates.get(rid) : undefined;
6692
7183
  if (!state) {
6693
- ctx.ui.notify(`Usage: /research-rm rN. Known: ${Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ") || "none"}`, "error");
7184
+ ctx.ui.notify(`Usage: /af-research-rm rN. Known: ${Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ") || "none"}`, "error");
6694
7185
  return;
6695
7186
  }
6696
7187
  removeResearchHelper(state, ctx);
6697
7188
  },
6698
7189
  });
6699
7190
 
6700
- // /research-clear — alias of /agents-kill all.
6701
- pi.registerCommand("research-clear", {
6702
- description: "Remove all research helpers (alias of /agents-kill all)",
7191
+ // /af-research-clear — alias of /af-agents-kill all.
7192
+ pi.registerCommand("af-research-clear", {
7193
+ description: "Remove all research helpers (alias of /af-agents-kill all)",
6703
7194
  handler: async (_args, ctx) => {
6704
7195
  widgetCtx = ctx;
6705
7196
  clearResearchHelpers(ctx);
6706
7197
  },
6707
7198
  });
6708
7199
 
6709
- pi.registerCommand("dispatch-policy", {
7200
+ pi.registerCommand("af-dispatch-policy", {
6710
7201
  description: "Show dispatch backend routing (dispatch-policy.yaml) for the active team",
6711
7202
  handler: async (_args, ctx) => {
6712
7203
  widgetCtx = ctx;
@@ -6723,15 +7214,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6723
7214
  const src = existsSync(policyPath) ? ".pi/agents/dispatch-policy.yaml" : "(no dispatch-policy.yaml — all native)";
6724
7215
  ctx.ui.notify(
6725
7216
  `Dispatch backends — ${src}, default: ${dispatchPolicy.default}\n${lines.join("\n") || "(no active team)"}\n` +
6726
- `Routing is decided per dispatch against the live coms pool (/coms to refresh).`,
7217
+ `Routing is decided per dispatch against the live coms pool (/af-coms to refresh).`,
6727
7218
  "info",
6728
7219
  );
6729
7220
  },
6730
7221
  });
6731
7222
 
6732
7223
  // 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.
7224
+ // (rN), each annotated with status — for the unified /af-agents-kill and
7225
+ // /af-agents-restart.
6735
7226
  const subagentTargetCompletions = (prefix: string): AutocompleteItem[] | null => {
6736
7227
  const items = [...(agentNameCompletions("") ?? []), ...(researchHandleCompletions("") ?? [])];
6737
7228
  if (items.length === 0) return null;
@@ -6739,7 +7230,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6739
7230
  return filtered.length > 0 ? filtered : items;
6740
7231
  };
6741
7232
 
6742
- // /agents-kill completions additionally offer "all" (research helpers only).
7233
+ // /af-agents-kill completions additionally offer "all" (research helpers only).
6743
7234
  const agentsKillCompletions = (prefix: string): AutocompleteItem[] | null => {
6744
7235
  const targets = subagentTargetCompletions("") ?? [];
6745
7236
  const items = researchStates.size > 0
@@ -6750,8 +7241,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6750
7241
  return filtered.length > 0 ? filtered : items;
6751
7242
  };
6752
7243
 
6753
- pi.registerCommand("agents-kill", {
6754
- description: "Kill a running specialist, or kill & remove research helper(s): /agents-kill <name|rN|all>",
7244
+ pi.registerCommand("af-agents-kill", {
7245
+ description: "Kill a running specialist, or kill & remove research helper(s): /af-agents-kill <name|rN|all>",
6755
7246
  getArgumentCompletions: agentsKillCompletions,
6756
7247
  handler: async (args, ctx) => {
6757
7248
  widgetCtx = ctx;
@@ -6782,7 +7273,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6782
7273
  ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6783
7274
  ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6784
7275
  ].join(", ");
6785
- ctx.ui.notify(`Usage: /agents-kill <name|rN|all>. Known: ${known || "none"}`, "error");
7276
+ ctx.ui.notify(`Usage: /af-agents-kill <name|rN|all>. Known: ${known || "none"}`, "error");
6786
7277
  return;
6787
7278
  }
6788
7279
  if (state.status !== "running" || (!state.proc && !state.comsAbort)) {
@@ -6805,16 +7296,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6805
7296
  },
6806
7297
  });
6807
7298
 
6808
- pi.registerCommand("agents-restart", {
6809
- description: "Kill and re-run a specialist's (or re-run a finished research helper's) last task fresh: /agents-restart <name|rN>",
7299
+ pi.registerCommand("af-agents-restart", {
7300
+ description: "Kill and re-run a specialist's (or re-run a finished research helper's) last task fresh: /af-agents-restart <name|rN>",
6810
7301
  getArgumentCompletions: subagentTargetCompletions,
6811
7302
  handler: async (args, ctx) => {
6812
7303
  widgetCtx = ctx;
6813
7304
  const name = args?.trim();
6814
7305
  // 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
7306
+ // (unlike /af-agents-cont, which resumes the existing one). A running helper
6816
7307
  // can't be restarted mid-flight — spawnResearch's promise is held by its
6817
- // original caller, and /agents-kill removes the helper outright.
7308
+ // original caller, and /af-agents-kill removes the helper outright.
6818
7309
  const rid = name ? parseResearchHandle(name) : null;
6819
7310
  if (rid != null) {
6820
7311
  const rState = researchStates.get(rid);
@@ -6824,7 +7315,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6824
7315
  return;
6825
7316
  }
6826
7317
  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");
7318
+ ctx.ui.notify(`Research r${rState.id} is still running — wait for it to finish (or /af-agents-kill r${rState.id} to discard it and /af-research the task again).`, "warning");
6828
7319
  return;
6829
7320
  }
6830
7321
  if (!rState.task) {
@@ -6844,7 +7335,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6844
7335
  ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6845
7336
  ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6846
7337
  ].join(", ");
6847
- ctx.ui.notify(`Usage: /agents-restart <name|rN>. Known: ${known || "none"}`, "error");
7338
+ ctx.ui.notify(`Usage: /af-agents-restart <name|rN>. Known: ${known || "none"}`, "error");
6848
7339
  return;
6849
7340
  }
6850
7341
  const task = state.task;
@@ -6869,6 +7360,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6869
7360
  await terminated;
6870
7361
  }
6871
7362
  // Re-run fresh: a frozen session file may be inconsistent, so drop it (no -c).
7363
+ // The file itself still reaches pi via --session, so an unusable one is
7364
+ // quarantined by dispatchAgent's session preflight, not here.
6872
7365
  state.sessionFile = null;
6873
7366
  ctx.ui.notify(`Restarting ${displayName(state.def.name)} (fresh)...`, "info");
6874
7367
  const result = await dispatchAgent(state.def.name, task, ctx);
@@ -6886,7 +7379,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6886
7379
  },
6887
7380
  });
6888
7381
 
6889
- pi.registerCommand("persona", {
7382
+ pi.registerCommand("af-persona", {
6890
7383
  description: "Select or reset the dispatcher persona (orchestrator flavor)",
6891
7384
  handler: async (_args, ctx) => {
6892
7385
  widgetCtx = ctx;
@@ -6919,9 +7412,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6919
7412
  },
6920
7413
  });
6921
7414
 
6922
- // ── Embedded coms: /coms + /handoff ──
7415
+ // ── Embedded coms: /af-coms + /af-handoff ──
6923
7416
 
6924
- // Completions over live peer names for /handoff.
7417
+ // Completions over live peer names for /af-handoff.
6925
7418
  const comsPeerCompletions = (prefix: string): AutocompleteItem[] | null => {
6926
7419
  // Same pool scope as coms_send/handoff resolution — only offer peers you can reach.
6927
7420
  const entries = peersInScope();
@@ -6932,7 +7425,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6932
7425
  return filtered.length > 0 ? filtered : items;
6933
7426
  };
6934
7427
 
6935
- pi.registerCommand("coms", {
7428
+ pi.registerCommand("af-coms", {
6936
7429
  description: "Force-refresh the coms pool widget (or filter with --all / --project <name>)",
6937
7430
  handler: async (args, ctx) => {
6938
7431
  if (!comsReady) { ctx.ui.notify("coms is not active in this session.", "warning"); return; }
@@ -6959,35 +7452,44 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6959
7452
  // context % rides the keepalive refresh.
6960
7453
  pi.on("before_agent_start", async () => {
6961
7454
  turnState = "working";
7455
+ if (monitorBridge && monitorTurnId) monitorBridge.finishParent(monitorTurnId, "completed");
7456
+ if (monitorBridge && monitorHubId) {
7457
+ monitorTurnId = `hub-turn-${monitorHubId}-${crypto.randomUUID()}`;
7458
+ monitorBridge.startParent({ id: monitorTurnId, hubInstanceId: monitorHubId, checkoutId: currentCtx?.cwd || process.cwd() });
7459
+ } else monitorTurnId = null;
6962
7460
  if (herdrPresence && identity) {
6963
7461
  const pct = Math.round(currentCtx?.getContextUsage()?.percent ?? 0);
6964
- void herdrPresence.report("working", formatPeerStatus(identity.name, pct, inboundQueue.size));
7462
+ void herdrPresence.report("working", { name: identity.name, project: identity.project, contextUsedPct: pct, queueDepth: inboundQueue.size });
6965
7463
  }
6966
7464
  });
6967
7465
  pi.on("agent_end", async () => {
6968
7466
  turnState = "idle";
7467
+ if (monitorBridge && monitorTurnId) {
7468
+ monitorBridge.finishParent(monitorTurnId, "completed");
7469
+ monitorTurnId = null;
7470
+ }
6969
7471
  if (herdrPresence && identity) {
6970
7472
  const pct = Math.round(currentCtx?.getContextUsage()?.percent ?? 0);
6971
- void herdrPresence.report("idle", formatPeerStatus(identity.name, pct, inboundQueue.size));
7473
+ void herdrPresence.report("idle", { name: identity.name, project: identity.project, contextUsedPct: pct, queueDepth: inboundQueue.size });
6972
7474
  }
6973
7475
  });
6974
7476
 
6975
- // /handoff <peer> — hand the session off to a coms peer. Per decision G1 we do NOT
7477
+ // /af-handoff <peer> — hand the session off to a coms peer. Per decision G1 we do NOT
6976
7478
  // extract the compaction summary; instead we ask the dispatcher LLM (next turn) to
6977
7479
  // compose a SELF-CONTAINED brief and coms_send it, then await + relay the reply.
6978
- pi.registerCommand("handoff", {
6979
- description: "Hand the session off to a coms peer (the dispatcher composes a self-contained brief): /handoff <peer>",
7480
+ pi.registerCommand("af-handoff", {
7481
+ description: "Hand the session off to a coms peer (the dispatcher composes a self-contained brief): /af-handoff <peer>",
6980
7482
  getArgumentCompletions: comsPeerCompletions,
6981
7483
  handler: async (args, ctx) => {
6982
- if (!comsReady) { ctx.ui.notify("coms is not active in this session — /handoff unavailable.", "warning"); return; }
7484
+ if (!comsReady) { ctx.ui.notify("coms is not active in this session — /af-handoff unavailable.", "warning"); return; }
6983
7485
  const target = (args ?? "").trim();
6984
7486
  if (!target) {
6985
- ctx.ui.notify("Usage: /handoff <peer>. See the coms pool for live peer names.", "error");
7487
+ ctx.ui.notify("Usage: /af-handoff <peer>. See the coms pool for live peer names.", "error");
6986
7488
  return;
6987
7489
  }
6988
7490
  const peer = resolveTarget(target);
6989
7491
  if (!peer) {
6990
- ctx.ui.notify(`coms: no live peer "${target}". Use /coms to refresh the pool.`, "error");
7492
+ ctx.ui.notify(`coms: no live peer "${target}". Use /af-coms to refresh the pool.`, "error");
6991
7493
  return;
6992
7494
  }
6993
7495
  const handoffToken = crypto.randomBytes(8).toString("hex");
@@ -7007,18 +7509,18 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7007
7509
  },
7008
7510
  });
7009
7511
 
7010
- // /compound [focus] — end-of-session compound-learning pass. Mirrors /handoff's
7512
+ // /af-compound [focus] — end-of-session compound-learning pass. Mirrors /af-handoff's
7011
7513
  // shape: the dispatcher LLM (which saw the whole session) composes the
7012
7514
  // candidate-lessons brief itself, gates it on the user, then dispatches the
7013
7515
  // documenter to land the approved lessons per skills/compound-learning/SKILL.md.
7014
7516
  // The rules/docs targets come from the overrides file; artifacts travel as
7015
7517
  // paths through the dispatch's `artifacts` array, never as pasted bodies.
7016
- pi.registerCommand("compound", {
7017
- description: "Capture this session's lessons into the project's rules/docs via the documenter: /compound [focus]",
7518
+ pi.registerCommand("af-compound", {
7519
+ description: "Capture this session's lessons into the project's rules/docs via the documenter: /af-compound [focus]",
7018
7520
  handler: async (args, ctx) => {
7019
7521
  if (!agentStates.has("documenter")) {
7020
7522
  ctx.ui.notify(
7021
- "compound: the documenter persona is not in the active team — switch with /agents-team (e.g. default or release), then re-run /compound.",
7523
+ "compound: the documenter persona is not in the active team — switch with /af-agents-team (e.g. default or release), then re-run /af-compound.",
7022
7524
  "warning",
7023
7525
  );
7024
7526
  return;
@@ -7053,9 +7555,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7053
7555
  },
7054
7556
  });
7055
7557
 
7056
- // ── ask_user wait tracking (for /agents-history real-work) ──
7558
+ // ── ask_user wait tracking (for /af-agents-history real-work) ──
7057
7559
  // pi-ask-user blocks the dispatcher turn while the human answers. Bracket each
7058
- // ask_user call with its tool_execution start/end so /agents-history can subtract
7560
+ // ask_user call with its tool_execution start/end so /af-agents-history can subtract
7059
7561
  // that "away from keyboard" time from the dispatcher's real work.
7060
7562
  pi.on("tool_execution_start", async (event) => {
7061
7563
  if (event.toolName === "ask_user") askUserStarts.set(event.toolCallId, Date.now());
@@ -7075,7 +7577,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7075
7577
  // ── System Prompt Override ───────────────────
7076
7578
 
7077
7579
  pi.on("before_agent_start", async (_event, _ctx) => {
7078
- // Open a fresh dispatcher turn for /agents-history. The orchestrator entry is
7580
+ // Open a fresh dispatcher turn for /af-agents-history. The orchestrator entry is
7079
7581
  // created lazily (only if this turn actually dispatches), so chat-only turns
7080
7582
  // add no history rows. Defensively close any entry a prior turn left open
7081
7583
  // (e.g. an aborted turn where agent_end never fired).
@@ -7220,7 +7722,7 @@ to how interesting the work is.
7220
7722
 
7221
7723
  ## Execution mode: ${hubMode}${turnTaskTier ? ` · tier: ${turnTaskTier}` : ""}
7222
7724
  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):
7725
+ spawn_research refuse; a new user message opens a fresh window; /af-hub-mode switches mode):
7224
7726
  - dispatch_agent calls: ${cap(budget.maxDispatches)} · spawn_research calls: ${cap(budget.maxResearch)}
7225
7727
  - turn wall clock: ${capMin(budget.wallMs)} · per-run deadline: ${capMin(budget.agentTurnMs)}
7226
7728
  Plan within the budget: batch related work into ONE dispatch (a coherent slice of 4–6
@@ -7238,7 +7740,7 @@ ${hubMode === "fast"
7238
7740
  verification and report back.
7239
7741
  - Nested delegation is disabled; do not commission inventories or parity audits.
7240
7742
  - 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.`
7743
+ switch modes (/af-hub-mode standard) instead of burning the budget.`
7242
7744
  : hubMode === "standard"
7243
7745
  ? `STANDARD mode rules: rigor where it pays, batching everywhere else.
7244
7746
  - At most ONE reconnaissance pass before building (skip it for familiar code); prefer the
@@ -7261,6 +7763,12 @@ acceptance assertions; build it before you dispatch, and refuse "done" until eac
7261
7763
  assertions and record them with \`set_assertions\` — one pass condition each, tagged
7262
7764
  test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
7263
7765
  Pass the relevant assertions VERBATIM into each dispatch.
7766
+ - Every assertion NAMES ITS SOURCE (\`source: "PLAN-x.md:585-595"\`, \`"user request"\`,
7767
+ \`"review finding F3"\`). The hub refuses a sourceless batch by id: a specialist told to
7768
+ prove A9 must be able to read where A9 came from instead of asking you.
7769
+ - Keep at most ${MAX_OPEN_ASSERTIONS} assertions OPEN at once. A large task still has many
7770
+ assertions — declare the batch the next dispatches actually prove, and \`set_assertions\`
7771
+ the next batch when it starts. Over the cap the hub accepts the call but warns.
7264
7772
  - Keep assertions NARROW: one subsystem / one behavior each. Never bundle several
7265
7773
  subsystems into one giant assertion — a compound assertion forces a full re-audit after
7266
7774
  every small fix. After a fix, re-verify the touched assertions only.
@@ -7303,12 +7811,15 @@ You are ALSO a peer on the coms mesh — project "${identity.project}", name "${
7303
7811
  your own team you can talk to the peers in your coms POOL — the agents shown in the pool widget:
7304
7812
  - \`coms_list\` — discover the peers in your pool (names, models, live context usage). The pool is
7305
7813
  scoped to YOUR project and excludes private (explicit) peers. You CANNOT widen this — only the human
7306
- can, with \`/coms --project <name>\` or \`/coms --all\`. Do not ask coms_list for other projects.
7814
+ can, with \`/af-coms --project <name>\` or \`/af-coms --all\`. Do not ask coms_list for other projects.
7307
7815
  - \`coms_send\` returns a msg_id; then \`coms_await\` (blocking) or \`coms_get\` (poll) reads the reply.
7816
+ For long work put the SAME budget on both calls: \`coms_send(reply_timeout_ms: N, ...)\`, then
7817
+ \`coms_await(timeout_ms: N, ...)\`. The send controls the receiver; await controls only your local
7818
+ wait. A timeout returns pending — await/get the same msg_id again, never re-send the task.
7308
7819
  This lets you use a peer as an on-demand subagent: send a SELF-CONTAINED task, await it, and fold the
7309
7820
  result into your plan. A peer does NOT share your context — spell out everything it needs.
7310
- - Only peers in your pool are reachable. \`coms_send\`/\`/handoff\` to anyone outside it is refused. If
7311
- you need a peer that is not in the pool, ASK THE HUMAN to widen scope (\`/coms --project\`/\`--all\`),
7821
+ - Only peers in your pool are reachable. \`coms_send\`/\`/af-handoff\` to anyone outside it is refused. If
7822
+ you need a peer that is not in the pool, ASK THE HUMAN to widen scope (\`/af-coms --project\`/\`--all\`),
7312
7823
  then retry. Do not pass cross-project context to a peer unless the human approved that reach.
7313
7824
  - Prefer \`dispatch_agent\`/\`spawn_research\` for in-team work; reach for coms when a task needs another
7314
7825
  STANDING agent already in your pool (a human-driven peer, a specialist outside this team).
@@ -7328,8 +7839,8 @@ ${languageLines}
7328
7839
  ## Active Team: ${activeTeamName}
7329
7840
  Members: ${teamMembers}
7330
7841
  You can ONLY dispatch to agents listed below. Do not attempt to dispatch to agents
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)
7842
+ outside this team. The roster CAN change mid-session: the human via /af-agents-add,
7843
+ /af-agents-drop, /af-agents-team — or you via \`team_adjust\` (add/drop with a reason)
7333
7844
  when the current roster genuinely cannot serve the task. Use it sparingly; more
7334
7845
  personas is usually the wrong answer.
7335
7846
 
@@ -7365,9 +7876,17 @@ This session runs inside a herdr workspace and can drive panes:
7365
7876
  - \`herdr_spawn_peer\` stands up an extra worker next to you — a persona peer (joins the coms
7366
7877
  pool, then talk to it via \`coms_send\`) or a raw command pane (a build watcher, a server).
7367
7878
  Spawn deliberately; every pane is a process the human sees. Tear down what you spawned.
7879
+ - A spawned persona peer BOOTS IDLE and waits for \`coms_send\`: the spawn hands it no task.
7880
+ The call waits for it to register and returns \`peer_ready\` with its coms name. Spawn one
7881
+ only immediately before the first message you will send it — a peer spawned "to have it
7882
+ ready" and never addressed is an empty pane named like a worker. If you sent it no work
7883
+ by the end of the turn, say so and offer to close it; the hub names unaddressed
7884
+ hub-spawned peers in the session digest.
7368
7885
  - \`herdr_read_pane\` is read-to-decide: peek at a worker/tool pane's recent output before
7369
- acting on it. It is NOT a messaging channel — prefer \`coms_send\`/\`coms_await\` for pi and
7370
- bridged peers; reading screens is the last resort for unbridged tools.
7886
+ acting on it. It is NOT a messaging channel and NOT a status poll — \`coms_list\` already
7887
+ reports each peer's \`pane_id\` and \`status\` (idle | working | booting), so check that
7888
+ before sending. Prefer \`coms_send\`/\`coms_await\` for pi and bridged peers; reading screens
7889
+ is the last resort for unbridged tools and post-mortems.
7371
7890
  - \`herdr_close_pane\` kills a pane and asks the HUMAN to confirm first. Close only panes you
7372
7891
  spawned, when their job is done or they are stuck.
7373
7892
  - \`herdr_notify\` reaches the human via desktop notification when they are away — use it when
@@ -7419,7 +7938,7 @@ ${researchCatalog}`;
7419
7938
  }
7420
7939
  researchStates.clear();
7421
7940
  nextResearchId = 1;
7422
- // Wipe the /agents-history log from any previous session.
7941
+ // Wipe the /af-agents-history log from any previous session.
7423
7942
  executionHistory.length = 0;
7424
7943
  currentOrchestratorEntry = null;
7425
7944
  turnActive = false;
@@ -7435,6 +7954,7 @@ ${researchCatalog}`;
7435
7954
  st.delegationsWatcher = undefined;
7436
7955
  }
7437
7956
  delegatedTokens = 0;
7957
+ hubSpawnedPeers.clear();
7438
7958
  widgetCtx = _ctx;
7439
7959
  contextWindow = _ctx.model?.contextWindow || 0;
7440
7960
  safetyHarnessPath = resolveSafetyHarness(_ctx.cwd);
@@ -7502,7 +8022,12 @@ ${researchCatalog}`;
7502
8022
  });
7503
8023
  },
7504
8024
  });
8025
+ const eventJournal = new MonitorEventJournal({ file: path.join(monitorConfig.runtimeDir, `monitor-events-${stableHubId}.ndjson`) });
8026
+ const invokeJournal = new MonitorInvokeJournal(path.join(monitorConfig.runtimeDir, `monitor-invokes-${stableHubId}.ndjson`));
7505
8027
  monitorBridge = createMonitorSessionBridge({
8028
+ events: eventJournal,
8029
+ hubInstanceId: stableHubId,
8030
+ onEventJournalError: (error: unknown) => _ctx.ui.notify(`Agent Fleet monitor event journal unavailable: ${error instanceof Error ? error.message : String(error)}`, "warning"),
7506
8031
  runtime: new MonitorRuntime({
7507
8032
  runtimeDir: monitorConfig.runtimeDir,
7508
8033
  profileId: monitorConfig.profileId,
@@ -7518,8 +8043,20 @@ ${researchCatalog}`;
7518
8043
  reason: "unsupported",
7519
8044
  },
7520
8045
  });
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 });
8046
+ const invoke = createMonitorInvokeAdmission({
8047
+ journal: invokeJournal,
8048
+ task: (id: string, generation: number) => monitorBridge?.snapshot().tasks.find((task: any) => task.id === id && task.generation === generation),
8049
+ owner: () => monitorOwnerId,
8050
+ queueDepth: () => inboundQueue.size,
8051
+ queueLimit: 64,
8052
+ enqueue: createWatchdogFollowUpEnqueue((message, options) => pi.sendMessage(message, options)),
8053
+ publish: (kind: "action.requested" | "action.accepted" | "action.rejected" | "action.completed" | "hub.queue_depth_changed", task: any, extra?: any) => monitorBridge?.publishEvent(kind, task, extra),
8054
+ });
8055
+ const registration = await monitorLifecycle.startBridge(monitorBridge, {
8056
+ profilePath: monitorConfig.profilePath, profileId: monitorConfig.profileId, hubInstanceId: stableHubId,
8057
+ events: (request: any) => eventJournal.replay(request.afterSequence, request.limit, request.waitMs, request.signal), invoke,
8058
+ });
8059
+ monitorOwnerId = registration?.ownerId;
7523
8060
  } catch (error) {
7524
8061
  monitorLifecycle = null;
7525
8062
  _ctx.ui.notify(`Agent Fleet monitor disabled: ${error instanceof Error ? error.message : String(error)}`, "warning");
@@ -7572,14 +8109,15 @@ ${researchCatalog}`;
7572
8109
 
7573
8110
  server = await bindEndpoint(endpoint, connHandler);
7574
8111
 
8112
+ const started_at = nowIso();
7575
8113
  const entry: RegistryEntry = {
7576
8114
  session_id, name, purpose, model, color,
7577
8115
  pid: process.pid, endpoint, cwd,
7578
- started_at: nowIso(), explicit, version: 1,
8116
+ started_at, explicit, version: 1,
7579
8117
  };
7580
8118
  const registryFile = writeRegistryAtomic(entry, project);
7581
8119
 
7582
- identity = { session_id, name, purpose, color, project, explicit, cwd, model, endpoint, registryFile };
8120
+ identity = { session_id, name, purpose, color, project, explicit, cwd, model, endpoint, registryFile, started_at };
7583
8121
  includeExplicit = false;
7584
8122
  displayProject = project;
7585
8123
  comsReady = true;
@@ -7593,14 +8131,26 @@ ${researchCatalog}`;
7593
8131
  // Presence backend: herdr (push events, no polling) when this
7594
8132
  // session runs inside a herdr pane with a live server; the files
7595
8133
  // ping loop otherwise. The registry keepalive runs in BOTH — it
7596
- // carries the full agent card (context %, queue depth) that
7597
- // herdr's 32-char custom_status cannot, and keeps us
7598
- // discoverable to peers running outside herdr panes.
8134
+ // carries the full agent card (purpose, model, colour) that a
8135
+ // pane annotation is no place for, and keeps us discoverable
8136
+ // to peers running outside herdr panes.
7599
8137
  const useHerdr = await herdrPresenceAvailable();
7600
8138
  if (useHerdr) {
7601
8139
  const paneId = herdrPaneId()!;
7602
- herdrPresence = new HerdrPresence({ paneId, source: `coms:${session_id}` });
7603
- void herdrPresence.report("idle", formatPeerStatus(name, 0, 0));
8140
+ herdrPresence = new HerdrPresence({
8141
+ paneId,
8142
+ source: `coms:${session_id}`,
8143
+ // A herdr that rejects our annotation dialect used to
8144
+ // be invisible: presence swallows errors, so the
8145
+ // sidebar simply stayed blank and every watcher saw
8146
+ // "detached" forever.
8147
+ onError: (err, dialect) => {
8148
+ try {
8149
+ pi.appendEntry("coms-log", { event: "presence_dialect_rejected", dialect, reason: err?.message ?? String(err) });
8150
+ } catch { /* best-effort */ }
8151
+ },
8152
+ });
8153
+ void herdrPresence.report("idle", { name, project, contextUsedPct: 0, queueDepth: 0 });
7604
8154
  herdrWatch = new HerdrAgentWatch({
7605
8155
  ownPaneId: paneId,
7606
8156
  onChange: (agents) => herdrSyncPeerCards(agents),
@@ -7625,7 +8175,7 @@ ${researchCatalog}`;
7625
8175
  // cards against the registry heartbeats just written.
7626
8176
  if (herdrPresence && identity) {
7627
8177
  const pct = Math.round(currentCtx?.getContextUsage()?.percent ?? 0);
7628
- void herdrPresence.report(turnState, formatPeerStatus(identity.name, pct, inboundQueue.size));
8178
+ void herdrPresence.report(turnState, { name: identity.name, project: identity.project, contextUsedPct: pct, queueDepth: inboundQueue.size });
7629
8179
  }
7630
8180
  if (herdrWatch) herdrSyncPeerCards(herdrWatch.current());
7631
8181
  }, KEEPALIVE_INTERVAL_MS);
@@ -7640,7 +8190,7 @@ ${researchCatalog}`;
7640
8190
 
7641
8191
  // ── Damage-control shared exemptions file ──
7642
8192
  // One per hub session (solo mode included). Exporting the path on our own
7643
- // process.env lets the co-loaded damage-control-continue mirror /allow
8193
+ // process.env lets the co-loaded damage-control-continue mirror /af-allow
7644
8194
  // session grants into the same file the spawned children read.
7645
8195
  if (!exemptionsFile) {
7646
8196
  exemptionsFile = exemptionsFilePath(identity?.session_id ?? `hub-solo-${process.pid}`);
@@ -7713,7 +8263,7 @@ ${researchCatalog}`;
7713
8263
  thinkingOverrides.clear();
7714
8264
  for (const def of allAgentDefs) {
7715
8265
  const lower = def.name.toLowerCase();
7716
- if (overrides.personaModels[lower]) def.model = overrides.personaModels[lower];
8266
+ if (overrides.personaModels[lower]) Object.assign(def, applyModelOverride(def, overrides.personaModels[lower]));
7717
8267
  if (overrides.personaModelLists[lower]) def.models = overrides.personaModelLists[lower];
7718
8268
  if (overrides.personaThinking[lower]) def.thinking = overrides.personaThinking[lower];
7719
8269
  // Delegation overrides: replace/add individual sub-roles (other declared
@@ -7721,7 +8271,15 @@ ${researchCatalog}`;
7721
8271
  const subOv = overrides.personaSubagents[lower];
7722
8272
  if (subOv) {
7723
8273
  def.subagents = { ...(def.subagents || {}) };
7724
- for (const [role, r] of Object.entries(subOv)) def.subagents[role] = r;
8274
+ for (const [role, r] of Object.entries(subOv)) {
8275
+ const declared = def.subagents[role];
8276
+ // A model-only override keeps the declared tool cap; an explicit
8277
+ // tools= value replaces it. Either way the frontmatter model is
8278
+ // retained as the one-shot runtime fallback.
8279
+ def.subagents[role] = declared
8280
+ ? applyModelOverride({ ...declared, ...(r.tools ? { tools: r.tools } : {}) }, r.model)
8281
+ : r;
8282
+ }
7725
8283
  }
7726
8284
  if (overrides.personaDelegateDepth[lower] !== undefined) {
7727
8285
  def.delegateDepth = overrides.personaDelegateDepth[lower];
@@ -7737,7 +8295,7 @@ ${researchCatalog}`;
7737
8295
  if (!def) {
7738
8296
  profileErrors.push(`profile "${profileName}": unknown persona "${persona}"`);
7739
8297
  } else if (!allowedModels(def).includes(model)) {
7740
- profileErrors.push(`profile "${profileName}": ${persona} does not declare ${model} (model:/models: in ${def.file})`);
8298
+ profileErrors.push(`profile "${profileName}": ${persona} does not declare ${model} (model:/af-models: in ${def.file})`);
7741
8299
  }
7742
8300
  }
7743
8301
  }
@@ -7763,13 +8321,13 @@ ${researchCatalog}`;
7763
8321
  // least one orchestrator persona exists, so it never blocks with nothing to pick.
7764
8322
  orchestratorPersonas = allAgentDefs.filter(d => (d.kind || "").toLowerCase() === "orchestrator");
7765
8323
  // Research personas (kind: research) — spawnable read-only via spawn_research and
7766
- // the /research command, independent of team membership.
8324
+ // the /af-research command, independent of team membership.
7767
8325
  researchPersonas = allAgentDefs.filter(d => (d.kind || "").toLowerCase() === "research");
7768
8326
  dispatcherPersona = null;
7769
8327
  personaGateEnabled = overrides.personaGate && orchestratorPersonas.length > 0;
7770
8328
  personaGateSatisfied = !personaGateEnabled;
7771
8329
 
7772
- // Default to first team — use /agents-team to switch
8330
+ // Default to first team — use /af-agents-team to switch
7773
8331
  const teamNames = Object.keys(teams);
7774
8332
  if (teamNames.length > 0) {
7775
8333
  activateTeam(teamNames[0]);
@@ -7807,7 +8365,7 @@ ${researchCatalog}`;
7807
8365
  ? "off (no `kind: orchestrator` personas found)"
7808
8366
  : "off (set `persona-gate: on` to enable)";
7809
8367
  const comsLabel = comsReady && identity
7810
- ? `📡 ${identity.name}@${identity.project} — peers via coms_list; /handoff <peer> to delegate`
8368
+ ? `📡 ${identity.name}@${identity.project} — peers via coms_list; /af-handoff <peer> to delegate`
7811
8369
  : soloMode
7812
8370
  ? "off (--solo: fixed specialists + research only)"
7813
8371
  : "off (endpoint bind failed — coms tools disabled)";
@@ -7818,9 +8376,9 @@ ${researchCatalog}`;
7818
8376
  .filter(([, s]) => s.prefer === "coms")
7819
8377
  .map(([n]) => n);
7820
8378
  const dispatchLabel = dispatchPolicy.default === "coms"
7821
- ? "coms default — any member with a live same-name pool peer is served by it (/dispatch-policy)"
8379
+ ? "coms default — any member with a live same-name pool peer is served by it (/af-dispatch-policy)"
7822
8380
  : comsPreferred.length > 0
7823
- ? `coms-preferred: ${comsPreferred.join(", ")} (live peer wins, /dispatch-policy for status)`
8381
+ ? `coms-preferred: ${comsPreferred.join(", ")} (live peer wins, /af-dispatch-policy for status)`
7824
8382
  : "all native (no substitutions in .pi/agents/dispatch-policy.yaml)";
7825
8383
  _ctx.ui.notify(
7826
8384
  `Team: ${activeTeamName} (${members})\n` +
@@ -7831,25 +8389,25 @@ ${researchCatalog}`;
7831
8389
  `Persona gate: ${personaGateLabel}\n` +
7832
8390
  `Coms: ${comsLabel}\n` +
7833
8391
  `Fleet: ${fleetLabel}\n\n` +
7834
- `/agents-team Select a team\n` +
7835
- `/agents-list List active agents and status\n` +
7836
- `/agents-history Timeline of agent runs — durations, parallel markers, grand total\n` +
7837
- `/agent-model <persona>[.<role>] Switch a persona's or sub-role's model\n` +
7838
- `/agent-model-thinking <persona> Switch a persona's thinking level\n` +
7839
- `/models [profile] Apply a named model profile to the team\n` +
7840
- `/agent-models-substitute <src> <tgt> Swap one model across all personas\n` +
7841
- `/dispatch-policy Show which members route to coms peers (dispatch-policy.yaml)\n` +
7842
- `/agents-kill <name> SIGTERM a frozen specialist (and its delegate children)\n` +
7843
- `/agents-restart <name> Kill + re-run its last task fresh\n` +
7844
- `/zoom <name|rN|child> Scrollable view of an agent / research / delegate-child stream\n` +
7845
- `/research <task> Spawn a read-only research helper (@persona, --model)\n` +
7846
- `/research-cont rN ... Resume a finished research helper\n` +
7847
- `/research-rm rN Remove a research helper (kill if running)\n` +
7848
- `/research-clear Remove all research helpers\n` +
7849
- `/persona Select/reset the dispatcher persona\n` +
7850
- `/coms [--all|--project N] Refresh the coms peer pool\n` +
7851
- `/handoff <peer> Hand the session off to a coms peer\n` +
7852
- `/compound [focus] Capture session lessons into the project rules/docs`,
8392
+ `/af-agents-team Select a team\n` +
8393
+ `/af-agents-list List active agents and status\n` +
8394
+ `/af-agents-history Timeline of agent runs — durations, parallel markers, grand total\n` +
8395
+ `/af-agent-model <persona>[.<role>] Switch a persona's or sub-role's model\n` +
8396
+ `/af-agent-model-thinking <persona> Switch a persona's thinking level\n` +
8397
+ `/af-models [profile] Apply a named model profile to the team\n` +
8398
+ `/af-agent-models-substitute <src> <tgt> Swap one model across all personas\n` +
8399
+ `/af-dispatch-policy Show which members route to coms peers (dispatch-policy.yaml)\n` +
8400
+ `/af-agents-kill <name> SIGTERM a frozen specialist (and its delegate children)\n` +
8401
+ `/af-agents-restart <name> Kill + re-run its last task fresh\n` +
8402
+ `/af-zoom <name|rN|child> Scrollable view of an agent / research / delegate-child stream\n` +
8403
+ `/af-research <task> Spawn a read-only research helper (@persona, --model)\n` +
8404
+ `/af-research-cont rN ... Resume a finished research helper\n` +
8405
+ `/af-research-rm rN Remove a research helper (kill if running)\n` +
8406
+ `/af-research-clear Remove all research helpers\n` +
8407
+ `/af-persona Select/reset the dispatcher persona\n` +
8408
+ `/af-coms [--all|--project N] Refresh the coms peer pool\n` +
8409
+ `/af-handoff <peer> Hand the session off to a coms peer\n` +
8410
+ `/af-compound [focus] Capture session lessons into the project rules/docs`,
7853
8411
  "info",
7854
8412
  );
7855
8413
  _ctx.ui.setStatus("dispatcher-persona", personaGateEnabled ? "Persona: (pick one)" : "Persona: Default");
@@ -7878,7 +8436,7 @@ ${researchCatalog}`;
7878
8436
 
7879
8437
  const left = renderHubFooterLeft(theme, HARNESS_VERSION, model, think, activeTeamName);
7880
8438
  const hint = theme.fg("muted", "Alt+A ") + theme.fg("dim", `view:${viewMode}`);
7881
- // The btw extension flips this global the first time a /btw command or
8439
+ // The btw extension flips this global the first time a /af-btw command or
7882
8440
  // Alt+' is used; surface its reopen shortcut right next to the Alt+A hint.
7883
8441
  const btwHint = (globalThis as { __btwActivated?: boolean }).__btwActivated
7884
8442
  ? theme.fg("muted", " · Alt+' ") + theme.fg("dim", "btw")
@@ -7910,7 +8468,7 @@ ${researchCatalog}`;
7910
8468
  // When this agent was addressed by a peer (an inbound prompt in the queue), the
7911
8469
  // turn's final assistant text becomes the response we ship back to the sender.
7912
8470
  pi.on("agent_end", async (_event, ctx) => {
7913
- // Close the /agents-history dispatcher turn (if this turn opened one). The
8471
+ // Close the /af-agents-history dispatcher turn (if this turn opened one). The
7914
8472
  // orchestrator entry's span covers all of its dispatches plus the wrap-up.
7915
8473
  turnActive = false;
7916
8474
  if (currentOrchestratorEntry) {
@@ -7920,6 +8478,12 @@ ${researchCatalog}`;
7920
8478
  historyRender?.();
7921
8479
  }
7922
8480
 
8481
+ // End-of-turn sweep: a peer spawned this turn and never sent to is still
8482
+ // running. Named once per turn it stays unaddressed; the close itself is
8483
+ // the human's call (herdr_close_pane keeps its confirmation).
8484
+ const peerSweep = unaddressedPeerSweep(Array.from(hubSpawnedPeers.values()));
8485
+ if (peerSweep) ctx.ui.notify(peerSweep.message, "warning");
8486
+
7923
8487
  const inbound = [...inboundQueue.values()].reverse().find((i) => !i.fulfilled);
7924
8488
  if (!inbound || !identity) return;
7925
8489