@chankov/agent-fleet 1.0.0 → 1.0.2

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 (598) hide show
  1. package/.pi/agents/model-profiles.yaml +2 -2
  2. package/.pi/extensions/package-lock.json +77 -45
  3. package/.pi/harnesses/agent-hub/README.md +116 -16
  4. package/.pi/harnesses/agent-hub/budget-continuation.ts +73 -0
  5. package/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  6. package/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  7. package/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  8. package/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  9. package/.pi/harnesses/agent-hub/hub-state-audit.js +73 -0
  10. package/.pi/harnesses/agent-hub/index.ts +1095 -465
  11. package/.pi/harnesses/agent-hub/package.json +1 -1
  12. package/.pi/harnesses/agent-hub/posture.ts +72 -17
  13. package/.pi/harnesses/agent-hub/run-budget.js +73 -13
  14. package/.pi/harnesses/agent-hub/spawn.ts +14 -2
  15. package/.pi/harnesses/ask-user-remote/index.ts +59 -4
  16. package/.pi/harnesses/coms/package.json +1 -1
  17. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  18. package/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  19. package/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  20. package/.pi/harnesses/lib/context-budget-view.ts +107 -0
  21. package/.pi/harnesses/lib/context-budget.ts +114 -0
  22. package/.pi/harnesses/lib/fleet-dashboard-ops.ts +37 -0
  23. package/.pi/harnesses/lib/fleet-detail-view.ts +92 -2
  24. package/.pi/harnesses/package-lock.json +73 -80
  25. package/.versions/1.0.1/.pi/agents/dispatch-policy.yaml +32 -0
  26. package/.versions/1.0.1/.pi/agents/model-profiles.yaml +27 -0
  27. package/.versions/1.0.1/.pi/agents/peers.yaml +142 -0
  28. package/.versions/1.0.1/.pi/agents/teams.yaml +41 -0
  29. package/.versions/1.0.1/.pi/damage-control-rules.yaml +297 -0
  30. package/.versions/1.0.1/.pi/extensions/agent-fleet-update-check/README.md +57 -0
  31. package/.versions/1.0.1/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  32. package/.versions/1.0.1/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  33. package/.versions/1.0.1/.pi/extensions/btw/README.md +120 -0
  34. package/.versions/1.0.1/.pi/extensions/btw/index.ts +914 -0
  35. package/.versions/1.0.1/.pi/extensions/btw/package.json +6 -0
  36. package/.versions/1.0.1/.pi/extensions/btw/state.js +179 -0
  37. package/.versions/1.0.1/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  38. package/.versions/1.0.1/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  39. package/.versions/1.0.1/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  40. package/.versions/1.0.1/.pi/extensions/compact-and-continue/README.md +42 -0
  41. package/.versions/1.0.1/.pi/extensions/compact-and-continue/index.ts +120 -0
  42. package/.versions/1.0.1/.pi/extensions/compact-and-continue/package.json +6 -0
  43. package/.versions/1.0.1/.pi/extensions/mcp-bridge/README.md +46 -0
  44. package/.versions/1.0.1/.pi/extensions/mcp-bridge/index.ts +206 -0
  45. package/.versions/1.0.1/.pi/extensions/mcp-bridge/package.json +6 -0
  46. package/.versions/1.0.1/.pi/extensions/package-lock.json +1143 -0
  47. package/.versions/1.0.1/.pi/extensions/package.json +9 -0
  48. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/README.md +205 -0
  49. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/config.ts +198 -0
  50. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  51. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/index.ts +248 -0
  52. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/package.json +6 -0
  53. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  54. package/.versions/1.0.1/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  55. package/.versions/1.0.1/.pi/harnesses/agent-hub/README.md +1065 -0
  56. package/.versions/1.0.1/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  57. package/.versions/1.0.1/.pi/harnesses/agent-hub/artifacts.js +146 -0
  58. package/.versions/1.0.1/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  59. package/.versions/1.0.1/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  60. package/.versions/1.0.1/.pi/harnesses/agent-hub/context-window.js +106 -0
  61. package/.versions/1.0.1/.pi/harnesses/agent-hub/delegate.ts +435 -0
  62. package/.versions/1.0.1/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  63. package/.versions/1.0.1/.pi/harnesses/agent-hub/drift-watchdog.js +211 -0
  64. package/.versions/1.0.1/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  65. package/.versions/1.0.1/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  66. package/.versions/1.0.1/.pi/harnesses/agent-hub/footer.ts +35 -0
  67. package/.versions/1.0.1/.pi/harnesses/agent-hub/helpers.ts +266 -0
  68. package/.versions/1.0.1/.pi/harnesses/agent-hub/hub-state-audit.js +55 -0
  69. package/.versions/1.0.1/.pi/harnesses/agent-hub/index.ts +9343 -0
  70. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  71. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  72. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  73. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  74. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  75. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  76. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  77. package/.versions/1.0.1/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  78. package/.versions/1.0.1/.pi/harnesses/agent-hub/package.json +7 -0
  79. package/.versions/1.0.1/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  80. package/.versions/1.0.1/.pi/harnesses/agent-hub/posture.ts +103 -0
  81. package/.versions/1.0.1/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  82. package/.versions/1.0.1/.pi/harnesses/agent-hub/research-retention.js +34 -0
  83. package/.versions/1.0.1/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  84. package/.versions/1.0.1/.pi/harnesses/agent-hub/return-contract.js +293 -0
  85. package/.versions/1.0.1/.pi/harnesses/agent-hub/return-extract.js +75 -0
  86. package/.versions/1.0.1/.pi/harnesses/agent-hub/review-findings.js +102 -0
  87. package/.versions/1.0.1/.pi/harnesses/agent-hub/run-budget.js +540 -0
  88. package/.versions/1.0.1/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  89. package/.versions/1.0.1/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  90. package/.versions/1.0.1/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  91. package/.versions/1.0.1/.pi/harnesses/agent-hub/session-health.js +110 -0
  92. package/.versions/1.0.1/.pi/harnesses/agent-hub/spawn.ts +354 -0
  93. package/.versions/1.0.1/.pi/harnesses/agent-hub/version.ts +42 -0
  94. package/.versions/1.0.1/.pi/harnesses/ask-user-remote/README.md +53 -0
  95. package/.versions/1.0.1/.pi/harnesses/ask-user-remote/index.ts +477 -0
  96. package/.versions/1.0.1/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  97. package/.versions/1.0.1/.pi/harnesses/coms/README.md +100 -0
  98. package/.versions/1.0.1/.pi/harnesses/coms/index.ts +1767 -0
  99. package/.versions/1.0.1/.pi/harnesses/coms/package.json +7 -0
  100. package/.versions/1.0.1/.pi/harnesses/coms/version.ts +42 -0
  101. package/.versions/1.0.1/.pi/harnesses/damage-control-continue/README.md +124 -0
  102. package/.versions/1.0.1/.pi/harnesses/damage-control-continue/index.ts +536 -0
  103. package/.versions/1.0.1/.pi/harnesses/damage-control-continue/package.json +7 -0
  104. package/.versions/1.0.1/.pi/harnesses/damage-control-continue/version.ts +42 -0
  105. package/.versions/1.0.1/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  106. package/.versions/1.0.1/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  107. package/.versions/1.0.1/.pi/harnesses/lib/fleet-dashboard-ops.ts +155 -0
  108. package/.versions/1.0.1/.pi/harnesses/lib/fleet-dashboard-view.ts +140 -0
  109. package/.versions/1.0.1/.pi/harnesses/lib/fleet-detail-view.ts +43 -0
  110. package/.versions/1.0.1/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  111. package/.versions/1.0.1/.pi/harnesses/lib/fleet-panel.ts +34 -0
  112. package/.versions/1.0.1/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  113. package/.versions/1.0.1/.pi/harnesses/lib/fleet-selection.ts +24 -0
  114. package/.versions/1.0.1/.pi/harnesses/lib/herdr-client.ts +472 -0
  115. package/.versions/1.0.1/.pi/harnesses/lib/herdr-presence.ts +399 -0
  116. package/.versions/1.0.1/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  117. package/.versions/1.0.1/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  118. package/.versions/1.0.1/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  119. package/.versions/1.0.1/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  120. package/.versions/1.0.1/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  121. package/.versions/1.0.1/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  122. package/.versions/1.0.1/.pi/harnesses/lib/spawned-peers.js +190 -0
  123. package/.versions/1.0.1/.pi/harnesses/package-lock.json +2046 -0
  124. package/.versions/1.0.1/.pi/harnesses/package.json +10 -0
  125. package/.versions/1.0.1/.pi/prompts/af-build.md +24 -0
  126. package/.versions/1.0.1/.pi/prompts/af-code-simplify.md +22 -0
  127. package/.versions/1.0.1/.pi/prompts/af-plan.md +16 -0
  128. package/.versions/1.0.1/.pi/prompts/af-review.md +16 -0
  129. package/.versions/1.0.1/.pi/prompts/af-set-hermes-telegram.md +15 -0
  130. package/.versions/1.0.1/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  131. package/.versions/1.0.1/.pi/prompts/af-ship.md +17 -0
  132. package/.versions/1.0.1/.pi/prompts/af-spec.md +15 -0
  133. package/.versions/1.0.1/.pi/prompts/af-test.md +19 -0
  134. package/.versions/1.0.1/.pi/skills/bowser/SKILL.md +145 -0
  135. package/.versions/1.0.1/.version +1 -0
  136. package/.versions/1.0.1/agents/architect.md +24 -0
  137. package/.versions/1.0.1/agents/bowser.md +27 -0
  138. package/.versions/1.0.1/agents/builder.md +54 -0
  139. package/.versions/1.0.1/agents/code-reviewer.md +208 -0
  140. package/.versions/1.0.1/agents/deep-researcher.md +32 -0
  141. package/.versions/1.0.1/agents/documenter.md +18 -0
  142. package/.versions/1.0.1/agents/orchestrator.md +72 -0
  143. package/.versions/1.0.1/agents/plan-reviewer.md +83 -0
  144. package/.versions/1.0.1/agents/planner.md +70 -0
  145. package/.versions/1.0.1/agents/releaser.md +24 -0
  146. package/.versions/1.0.1/agents/researcher.md +28 -0
  147. package/.versions/1.0.1/agents/security-auditor.md +167 -0
  148. package/.versions/1.0.1/agents/test-engineer.md +153 -0
  149. package/.versions/1.0.1/agents/web-debugger.md +43 -0
  150. package/.versions/1.0.1/agents/web-performance-auditor.md +193 -0
  151. package/.versions/1.0.1/bin/catalog/harness-runtime-closure.json +38 -0
  152. package/.versions/1.0.1/codex/CONDUCTOR.md +148 -0
  153. package/.versions/1.0.1/docs/ARCHITECTURE.md +337 -0
  154. package/.versions/1.0.1/docs/agent-fleet-setup.md +437 -0
  155. package/.versions/1.0.1/docs/claude-code-coms-bridge.md +128 -0
  156. package/.versions/1.0.1/docs/codex-remote-conductor.md +170 -0
  157. package/.versions/1.0.1/docs/coms-hermes-bridge.md +189 -0
  158. package/.versions/1.0.1/docs/getting-started.md +98 -0
  159. package/.versions/1.0.1/docs/npm-install.md +292 -0
  160. package/.versions/1.0.1/docs/pi-extensions.md +412 -0
  161. package/.versions/1.0.1/docs/pi-setup.md +74 -0
  162. package/.versions/1.0.1/docs/skill-anatomy.md +150 -0
  163. package/.versions/1.0.1/hermes/README.md +347 -0
  164. package/.versions/1.0.1/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  165. package/.versions/1.0.1/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  166. package/.versions/1.0.1/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  167. package/.versions/1.0.1/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  168. package/.versions/1.0.1/hermes/gates/gate-o-capability.md +8 -0
  169. package/.versions/1.0.1/hermes/gates/gate-o-validator-fixtures.json +1 -0
  170. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  171. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  172. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  173. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  174. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  175. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  176. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  177. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  178. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  179. package/.versions/1.0.1/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  180. package/.versions/1.0.1/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  181. package/.versions/1.0.1/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  182. package/.versions/1.0.1/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  183. package/.versions/1.0.1/hermes/skills/hub-conductor/SKILL.md +84 -0
  184. package/.versions/1.0.1/hermes/skills/hub-liaison/SKILL.md +84 -0
  185. package/.versions/1.0.1/hermes/skills/hub-watchdog/SKILL.md +76 -0
  186. package/.versions/1.0.1/hermes/skills/hub-watchdog/manifest.json +1 -0
  187. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  188. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  189. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  190. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  191. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  192. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  193. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  194. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  195. package/.versions/1.0.1/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  196. package/.versions/1.0.1/hermes/watchdog-tests/__init__.py +0 -0
  197. package/.versions/1.0.1/hooks/coms-stop-hook.mjs +84 -0
  198. package/.versions/1.0.1/install-manifest.json +2745 -0
  199. package/.versions/1.0.1/justfile +272 -0
  200. package/.versions/1.0.1/manifest-meta.json +882 -0
  201. package/.versions/1.0.1/references/accessibility-checklist.md +160 -0
  202. package/.versions/1.0.1/references/definition-of-done.md +67 -0
  203. package/.versions/1.0.1/references/fleet-coordination-patterns.md +151 -0
  204. package/.versions/1.0.1/references/observability-checklist.md +91 -0
  205. package/.versions/1.0.1/references/orchestration-patterns.md +370 -0
  206. package/.versions/1.0.1/references/performance-checklist.md +153 -0
  207. package/.versions/1.0.1/references/prompting-patterns.md +380 -0
  208. package/.versions/1.0.1/references/security-checklist.md +179 -0
  209. package/.versions/1.0.1/references/testing-patterns.md +236 -0
  210. package/.versions/1.0.1/scripts/codex-conductor.ts +41 -0
  211. package/.versions/1.0.1/scripts/codex-remote-control.ts +167 -0
  212. package/.versions/1.0.1/scripts/coms-claude-bridge.ts +411 -0
  213. package/.versions/1.0.1/scripts/coms-cli.ts +484 -0
  214. package/.versions/1.0.1/scripts/coms-hermes-bridge.ts +413 -0
  215. package/.versions/1.0.1/scripts/fleet.ts +185 -0
  216. package/.versions/1.0.1/scripts/hermes-monitor-capability-runner.ts +25 -0
  217. package/.versions/1.0.1/scripts/hermes-monitor-scenario.ts +474 -0
  218. package/.versions/1.0.1/scripts/hermes-watchdog-capability-probe.ts +45 -0
  219. package/.versions/1.0.1/scripts/install-hermes-plugin.sh +180 -0
  220. package/.versions/1.0.1/scripts/lib/claude-bridge-core.ts +210 -0
  221. package/.versions/1.0.1/scripts/lib/codex-conductor.ts +88 -0
  222. package/.versions/1.0.1/scripts/lib/codex-remote-control.ts +480 -0
  223. package/.versions/1.0.1/scripts/lib/coms-envelope.ts +582 -0
  224. package/.versions/1.0.1/scripts/lib/fake-herdr-server.ts +88 -0
  225. package/.versions/1.0.1/scripts/lib/fleet-command.ts +266 -0
  226. package/.versions/1.0.1/scripts/lib/herdr-layout.ts +281 -0
  227. package/.versions/1.0.1/scripts/lib/hermes-bridge-core.ts +241 -0
  228. package/.versions/1.0.1/scripts/lib/hermes-monitor-events.ts +1 -0
  229. package/.versions/1.0.1/scripts/lib/hermes-monitor-herdr.ts +2 -0
  230. package/.versions/1.0.1/scripts/lib/hermes-monitor-model.ts +3 -0
  231. package/.versions/1.0.1/scripts/lib/hermes-monitor-registry.ts +2 -0
  232. package/.versions/1.0.1/scripts/lib/hermes-monitor-socket.ts +2 -0
  233. package/.versions/1.0.1/scripts/lib/hermes-monitor-store.ts +2 -0
  234. package/.versions/1.0.1/scripts/lib/monitor-env.ts +146 -0
  235. package/.versions/1.0.1/scripts/lib/peer-launch.ts +318 -0
  236. package/.versions/1.0.1/scripts/lib/persona-banner.ts +62 -0
  237. package/.versions/1.0.1/scripts/lib/spawn-stagger.ts +101 -0
  238. package/.versions/1.0.1/scripts/lib/team-project.ts +213 -0
  239. package/.versions/1.0.1/scripts/lib/team-snapshot.ts +147 -0
  240. package/.versions/1.0.1/scripts/peer-banner.ts +40 -0
  241. package/.versions/1.0.1/scripts/peer-launch.ts +259 -0
  242. package/.versions/1.0.1/scripts/team-snapshot.ts +237 -0
  243. package/.versions/1.0.1/scripts/team-up.ts +406 -0
  244. package/.versions/1.0.1/skills/_internal/grilling.md +11 -0
  245. package/.versions/1.0.1/skills/browser-testing-with-devtools/SKILL.md +351 -0
  246. package/.versions/1.0.1/skills/code-review-and-quality/SKILL.md +381 -0
  247. package/.versions/1.0.1/skills/compound-learning/SKILL.md +137 -0
  248. package/.versions/1.0.1/skills/context-engineering/SKILL.md +291 -0
  249. package/.versions/1.0.1/skills/deprecation-and-migration/SKILL.md +206 -0
  250. package/.versions/1.0.1/skills/designing-agents/SKILL.md +394 -0
  251. package/.versions/1.0.1/skills/designing-agents/pi-harness-authoring.md +222 -0
  252. package/.versions/1.0.1/skills/frontend-ui-engineering/SKILL.md +328 -0
  253. package/.versions/1.0.1/skills/git-workflow-and-versioning/SKILL.md +316 -0
  254. package/.versions/1.0.1/skills/idea-refine/SKILL.md +182 -0
  255. package/.versions/1.0.1/skills/idea-refine/examples.md +238 -0
  256. package/.versions/1.0.1/skills/idea-refine/frameworks.md +99 -0
  257. package/.versions/1.0.1/skills/idea-refine/refinement-criteria.md +113 -0
  258. package/.versions/1.0.1/skills/idea-refine/scripts/idea-refine.sh +15 -0
  259. package/.versions/1.0.1/skills/incremental-implementation/SKILL.md +287 -0
  260. package/.versions/1.0.1/skills/interview-me/SKILL.md +226 -0
  261. package/.versions/1.0.1/skills/orchestration-verification/SKILL.md +181 -0
  262. package/.versions/1.0.1/skills/peer-coms/SKILL.md +90 -0
  263. package/.versions/1.0.1/skills/performance-optimization/SKILL.md +350 -0
  264. package/.versions/1.0.1/skills/planning-and-task-breakdown/SKILL.md +254 -0
  265. package/.versions/1.0.1/skills/security-and-hardening/SKILL.md +461 -0
  266. package/.versions/1.0.1/skills/spec-driven-development/SKILL.md +257 -0
  267. package/.versions/1.0.1/skills/using-agent-skills/SKILL.md +199 -0
  268. package/.versions/1.0.1/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  269. package/.versions/1.0.1/vendor/agent-skills-upstream/LICENSE +21 -0
  270. package/.versions/1.0.1/vendor/agent-skills-upstream/README.md +11 -0
  271. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  272. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  273. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  274. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  275. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  276. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  277. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  278. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  279. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  280. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  281. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  282. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  283. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  284. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  285. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  286. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  287. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  288. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  289. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  290. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  291. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  292. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  293. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  294. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  295. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  296. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  297. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  298. package/.versions/1.0.1/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  299. package/.versions/1.0.2/.pi/agents/dispatch-policy.yaml +32 -0
  300. package/.versions/1.0.2/.pi/agents/model-profiles.yaml +27 -0
  301. package/.versions/1.0.2/.pi/agents/peers.yaml +142 -0
  302. package/.versions/1.0.2/.pi/agents/teams.yaml +41 -0
  303. package/.versions/1.0.2/.pi/damage-control-rules.yaml +297 -0
  304. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/README.md +57 -0
  305. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  306. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  307. package/.versions/1.0.2/.pi/extensions/btw/README.md +120 -0
  308. package/.versions/1.0.2/.pi/extensions/btw/index.ts +914 -0
  309. package/.versions/1.0.2/.pi/extensions/btw/package.json +6 -0
  310. package/.versions/1.0.2/.pi/extensions/btw/state.js +179 -0
  311. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  312. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  313. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  314. package/.versions/1.0.2/.pi/extensions/compact-and-continue/README.md +42 -0
  315. package/.versions/1.0.2/.pi/extensions/compact-and-continue/index.ts +120 -0
  316. package/.versions/1.0.2/.pi/extensions/compact-and-continue/package.json +6 -0
  317. package/.versions/1.0.2/.pi/extensions/mcp-bridge/README.md +46 -0
  318. package/.versions/1.0.2/.pi/extensions/mcp-bridge/index.ts +206 -0
  319. package/.versions/1.0.2/.pi/extensions/mcp-bridge/package.json +6 -0
  320. package/.versions/1.0.2/.pi/extensions/package-lock.json +1175 -0
  321. package/.versions/1.0.2/.pi/extensions/package.json +9 -0
  322. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/README.md +205 -0
  323. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/config.ts +198 -0
  324. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  325. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/index.ts +248 -0
  326. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/package.json +6 -0
  327. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  328. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  329. package/.versions/1.0.2/.pi/harnesses/agent-hub/README.md +1156 -0
  330. package/.versions/1.0.2/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  331. package/.versions/1.0.2/.pi/harnesses/agent-hub/artifacts.js +146 -0
  332. package/.versions/1.0.2/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  333. package/.versions/1.0.2/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  334. package/.versions/1.0.2/.pi/harnesses/agent-hub/budget-continuation.ts +73 -0
  335. package/.versions/1.0.2/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  336. package/.versions/1.0.2/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  337. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  338. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  339. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-window.js +106 -0
  340. package/.versions/1.0.2/.pi/harnesses/agent-hub/delegate.ts +435 -0
  341. package/.versions/1.0.2/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  342. package/.versions/1.0.2/.pi/harnesses/agent-hub/drift-watchdog.js +211 -0
  343. package/.versions/1.0.2/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  344. package/.versions/1.0.2/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  345. package/.versions/1.0.2/.pi/harnesses/agent-hub/footer.ts +35 -0
  346. package/.versions/1.0.2/.pi/harnesses/agent-hub/helpers.ts +266 -0
  347. package/.versions/1.0.2/.pi/harnesses/agent-hub/hub-state-audit.js +73 -0
  348. package/.versions/1.0.2/.pi/harnesses/agent-hub/index.ts +9909 -0
  349. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  350. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  351. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  352. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  353. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  354. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  355. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  356. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  357. package/.versions/1.0.2/.pi/harnesses/agent-hub/package.json +7 -0
  358. package/.versions/1.0.2/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  359. package/.versions/1.0.2/.pi/harnesses/agent-hub/posture.ts +158 -0
  360. package/.versions/1.0.2/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  361. package/.versions/1.0.2/.pi/harnesses/agent-hub/research-retention.js +34 -0
  362. package/.versions/1.0.2/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  363. package/.versions/1.0.2/.pi/harnesses/agent-hub/return-contract.js +293 -0
  364. package/.versions/1.0.2/.pi/harnesses/agent-hub/return-extract.js +75 -0
  365. package/.versions/1.0.2/.pi/harnesses/agent-hub/review-findings.js +102 -0
  366. package/.versions/1.0.2/.pi/harnesses/agent-hub/run-budget.js +539 -0
  367. package/.versions/1.0.2/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  368. package/.versions/1.0.2/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  369. package/.versions/1.0.2/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  370. package/.versions/1.0.2/.pi/harnesses/agent-hub/session-health.js +110 -0
  371. package/.versions/1.0.2/.pi/harnesses/agent-hub/spawn.ts +366 -0
  372. package/.versions/1.0.2/.pi/harnesses/agent-hub/version.ts +42 -0
  373. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/README.md +53 -0
  374. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/index.ts +532 -0
  375. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  376. package/.versions/1.0.2/.pi/harnesses/coms/README.md +100 -0
  377. package/.versions/1.0.2/.pi/harnesses/coms/index.ts +1767 -0
  378. package/.versions/1.0.2/.pi/harnesses/coms/package.json +7 -0
  379. package/.versions/1.0.2/.pi/harnesses/coms/version.ts +42 -0
  380. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/README.md +124 -0
  381. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/index.ts +536 -0
  382. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/package.json +7 -0
  383. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/version.ts +42 -0
  384. package/.versions/1.0.2/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  385. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  386. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  387. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-view.ts +107 -0
  388. package/.versions/1.0.2/.pi/harnesses/lib/context-budget.ts +114 -0
  389. package/.versions/1.0.2/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  390. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  391. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  392. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  393. package/.versions/1.0.2/.pi/harnesses/lib/fleet-dashboard-ops.ts +155 -0
  394. package/.versions/1.0.2/.pi/harnesses/lib/fleet-dashboard-view.ts +140 -0
  395. package/.versions/1.0.2/.pi/harnesses/lib/fleet-detail-view.ts +133 -0
  396. package/.versions/1.0.2/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  397. package/.versions/1.0.2/.pi/harnesses/lib/fleet-panel.ts +34 -0
  398. package/.versions/1.0.2/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  399. package/.versions/1.0.2/.pi/harnesses/lib/fleet-selection.ts +24 -0
  400. package/.versions/1.0.2/.pi/harnesses/lib/herdr-client.ts +472 -0
  401. package/.versions/1.0.2/.pi/harnesses/lib/herdr-presence.ts +399 -0
  402. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  403. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  404. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  405. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  406. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  407. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  408. package/.versions/1.0.2/.pi/harnesses/lib/spawned-peers.js +190 -0
  409. package/.versions/1.0.2/.pi/harnesses/package-lock.json +2039 -0
  410. package/.versions/1.0.2/.pi/harnesses/package.json +10 -0
  411. package/.versions/1.0.2/.pi/prompts/af-build.md +24 -0
  412. package/.versions/1.0.2/.pi/prompts/af-code-simplify.md +22 -0
  413. package/.versions/1.0.2/.pi/prompts/af-plan.md +16 -0
  414. package/.versions/1.0.2/.pi/prompts/af-review.md +16 -0
  415. package/.versions/1.0.2/.pi/prompts/af-set-hermes-telegram.md +15 -0
  416. package/.versions/1.0.2/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  417. package/.versions/1.0.2/.pi/prompts/af-ship.md +17 -0
  418. package/.versions/1.0.2/.pi/prompts/af-spec.md +15 -0
  419. package/.versions/1.0.2/.pi/prompts/af-test.md +19 -0
  420. package/.versions/1.0.2/.pi/skills/bowser/SKILL.md +145 -0
  421. package/.versions/1.0.2/.version +1 -0
  422. package/.versions/1.0.2/agents/architect.md +24 -0
  423. package/.versions/1.0.2/agents/bowser.md +27 -0
  424. package/.versions/1.0.2/agents/builder.md +54 -0
  425. package/.versions/1.0.2/agents/code-reviewer.md +208 -0
  426. package/.versions/1.0.2/agents/deep-researcher.md +32 -0
  427. package/.versions/1.0.2/agents/documenter.md +18 -0
  428. package/.versions/1.0.2/agents/orchestrator.md +20 -0
  429. package/.versions/1.0.2/agents/plan-reviewer.md +83 -0
  430. package/.versions/1.0.2/agents/planner.md +70 -0
  431. package/.versions/1.0.2/agents/releaser.md +24 -0
  432. package/.versions/1.0.2/agents/researcher.md +28 -0
  433. package/.versions/1.0.2/agents/security-auditor.md +167 -0
  434. package/.versions/1.0.2/agents/test-engineer.md +153 -0
  435. package/.versions/1.0.2/agents/web-debugger.md +43 -0
  436. package/.versions/1.0.2/agents/web-performance-auditor.md +193 -0
  437. package/.versions/1.0.2/bin/catalog/harness-runtime-closure.json +38 -0
  438. package/.versions/1.0.2/codex/CONDUCTOR.md +148 -0
  439. package/.versions/1.0.2/docs/ARCHITECTURE.md +369 -0
  440. package/.versions/1.0.2/docs/agent-fleet-setup.md +468 -0
  441. package/.versions/1.0.2/docs/claude-code-coms-bridge.md +128 -0
  442. package/.versions/1.0.2/docs/codex-remote-conductor.md +170 -0
  443. package/.versions/1.0.2/docs/coms-hermes-bridge.md +189 -0
  444. package/.versions/1.0.2/docs/getting-started.md +98 -0
  445. package/.versions/1.0.2/docs/npm-install.md +292 -0
  446. package/.versions/1.0.2/docs/pi-extensions.md +439 -0
  447. package/.versions/1.0.2/docs/pi-setup.md +74 -0
  448. package/.versions/1.0.2/docs/skill-anatomy.md +150 -0
  449. package/.versions/1.0.2/hermes/README.md +347 -0
  450. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  451. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  452. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  453. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  454. package/.versions/1.0.2/hermes/gates/gate-o-capability.md +8 -0
  455. package/.versions/1.0.2/hermes/gates/gate-o-validator-fixtures.json +1 -0
  456. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  457. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  458. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  459. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  460. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  461. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  462. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  463. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  464. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  465. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  466. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  467. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  468. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  469. package/.versions/1.0.2/hermes/skills/hub-conductor/SKILL.md +84 -0
  470. package/.versions/1.0.2/hermes/skills/hub-liaison/SKILL.md +84 -0
  471. package/.versions/1.0.2/hermes/skills/hub-watchdog/SKILL.md +76 -0
  472. package/.versions/1.0.2/hermes/skills/hub-watchdog/manifest.json +1 -0
  473. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  474. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  475. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  476. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  477. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  478. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  479. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  480. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  481. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  482. package/.versions/1.0.2/hermes/watchdog-tests/__init__.py +0 -0
  483. package/.versions/1.0.2/hooks/coms-stop-hook.mjs +84 -0
  484. package/.versions/1.0.2/install-manifest.json +2745 -0
  485. package/.versions/1.0.2/justfile +272 -0
  486. package/.versions/1.0.2/manifest-meta.json +882 -0
  487. package/.versions/1.0.2/references/accessibility-checklist.md +160 -0
  488. package/.versions/1.0.2/references/definition-of-done.md +67 -0
  489. package/.versions/1.0.2/references/fleet-coordination-patterns.md +151 -0
  490. package/.versions/1.0.2/references/observability-checklist.md +91 -0
  491. package/.versions/1.0.2/references/orchestration-patterns.md +370 -0
  492. package/.versions/1.0.2/references/performance-checklist.md +153 -0
  493. package/.versions/1.0.2/references/prompting-patterns.md +380 -0
  494. package/.versions/1.0.2/references/security-checklist.md +179 -0
  495. package/.versions/1.0.2/references/testing-patterns.md +236 -0
  496. package/.versions/1.0.2/scripts/codex-conductor.ts +41 -0
  497. package/.versions/1.0.2/scripts/codex-remote-control.ts +167 -0
  498. package/.versions/1.0.2/scripts/coms-claude-bridge.ts +411 -0
  499. package/.versions/1.0.2/scripts/coms-cli.ts +484 -0
  500. package/.versions/1.0.2/scripts/coms-hermes-bridge.ts +413 -0
  501. package/.versions/1.0.2/scripts/fleet.ts +185 -0
  502. package/.versions/1.0.2/scripts/hermes-monitor-capability-runner.ts +25 -0
  503. package/.versions/1.0.2/scripts/hermes-monitor-scenario.ts +474 -0
  504. package/.versions/1.0.2/scripts/hermes-watchdog-capability-probe.ts +45 -0
  505. package/.versions/1.0.2/scripts/install-hermes-plugin.sh +180 -0
  506. package/.versions/1.0.2/scripts/lib/claude-bridge-core.ts +210 -0
  507. package/.versions/1.0.2/scripts/lib/codex-conductor.ts +88 -0
  508. package/.versions/1.0.2/scripts/lib/codex-remote-control.ts +480 -0
  509. package/.versions/1.0.2/scripts/lib/coms-envelope.ts +582 -0
  510. package/.versions/1.0.2/scripts/lib/fake-herdr-server.ts +88 -0
  511. package/.versions/1.0.2/scripts/lib/fleet-command.ts +266 -0
  512. package/.versions/1.0.2/scripts/lib/herdr-layout.ts +281 -0
  513. package/.versions/1.0.2/scripts/lib/hermes-bridge-core.ts +241 -0
  514. package/.versions/1.0.2/scripts/lib/hermes-monitor-events.ts +1 -0
  515. package/.versions/1.0.2/scripts/lib/hermes-monitor-herdr.ts +2 -0
  516. package/.versions/1.0.2/scripts/lib/hermes-monitor-model.ts +3 -0
  517. package/.versions/1.0.2/scripts/lib/hermes-monitor-registry.ts +2 -0
  518. package/.versions/1.0.2/scripts/lib/hermes-monitor-socket.ts +2 -0
  519. package/.versions/1.0.2/scripts/lib/hermes-monitor-store.ts +2 -0
  520. package/.versions/1.0.2/scripts/lib/monitor-env.ts +146 -0
  521. package/.versions/1.0.2/scripts/lib/peer-launch.ts +318 -0
  522. package/.versions/1.0.2/scripts/lib/persona-banner.ts +62 -0
  523. package/.versions/1.0.2/scripts/lib/spawn-stagger.ts +101 -0
  524. package/.versions/1.0.2/scripts/lib/team-project.ts +213 -0
  525. package/.versions/1.0.2/scripts/lib/team-snapshot.ts +147 -0
  526. package/.versions/1.0.2/scripts/peer-banner.ts +40 -0
  527. package/.versions/1.0.2/scripts/peer-launch.ts +259 -0
  528. package/.versions/1.0.2/scripts/team-snapshot.ts +237 -0
  529. package/.versions/1.0.2/scripts/team-up.ts +406 -0
  530. package/.versions/1.0.2/skills/_internal/grilling.md +11 -0
  531. package/.versions/1.0.2/skills/browser-testing-with-devtools/SKILL.md +351 -0
  532. package/.versions/1.0.2/skills/code-review-and-quality/SKILL.md +381 -0
  533. package/.versions/1.0.2/skills/compound-learning/SKILL.md +137 -0
  534. package/.versions/1.0.2/skills/context-engineering/SKILL.md +291 -0
  535. package/.versions/1.0.2/skills/deprecation-and-migration/SKILL.md +206 -0
  536. package/.versions/1.0.2/skills/designing-agents/SKILL.md +394 -0
  537. package/.versions/1.0.2/skills/designing-agents/pi-harness-authoring.md +222 -0
  538. package/.versions/1.0.2/skills/frontend-ui-engineering/SKILL.md +328 -0
  539. package/.versions/1.0.2/skills/git-workflow-and-versioning/SKILL.md +316 -0
  540. package/.versions/1.0.2/skills/idea-refine/SKILL.md +182 -0
  541. package/.versions/1.0.2/skills/idea-refine/examples.md +238 -0
  542. package/.versions/1.0.2/skills/idea-refine/frameworks.md +99 -0
  543. package/.versions/1.0.2/skills/idea-refine/refinement-criteria.md +113 -0
  544. package/.versions/1.0.2/skills/idea-refine/scripts/idea-refine.sh +15 -0
  545. package/.versions/1.0.2/skills/incremental-implementation/SKILL.md +287 -0
  546. package/.versions/1.0.2/skills/interview-me/SKILL.md +226 -0
  547. package/.versions/1.0.2/skills/orchestration-verification/SKILL.md +181 -0
  548. package/.versions/1.0.2/skills/peer-coms/SKILL.md +90 -0
  549. package/.versions/1.0.2/skills/performance-optimization/SKILL.md +350 -0
  550. package/.versions/1.0.2/skills/planning-and-task-breakdown/SKILL.md +254 -0
  551. package/.versions/1.0.2/skills/security-and-hardening/SKILL.md +461 -0
  552. package/.versions/1.0.2/skills/spec-driven-development/SKILL.md +257 -0
  553. package/.versions/1.0.2/skills/using-agent-skills/SKILL.md +199 -0
  554. package/.versions/1.0.2/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  555. package/.versions/1.0.2/vendor/agent-skills-upstream/LICENSE +21 -0
  556. package/.versions/1.0.2/vendor/agent-skills-upstream/README.md +11 -0
  557. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  558. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  559. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  560. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  561. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  562. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  563. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  564. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  565. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  566. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  567. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  568. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  569. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  570. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  571. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  572. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  573. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  574. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  575. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  576. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  577. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  578. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  579. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  580. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  581. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  582. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  583. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  584. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  585. package/CHANGELOG.md +15 -0
  586. package/README.md +4 -2
  587. package/agents/code-reviewer.md +1 -1
  588. package/agents/deep-researcher.md +1 -1
  589. package/agents/orchestrator.md +4 -56
  590. package/agents/plan-reviewer.md +1 -1
  591. package/agents/planner.md +1 -1
  592. package/agents/security-auditor.md +1 -1
  593. package/agents/test-engineer.md +1 -1
  594. package/docs/ARCHITECTURE.md +48 -16
  595. package/docs/agent-fleet-setup.md +33 -2
  596. package/docs/pi-extensions.md +29 -2
  597. package/install-manifest.json +2 -2
  598. package/package.json +2 -2
@@ -17,6 +17,7 @@
17
17
  * /af-agents-team — switch active team
18
18
  * /af-agents-list — open the Fleet Dashboard
19
19
  * /af-agents-history — timeline of agent execution (durations + grand total)
20
+ * /af-context — read-only full-screen context budget diagnostic
20
21
  * /af-agent-model <persona>[.<role>] — switch a team or research persona's (or
21
22
  * delegate sub-role's) model from its declared candidates
22
23
  * /af-agent-model-thinking <persona> — switch a team or research persona's thinking
@@ -62,7 +63,7 @@
62
63
  * Direct guarded launch: pi -e .pi/harnesses/damage-control-continue/index.ts -e .pi/harnesses/agent-hub/index.ts
63
64
  */
64
65
 
65
- import type { ExtensionAPI, ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
66
+ import type { ExtensionAPI, ExtensionContext, ImageContent, Theme } from "@mariozechner/pi-coding-agent";
66
67
  import { DynamicBorder, getMarkdownTheme as getPiMdTheme, copyToClipboard } from "@mariozechner/pi-coding-agent";
67
68
  import { Type } from "@sinclair/typebox";
68
69
  import {
@@ -88,8 +89,9 @@ import {
88
89
  AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
89
90
  exemptionsFilePath, type AccessRequest,
90
91
  } from "../lib/damage-control-shared.ts";
91
- import { applyModelOverride, clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, resolveStartupRoster, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
92
- import { DEFAULT_HUB_MODE, DEFAULT_TASK_TIER, HUB_MODES, TASK_BUDGET_MULTIPLIER, applyTierChange, blockingFindingCap, budgetStatusLine, checkReviewRoundCap, checkTaskBudget, checkTierPersonaGate, checkTurnBudget, contextOverflowDiagnostic, isReviewPersona, normalizeHubMode, remainingTaskResearch, resolveTaskBudget, resolveTurnBudget, reviewBudgetClause, reviewRoundCap, shouldRecycleSession, turnActiveMs } from "./run-budget.js";
92
+ import { applyModelOverride, clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
93
+ import { DEFAULT_HUB_MODE, DEFAULT_TASK_TIER, HUB_MODES, TASK_BUDGET_MULTIPLIER, addTaskClockWait, applyTierChange, blockingFindingCap, budgetStatusLine, checkReviewRoundCap, checkTaskBudget, checkTierPersonaGate, checkTurnBudget, closeTaskClock, contextOverflowDiagnostic, createTaskClock, isReviewPersona, normalizeHubMode, openTaskClock, remainingTaskResearch, resetTaskClock, resolveTaskBudget, resolveTurnBudget, reviewBudgetClause, reviewRoundCap, shouldRecycleSession, taskClockElapsedMs } from "./run-budget.js";
94
+ import { buildBudgetContinuationAudit, buildHubAuditIdentity, buildHubModeAudit, buildTaskResetAudit } from "./hub-state-audit.js";
93
95
  import { countReviewFindings, findingBudgetNotice } from "./review-findings.js";
94
96
  import { checkDocsLane, docsLaneNotice } from "./docs-lane.js";
95
97
  import { checkExternalBlockerGate, externalBlockedProtocol, extractExternalBlockers } from "./external-blocker.js";
@@ -114,7 +116,12 @@ import { crossCheck, deliveryDisposition, extractAssertionIds, parseDeliveredRet
114
116
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
115
117
  import { validateEvidence } from "./evidence-rules.js";
116
118
  import { comsRequiredRefusal, explicitComsRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
117
- import { parsePosture, posturePrompt, resolvePostureTools, resolveSessionPosture, type Posture } from "./posture.ts";
119
+ import { NATIVE_ROSTER_ENTRY_TYPE, parsePosture, persistedNativeRosterState, posturePrompt, resolvePostureTools, resolveSessionPosture, resolveSessionRoster, type Posture } from "./posture.ts";
120
+ import { CAPABILITY_PACKS, latestPersistedCapabilityState, persistedCapabilityState, resolveCapabilityPacks, type CapabilityPack, type CapabilityResolution, type ContextState, type PendingOperation } from "./capability-packs.ts";
121
+ import { contextPressureDiagnostic, createContextPressureState, transitionContextPressure, type ContextPressureState } from "./context-pressure.ts";
122
+ import { confirmationGate, confirmationOutcome, capabilityConfirmationPack, capabilityConfirmationQuestion, type CapabilityConfirmationState, type ConfirmableCapabilityPack } from "./capability-confirmation.ts";
123
+ import { budgetContinuationInstruction, budgetContinuationKind, budgetContinuationOutcome, turnBudgetActiveMs, type BudgetContinuationKind } from "./budget-continuation.ts";
124
+ import { observeAskUserResults } from "../ask-user-remote/index.ts";
118
125
  import { buildHubPeerSpawnPlan, launchHubPeerInPane } from "./peer-spawn-plan.ts";
119
126
  import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
120
127
  import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
@@ -133,10 +140,23 @@ import { buildLiveRegistryEntry, type ComsRegistryEntry } from "../lib/coms-regi
133
140
  import { FULLSCREEN_OVERLAY, bodyRows, clampScroll, fitToHeight } from "../lib/fleet-overlay.ts";
134
141
  import { createPanelResources } from "../lib/fleet-panel.ts";
135
142
  import { buildFleetRows, fleetTiming, summarise, unionMs, type DelegateInput, type FleetRow, type FleetSource, type PeerInput, type ResearchInput, type SpecialistInput } from "../lib/fleet-read-model.ts";
136
- import { attachFleetDashboardTicker, compactWidgetsEnabled, liveTimeline, resolveFleetKill, resolveFleetRestart } from "../lib/fleet-dashboard-ops.ts";
143
+ import { attachFleetDashboardTicker, compactWidgetsEnabled, gridColumnsForItems, gridColumnsForSize, liveTimeline, renderCardGrid, resolveFleetKill, resolveFleetRestart } from "../lib/fleet-dashboard-ops.ts";
137
144
  import { dashboardTransition, renderFleetDashboard, FLEET_CHROME_ROWS, type DashboardConfirm } from "../lib/fleet-dashboard-view.ts";
138
- import { detailContent, detailTransition, renderFleetDetail, DETAIL_CHROME_ROWS } from "../lib/fleet-detail-view.ts";
145
+ import { detailContent, detailTransition, fleetModelChoices, modelPickerTransition, normalizeFleetDetailInput, renderFleetDetail, renderFleetModelPicker, DETAIL_CHROME_ROWS, type FleetDetailKey, type FleetModelChoice } from "../lib/fleet-detail-view.ts";
139
146
  import { reconcileSelection, type Selection } from "../lib/fleet-selection.ts";
147
+ import { collectContextBudgetSnapshot, type LivePlane } from "./context-budget-snapshot.ts";
148
+ import { CONTEXT_BUDGET_CHROME_ROWS, contextBudgetTransition, renderContextBudget, type ContextBudgetViewState } from "../lib/context-budget-view.ts";
149
+ import { component, safeSchemaChars, type ContextBudgetComponent } from "../lib/context-budget.ts";
150
+ import { assembleHubSystemPrompt, HUB_HERDR_SECTION, namedHubLedgerParts, recordHubLedger } from "../lib/context-budget-hub-prompt.ts";
151
+ import {
152
+ delegateStandingParts,
153
+ buildSpecialistContextManifest,
154
+ nativeResearchSystemPrompt,
155
+ nativeSpecialistSystemPrompt,
156
+ researchStandingParts,
157
+ type SpecialistContextManifest,
158
+ specialistStandingParts,
159
+ } from "../lib/context-budget-child-prompt.ts";
140
160
  import { parseEnvFile, resolveEnvFilePath } from "../../../scripts/lib/herdr-layout.ts";
141
161
  import { worktreeTag } from "../../../scripts/lib/team-project.ts";
142
162
  import { STAGGER_ENV_VAR, WARMUP_SECONDS, oauthNeedsWarmup } from "../../../scripts/lib/spawn-stagger.ts";
@@ -237,6 +257,8 @@ interface AgentState {
237
257
  // a percentage cannot be compared against a window it was not divided by.
238
258
  contextTokens: number;
239
259
  sessionFile: string | null;
260
+ /** Metadata-only child context retained across research-pause resume. */
261
+ specialistManifest?: SpecialistContextManifest;
240
262
  runCount: number;
241
263
  // Runs served by the CURRENT accumulated session (-c resume chain). Reset on
242
264
  // recycle; drives shouldRecycleSession together with the measured contextPct.
@@ -297,6 +319,7 @@ interface ResearchState {
297
319
  elapsed: number;
298
320
  lastWork: string;
299
321
  contextPct: number;
322
+ contextTokens: number;
300
323
  sessionFile: string | null; // set after a successful run → enables `-c` resume
301
324
  turnCount: number;
302
325
  finishedAt?: number; // last time a run ended (any status) — LRU key for retention
@@ -428,7 +451,7 @@ function extractNeedsResearch(output: string): string[] {
428
451
  // max-dispatches-per-turn: <n>|off — dispatch_agent calls allowed per user turn
429
452
  // (replaces the mode default; "off" = unlimited).
430
453
  // max-research-per-turn: <n>|off — spawn_research calls allowed per user turn.
431
- // turn-wall-time-s: <n>|off — wall-clock budget per user turn.
454
+ // turn-wall-time-s: <n>|off — active-time budget per user turn (ask_user waits excluded).
432
455
  // agent-turn-timeout-s: <n>|off — whole-run deadline for each spawned
433
456
  // specialist/research/delegate run (not per tool).
434
457
  // session-recycle-runs: <n>|off — recycle a specialist's accumulated session
@@ -458,6 +481,7 @@ interface AgentTeamOverrides {
458
481
  researchKeep: number;
459
482
  reconSearchTimeoutMs: number | null;
460
483
  hubMode: string;
484
+ hubModeSource: "default" | "project-override";
461
485
  // Per-axis turn-budget overrides for run-budget.js resolveTurnBudget():
462
486
  // number replaces the mode default, null = "off", undefined = keep default.
463
487
  budgetOverrides: {
@@ -488,6 +512,7 @@ const DEFAULT_OVERRIDES: AgentTeamOverrides = {
488
512
  researchKeep: DEFAULT_RESEARCH_KEEP,
489
513
  reconSearchTimeoutMs: 120_000,
490
514
  hubMode: DEFAULT_HUB_MODE,
515
+ hubModeSource: "default",
491
516
  budgetOverrides: {},
492
517
  watchdogSetting: DEFAULT_WATCHDOG_SETTING,
493
518
  watchdogJudgeModel: null,
@@ -573,6 +598,7 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
573
598
  const mode = normalizeHubMode(value);
574
599
  if (mode) {
575
600
  result.hubMode = mode;
601
+ result.hubModeSource = "project-override";
576
602
  } else {
577
603
  result.warnings.push(`mode "${value}" is not one of ${HUB_MODES.join("|")} — using the default (${DEFAULT_HUB_MODE})`);
578
604
  }
@@ -869,18 +895,6 @@ const CONTEXT_WARN_THRESHOLD = 70;
869
895
  // child spawns reserved tree-wide for a dispatch.
870
896
  const DELEGATE_CALL_BUDGET = DELEGATE_TREE_SPAWN_BUDGET;
871
897
 
872
- // Appended to every research helper's system prompt so it knows its sandbox and how to
873
- // report. Kept separate from the dispatcher's clarification protocol: helpers don't
874
- // bubble up ASK_USER — they report findings and the dispatcher decides what to do.
875
- const RESEARCH_PROTOCOL = `
876
-
877
- ## You are a READ-ONLY research helper
878
- You can ONLY read, search, and list files (tools: read, grep, find, ls). You CANNOT
879
- edit, write, or run shell/bash commands — they are not available to you. Investigate
880
- what you're asked, then report findings concisely, citing concrete locations as
881
- path:line. Do not propose or attempt edits; another agent will act on your findings.
882
- If something can't be found or is ambiguous, say so plainly rather than guessing.`;
883
-
884
898
  // System prompt for an ad-hoc (anonymous) research helper — one with no persona file.
885
899
  const ANON_RESEARCH_PROMPT = `# Research Helper
886
900
 
@@ -1850,6 +1864,8 @@ export default function (pi: ExtensionAPI) {
1850
1864
  // Read-only research helpers (Phase 4), keyed by numeric id (handle `rN`). Lives
1851
1865
  // alongside the standing team but renders in its own widget row.
1852
1866
  const researchStates: Map<number, ResearchState> = new Map();
1867
+ // Metadata only: prompt text is never retained by this ledger.
1868
+ let lastHubLedger: ContextBudgetComponent[] = [];
1853
1869
  let nextResearchId = 1;
1854
1870
  // Retention cap for finished durable (manual/persona) helpers — set from the
1855
1871
  // overrides file's `research-keep:` key at session start (default 4, Infinity
@@ -2059,6 +2075,12 @@ than bulk-reading doc trees; when an entry point is a folder, start from its REA
2059
2075
  or index file. If your work changes something the docs describe (architecture, public
2060
2076
  APIs, commands, structure), say so in your final response so the docs can be updated.`;
2061
2077
  }
2078
+
2079
+ /** One canonical repository context file plus explicitly configured rule roots. */
2080
+ function specialistProjectPolicyPaths(cwd: string): string[] {
2081
+ const canonical = ["AGENTS.md", "CLAUDE.md"].find(candidate => existsSync(path.join(cwd, candidate)));
2082
+ return [...new Set([...(canonical ? [canonical] : []), ...projectRulesDirs])];
2083
+ }
2062
2084
  // The one supported safety harness. Every native specialist, researcher, and
2063
2085
  // nested delegate receives it; a missing harness refuses child dispatch.
2064
2086
  let safetyHarnessPath: string | null = null;
@@ -2071,18 +2093,27 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2071
2093
  // ── Execution mode & per-turn budgets (run-budget.js) ──
2072
2094
  // hubMode: overrides-file default, switchable live via /af-hub-mode (session-
2073
2095
  // lifetime). Budgets are per USER TURN: counters reset in before_agent_start,
2074
- // so exhaustion means "stop, summarize, ask" and the next user message opens
2075
- // a fresh window. currentTurnStartedAt (above) doubles as the wall-clock base.
2096
+ // or after an explicit one-click continuation. currentTurnStartedAt (above)
2097
+ // is the active-time base; ask_user waits are subtracted.
2076
2098
  let hubMode: string = DEFAULT_HUB_MODE;
2077
2099
  let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
2078
2100
  let turnDispatchCount = 0;
2079
2101
  let turnResearchCount = 0;
2102
+ // Human wait time is not fleet work. Track it separately from history UI
2103
+ // intervals so a continuation can rebase the budget without erasing history.
2104
+ let turnBudgetAskUserWaitMs = 0;
2105
+ type PendingBudgetContinuation = { kind: BudgetContinuationKind; reason: string };
2106
+ let pendingBudgetContinuation: PendingBudgetContinuation | null = null;
2107
+ const budgetContinuationAsks = new Map<string, { kind: BudgetContinuationKind; reason: string; params: { context?: unknown; options?: unknown } }>();
2108
+ let taskContinuationCount = 0;
2109
+ let turnContinuationCount = 0;
2080
2110
  // ── Task-scoped budget & tier (run-budget.js) ──
2081
2111
  // A per-message allowance cannot bound a task: every steering message opened a
2082
2112
  // fresh turn window, so a run could spend 8 dispatches and 60 minutes again and
2083
2113
  // again without any counter ever binding. These counters span the whole TASK
2084
- // and are cleared only by an explicit new task (/af-new-task or
2085
- // set_task_tier `new_task: true`) — not by a user message.
2114
+ // and are cleared only by an explicit new task (`set_task_tier` with
2115
+ // `new_task: true`) or an approved task-budget continuation — never by an
2116
+ // ordinary user message.
2086
2117
  let taskDispatchCount = 0;
2087
2118
  let taskResearchCount = 0;
2088
2119
  let taskLabel: string | null = null;
@@ -2092,9 +2123,9 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2092
2123
  // at fast mode's 45-minute envelope that hard-stops a task with two dispatches
2093
2124
  // spent. A false stop is worse than no stop: it teaches people to reset the
2094
2125
  // task window reflexively, which is the one thing that must stay deliberate.
2095
- // `taskActiveMs` accumulates finished turns; the open turn is added at check time.
2096
- let taskActiveMs = 0;
2097
- let turnAskUserWaitMs = 0;
2126
+ // The explicit clock state makes `active` authoritative: a stale timestamp can
2127
+ // never turn inter-turn idle time into task work.
2128
+ let taskClock = createTaskClock();
2098
2129
  // Review dispatches spent on this task (review-round cap).
2099
2130
  let taskReviewRounds = 0;
2100
2131
  // Task tier (complexity triage): declared by the dispatcher via set_task_tier.
@@ -2140,34 +2171,135 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2140
2171
  * minus its ask_user waits. An ask_user still in flight is subtracted too, so
2141
2172
  * the clock does not tick while the dispatcher sits at a question.
2142
2173
  */
2143
- function taskActiveElapsedMs(): number {
2174
+ function taskActiveElapsedMs(now = Date.now()): number {
2144
2175
  let openWait = 0;
2145
- const now = Date.now();
2146
2176
  for (const startedAt of askUserStarts.values()) openWait += Math.max(0, now - startedAt);
2147
- return taskActiveMs + turnActiveMs(currentTurnStartedAt, now, turnAskUserWaitMs + openWait);
2177
+ return taskClockElapsedMs(taskClock, now, openWait);
2178
+ }
2179
+ function turnBudgetActiveElapsedMs(now = Date.now()): number {
2180
+ let openWait = 0;
2181
+ for (const startedAt of askUserStarts.values()) openWait += Math.max(0, now - startedAt);
2182
+ return turnBudgetActiveMs(currentTurnStartedAt, now, turnBudgetAskUserWaitMs, openWait);
2183
+ }
2184
+ function armBudgetContinuation(kind: BudgetContinuationKind, reason: string): void {
2185
+ pendingBudgetContinuation = { kind, reason };
2186
+ }
2187
+ /** Renew only the per-turn envelope; the task identity and outer counters stay intact. */
2188
+ function renewTurnBudgetWindow(now = Date.now()): void {
2189
+ turnDispatchCount = 0;
2190
+ turnResearchCount = 0;
2191
+ currentTurnStartedAt = now;
2192
+ turnBudgetAskUserWaitMs = 0;
2193
+ turnDispatchFingerprints.clear();
2194
+ turnContinuationCount++;
2195
+ updateModeStatus();
2196
+ }
2197
+ /** Add one task tranche while preserving tier, assertions, packs, blockers, and label. */
2198
+ function continueTaskBudgetWindow(now = Date.now()): void {
2199
+ taskDispatchCount = 0;
2200
+ taskResearchCount = 0;
2201
+ taskClock = resetTaskClock(taskClock, now);
2202
+ taskReviewRounds = 0;
2203
+ taskContinuationCount++;
2204
+ renewTurnBudgetWindow(now);
2148
2205
  }
2149
2206
  /** Fold the turn that is ending into the task's active-time accumulator. */
2150
- function closeTurnActiveTime() {
2151
- if (!currentTurnStartedAt) return;
2152
- taskActiveMs += turnActiveMs(currentTurnStartedAt, Date.now(), turnAskUserWaitMs);
2153
- turnAskUserWaitMs = 0;
2207
+ function closeTurnActiveTime(now = Date.now()) {
2208
+ taskClock = closeTaskClock(taskClock, now);
2154
2209
  }
2155
2210
  /** Clear the task window: counters, tier, clock, review rounds, blocker breaker. */
2156
- function resetTaskWindow(label: string | null = null) {
2211
+ function resetTaskWindow(label: string | null = null, now = Date.now()) {
2157
2212
  taskDispatchCount = 0;
2158
2213
  taskResearchCount = 0;
2159
- taskActiveMs = 0;
2160
- turnAskUserWaitMs = 0;
2214
+ taskClock = resetTaskClock(taskClock, now);
2161
2215
  taskReviewRounds = 0;
2216
+ taskContinuationCount = 0;
2217
+ pendingBudgetContinuation = null;
2218
+ budgetContinuationAsks.clear();
2162
2219
  taskLabel = label;
2163
2220
  taskTier = null;
2164
2221
  taskTierAssumed = false;
2222
+ taskCapabilityPacks = [];
2223
+ taskProvisionalPacks = [];
2224
+ capabilityConfirmation = {};
2165
2225
  externalBlockers = [];
2166
2226
  externalBlockerAcknowledged = false;
2167
2227
  externalBlockerRefusedOnce = false;
2168
2228
  turnDispatchFingerprints.clear();
2229
+ resolveIncomingCapabilities("", true);
2230
+ applyPostureTools();
2169
2231
  updateModeStatus();
2170
2232
  }
2233
+ function hubAuditIdentity(ctx?: ExtensionContext) {
2234
+ return buildHubAuditIdentity({
2235
+ cwd: ctx?.cwd ?? identity?.cwd ?? currentCtx?.cwd ?? process.cwd(),
2236
+ pid: process.pid,
2237
+ sessionId: identity?.session_id,
2238
+ project: identity?.project,
2239
+ workspaceId: process.env.HERDR_WORKSPACE_ID,
2240
+ paneId: process.env.HERDR_PANE_ID,
2241
+ });
2242
+ }
2243
+ function hubLocationSuffix(ctx?: ExtensionContext): string {
2244
+ const where = hubAuditIdentity(ctx);
2245
+ return `\nRepository: ${where.cwd ?? "unknown"}${where.herdr_pane_id ? ` · pane ${where.herdr_pane_id}` : ""}`;
2246
+ }
2247
+ function appendHubModeEntry(input: {
2248
+ previousMode: string;
2249
+ mode: string;
2250
+ source: "slash-command" | "project-override" | "default";
2251
+ overrideFile?: string | null;
2252
+ ctx?: ExtensionContext;
2253
+ }) {
2254
+ try {
2255
+ pi.appendEntry("agent-hub-mode", buildHubModeAudit({
2256
+ ...input,
2257
+ taskTier,
2258
+ turnDispatches: turnDispatchCount,
2259
+ turnResearch: turnResearchCount,
2260
+ identity: hubAuditIdentity(input.ctx),
2261
+ }));
2262
+ } catch { /* diagnostics are best-effort; state changes still succeed */ }
2263
+ }
2264
+ function taskResetSnapshot(now = Date.now()) {
2265
+ return {
2266
+ tier: taskTier,
2267
+ dispatches: taskDispatchCount,
2268
+ research: taskResearchCount,
2269
+ reviewRounds: taskReviewRounds,
2270
+ activeMs: taskActiveElapsedMs(now),
2271
+ };
2272
+ }
2273
+ function budgetContinuationSnapshot(kind: BudgetContinuationKind, now = Date.now()) {
2274
+ return kind === "task" ? taskResetSnapshot(now) : {
2275
+ tier: taskTier,
2276
+ dispatches: turnDispatchCount,
2277
+ research: turnResearchCount,
2278
+ reviewRounds: 0,
2279
+ activeMs: turnBudgetActiveElapsedMs(now),
2280
+ };
2281
+ }
2282
+ function appendTaskResetEntry(source: "tool:set_task_tier", label: string | null, prior: ReturnType<typeof taskResetSnapshot>, ctx?: ExtensionContext) {
2283
+ try {
2284
+ pi.appendEntry("agent-hub-task-reset", buildTaskResetAudit({
2285
+ source,
2286
+ label,
2287
+ prior,
2288
+ identity: hubAuditIdentity(ctx),
2289
+ }));
2290
+ } catch { /* diagnostics are best-effort; state changes still succeed */ }
2291
+ }
2292
+ function appendBudgetContinuationEntry(kind: BudgetContinuationKind, reason: string, prior: ReturnType<typeof taskResetSnapshot>, ctx?: ExtensionContext) {
2293
+ try {
2294
+ pi.appendEntry("agent-hub-budget-continuation", buildBudgetContinuationAudit({
2295
+ kind,
2296
+ continuation: kind === "task" ? taskContinuationCount : turnContinuationCount,
2297
+ reason,
2298
+ prior,
2299
+ identity: hubAuditIdentity(ctx),
2300
+ }));
2301
+ } catch { /* diagnostics are best-effort; state changes still succeed */ }
2302
+ }
2171
2303
  function updateModeStatus() {
2172
2304
  try {
2173
2305
  widgetCtx?.ui?.setStatus(
@@ -2665,8 +2797,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2665
2797
 
2666
2798
  // Auto-size grid columns based on team size
2667
2799
  function recomputeGrid() {
2668
- const size = agentStates.size;
2669
- gridCols = size <= 3 ? size : size === 4 ? 2 : 3;
2800
+ gridCols = gridColumnsForSize(agentStates.size);
2670
2801
  }
2671
2802
 
2672
2803
  function activateTeam(teamName: string) {
@@ -2684,6 +2815,11 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2684
2815
  recomputeGrid();
2685
2816
  }
2686
2817
 
2818
+ function persistActiveRoster(): void {
2819
+ if (!activeTeamName || agentStates.size === 0) return;
2820
+ pi.appendEntry(NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState(activeTeamName));
2821
+ }
2822
+
2687
2823
  // ── Dynamic roster (add/drop/save; /af-agents-add, /af-agents-drop, team_adjust) ──
2688
2824
  // The system prompt is rebuilt every turn from agentStates, so a roster
2689
2825
  // change takes effect on the dispatcher's next turn with no restart.
@@ -2975,28 +3111,19 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2975
3111
  // into the belowEditor "agent-running" widget instead.
2976
3112
  if (!compactWidgetsEnabled(viewMode)) return [];
2977
3113
 
2978
- const cols = Math.min(gridCols, states.length);
3114
+ const cols = gridColumnsForItems(gridCols, states.length);
2979
3115
  const gap = 1;
2980
3116
  const colWidth = Math.floor((width - gap * (cols - 1)) / cols);
2981
3117
  const labelText = "── research ";
2982
3118
  const header = theme.fg("dim", labelText + "─".repeat(Math.max(0, width - labelText.length)));
2983
- const rows: string[][] = [];
2984
-
2985
- for (let i = 0; i < states.length; i += cols) {
2986
- const rowStates = states.slice(i, i + cols);
2987
- const cards = rowStates.map(s => renderResearchCard(s, colWidth, theme));
2988
-
2989
- while (cards.length < cols) {
2990
- cards.push(Array(CARD_HEIGHT).fill(" ".repeat(Math.max(0, colWidth))));
2991
- }
2992
-
2993
- const cardHeight = cards[0].length;
2994
- for (let line = 0; line < cardHeight; line++) {
2995
- rows.push(cards.map(card => card[line] || ""));
2996
- }
2997
- }
2998
-
2999
- const grid = rows.map(cs => cs.join(" ".repeat(gap)));
3119
+ const grid = renderCardGrid(
3120
+ states,
3121
+ cols,
3122
+ CARD_HEIGHT,
3123
+ s => renderResearchCard(s, colWidth, theme),
3124
+ " ".repeat(gap),
3125
+ " ".repeat(Math.max(0, colWidth)),
3126
+ );
3000
3127
  text.setText([header, ...grid].join("\n"));
3001
3128
  return text.render(width);
3002
3129
  },
@@ -3438,6 +3565,7 @@ ${externalBlockedProtocol()}
3438
3565
  scopeGlobs: string[] = [],
3439
3566
  watchdogParam?: boolean,
3440
3567
  requestedBackend: "auto" | "native" | "coms" = "auto",
3568
+ preserveManifest = false,
3441
3569
  ): Promise<{
3442
3570
  output: string;
3443
3571
  exitCode: number;
@@ -3646,44 +3774,6 @@ ${externalBlockedProtocol()}
3646
3774
  }
3647
3775
  }
3648
3776
 
3649
- // Clarification protocol — every specialist learns to bubble up questions
3650
- // to the dispatcher instead of guessing.
3651
- const clarificationProtocol = `
3652
-
3653
- ## Clarification protocol
3654
- If at any point you need a decision from the human user (ambiguity, missing input,
3655
- contradiction, or a destructive/irreversible next step), DO NOT guess. Stop and
3656
- return a single line of the form:
3657
-
3658
- ASK_USER: <your question in one clear English sentence>
3659
-
3660
- You may emit multiple ASK_USER lines if you have several questions. The dispatcher
3661
- will surface each to the human user in ${userLanguage} and re-dispatch you with the
3662
- answers. Do not invent values, do not pick "reasonable defaults" silently — ask.
3663
-
3664
- ## External-blocker protocol
3665
- ${externalBlockedProtocol()}
3666
-
3667
- ## Research protocol
3668
- If you need reconnaissance you cannot perform with your own tools (broad code search,
3669
- reading unfamiliar areas of the codebase, summarizing docs), DO NOT guess and DO NOT
3670
- ask the user. Pause for research instead: end your turn with one or more lines of the
3671
- form
3672
-
3673
- NEEDS_RESEARCH: <one specific, self-contained question>
3674
-
3675
- with nothing after them. Your session pauses there; read-only research helpers are
3676
- spawned for you, each helper's findings are saved to a file, and you are resumed in
3677
- this same session with the file paths — read them and continue from where you left
3678
- off. Ask at most ${MAX_AUTO_RESEARCH_QUESTIONS} questions per pause. Use ASK_USER only
3679
- for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked up.`;
3680
-
3681
- // Project rules and docs — when the overrides file lists rule folders or
3682
- // doc entry points, every specialist learns where they are and how to
3683
- // resolve them (rules index-first, docs as orientation entry points).
3684
- const rulesProtocol = buildRulesProtocol();
3685
- const docsProtocol = buildDocsProtocol();
3686
-
3687
3777
  // Mid-turn delegation: a persona that declares `subagents:` gets the
3688
3778
  // delegate extension injected (`-e delegate.ts`), the `delegate` tool
3689
3779
  // added to its allowlist (pi filters extension tools too), and its
@@ -3706,7 +3796,6 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3706
3796
  const extensions = [...safety.extensions];
3707
3797
  let effectiveTools = state.def.tools;
3708
3798
  let delegateEnv: Record<string, string> | undefined;
3709
- let delegationProtocol = "";
3710
3799
  if (delegationActive) {
3711
3800
  const delegationDir = safePathWithin(sessionDir, "delegations", agentKey);
3712
3801
  try { rmSync(delegationDir, { recursive: true, force: true }); } catch {}
@@ -3731,25 +3820,25 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3731
3820
  cwd: ctx.cwd || process.cwd(),
3732
3821
  }),
3733
3822
  };
3734
- delegationProtocol = `
3735
-
3736
- ## Delegation protocol
3737
- You have a \`delegate\` tool with pre-configured sub-agents on cheaper models
3738
- (roles: ${Object.keys(subagentRoles!).join(", ")}). Prefer delegating scoped, self-contained
3739
- sub-tasks to them over doing everything yourself. A child shares NONE of your
3740
- context — put everything it needs into its instruction/context. You may run up
3741
- to ${DELEGATE_TREE_SPAWN_BUDGET} delegate calls for this dispatch; parallel children are forced read-only.
3742
- Children are terminal workers: they do not receive delegate tooling at remaining depth 0.`;
3743
3823
  startDelegationWatch(state, delegationDir);
3744
3824
  }
3745
3825
 
3746
- const deliverableProtocol = `
3747
-
3748
- ## Deliverable-to-file protocol
3749
- When your deliverable is a document (plan, review, critique, inventory, report), write the full document to the real session artifact path when your tools allow it: .pi/agent-sessions/artifacts/<kind>/${agentKey}-run${runNumber}.md (kinds: plans, reviews, inventories, evidence). Do NOT write repo-root ./artifacts/... files. In your final response, report and pass the artifact-relative handoff path: artifacts/<kind>/${agentKey}-run${runNumber}.md. If your persona already has an explicit output path contract such as planner PLAN_FILE, keep that existing behavior and also summarize/return the session artifact path the hub gives you.
3750
- Finish with the artifact-relative path plus a digest of no more than 10 lines. If the dispatch includes acceptance assertions (A1, A2, ...), also include the structured return from skills/orchestration-verification/SKILL.md. If your tools are read-only and you cannot write a document artifact yourself, finish with the digest + structured return; the hub will still persist your full final return under artifacts/returns/ for dispatcher recovery.`;
3751
-
3752
- const appendedSystemPrompt = state.def.systemPrompt + clarificationProtocol + rulesProtocol + docsProtocol + delegationProtocol + deliverableProtocol;
3826
+ const manifest = preserveManifest && state.specialistManifest
3827
+ ? state.specialistManifest
3828
+ : buildSpecialistContextManifest({
3829
+ personaName: state.def.name,
3830
+ personaPath: state.def.file,
3831
+ personaPrompt: state.def.systemPrompt,
3832
+ task,
3833
+ rulesPaths: specialistProjectPolicyPaths(ctx.cwd || process.cwd()),
3834
+ docsPaths: projectDocsPaths,
3835
+ hasAssertions: extractAssertionIds(task).length > 0,
3836
+ hasScope: scopeGlobs.length > 0,
3837
+ hasArtifacts: inputArtifacts.length > 0,
3838
+ delegateRoles: delegationActive ? Object.keys(subagentRoles!) : [],
3839
+ });
3840
+ state.specialistManifest = manifest;
3841
+ const replacementSystemPrompt = nativeSpecialistSystemPrompt({ manifest, userLanguage, agentKey, runNumber });
3753
3842
 
3754
3843
  // Per-agent thinking: the persona's `thinking:` frontmatter (or a
3755
3844
  // /af-agent-model-thinking session override) sets the pi --thinking reasoning
@@ -3810,7 +3899,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3810
3899
  if (state.sessionFile && !sessionRecycled) {
3811
3900
  const overflow = shouldRecycleBeforeSpawn({
3812
3901
  priorTokens: state.contextTokens,
3813
- promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(appendedSystemPrompt),
3902
+ promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(replacementSystemPrompt),
3814
3903
  window: agentWindow.window,
3815
3904
  });
3816
3905
  if (overflow) {
@@ -3834,10 +3923,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3834
3923
  model,
3835
3924
  tools: effectiveTools,
3836
3925
  thinking: thinkingLevel,
3837
- appendSystemPrompt: appendedSystemPrompt,
3926
+ systemPrompt: replacementSystemPrompt,
3927
+ noSkills: true,
3928
+ noContextFiles: true,
3838
3929
  sessionFile: agentSessionFile,
3839
3930
  resume: !!state.sessionFile,
3840
3931
  prompt: runPrompt,
3932
+ cwd: ctx.cwd || process.cwd(),
3841
3933
  extensions,
3842
3934
  env: { ...guardrailEnv(agentKey), ...(delegateEnv || {}) },
3843
3935
  detached: true,
@@ -4169,6 +4261,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4169
4261
  elapsed: 0,
4170
4262
  lastWork: "",
4171
4263
  contextPct: 0,
4264
+ contextTokens: 0,
4172
4265
  sessionFile: null,
4173
4266
  turnCount: 1,
4174
4267
  timeline: [],
@@ -4248,13 +4341,18 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4248
4341
  model: state.model,
4249
4342
  tools: RESEARCH_TOOLS,
4250
4343
  thinking: thinkingLevel,
4251
- // Research helpers get the docs orientation block (WHAT/WHY entry
4252
- // points) but not the rules block — rules govern producing/validating
4253
- // changes, which read-only research does not do.
4254
- appendSystemPrompt: state.def.systemPrompt + RESEARCH_PROTOCOL + buildDocsProtocol(),
4344
+ // Replacement policy avoids inherited skills and project context files.
4345
+ // The selected persona remains available by its explicit source path.
4346
+ systemPrompt: nativeResearchSystemPrompt({
4347
+ ...(state.persona ? { personaName: state.def.name, personaPath: state.def.file } : {}),
4348
+ cwd: ctx.cwd || process.cwd(),
4349
+ }),
4350
+ noSkills: true,
4351
+ noContextFiles: true,
4255
4352
  sessionFile: sessionPath,
4256
4353
  resume: !!state.sessionFile,
4257
4354
  prompt: appendInputArtifacts(prompt, inputArtifacts),
4355
+ cwd: ctx.cwd || process.cwd(),
4258
4356
  // A blocked read feeds back so the helper can adapt without aborting.
4259
4357
  extensions: safety.extensions,
4260
4358
  env: guardrailEnv(`research-r${state.id}`),
@@ -4294,7 +4392,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4294
4392
  state.zoomRender?.();
4295
4393
  },
4296
4394
  onUsage: (usage) => {
4297
- if (researchWindow.window > 0) {
4395
+ state.contextTokens = (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
4396
+ if (researchWindow.window > 0) {
4298
4397
  // Same context truth as dispatchAgent: include cache reads/writes,
4299
4398
  // measured against THIS helper's window rather than the dispatcher's.
4300
4399
  state.contextPct = contextPct(usage, researchWindow.window);
@@ -4433,6 +4532,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4433
4532
  }
4434
4533
 
4435
4534
  function handlePrompt(socket: net.Socket, env: PromptEnvelope): void {
4535
+ if (currentCtx && modelWorkBlockedByRosterRecovery(currentCtx)) {
4536
+ nack(socket, env.msg_id, "orchestrator roster recovery required");
4537
+ return;
4538
+ }
4436
4539
  // 1. Hop limit check
4437
4540
  if (typeof env.hops !== "number" || env.hops >= MAX_HOPS) {
4438
4541
  nack(socket, env.msg_id, "hops exceeded");
@@ -4937,22 +5040,24 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4937
5040
  pi.registerTool({
4938
5041
  name: "dispatch_agent",
4939
5042
  label: "Dispatch Agent",
4940
- description: "Dispatch a task to a specialist agent. The agent will execute the task and return the result. Use the system prompt to see available agent names.",
5043
+ description: "Dispatch one focused task to a listed specialist; it returns evidence.",
4941
5044
  parameters: Type.Object({
4942
5045
  agent: Type.String({ description: "Agent name (case-insensitive)" }),
4943
5046
  task: Type.String({ description: "Task description for the agent to execute" }),
4944
- 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." }))),
4945
- 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." }))),
4946
- 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)." })),
4947
- review_reason: Type.Optional(Type.String({ description: "Why a documentation-only change needs a review gate (e.g. it publishes a credential, or states a contract other systems rely on). Only needed when dispatching a review persona with a docs-only `scope`." })),
5047
+ artifacts: Type.Optional(Type.Array(Type.String({ description: "Input artifact path; the specialist reads it." }))),
5048
+ scope: Type.Optional(Type.Array(Type.String({ description: "Advisory writable-file globs; violations are reported, never reverted." }))),
5049
+ watchdog: Type.Optional(Type.Boolean({ description: "Override this dispatch's drift watchdog." })),
5050
+ review_reason: Type.Optional(Type.String({ description: "Why a docs-only review is needed." })),
4948
5051
  backend: Type.Optional(Type.Union([
4949
5052
  Type.Literal("auto"),
4950
5053
  Type.Literal("native"),
4951
5054
  Type.Literal("coms"),
4952
- ], { description: "Dispatch backend. auto follows dispatch-policy.yaml (default); native always starts the local Pi specialist; coms requires a live same-name peer and never falls back." })),
5055
+ ], { description: "auto policy; native local; coms requires its live peer (no fallback)." })),
4953
5056
  }),
4954
5057
 
4955
5058
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
5059
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5060
+ if (confirmationRefusal) return confirmationRefusal;
4956
5061
  const { task, artifacts, scope, watchdog, review_reason, backend = "auto" } = params as { agent: string; task: string; artifacts?: string[]; scope?: string[]; watchdog?: boolean; review_reason?: string; backend?: "auto" | "native" | "coms" };
4957
5062
  // Display names / underscores resolve to the persona slug key space, so
4958
5063
  // `agent: "Test Engineer"` never burns a dispatch on a lookup error.
@@ -4994,8 +5099,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4994
5099
  if (taskRefusal) {
4995
5100
  turnReport.refusals++;
4996
5101
  sessionTotals.refusals++;
5102
+ armBudgetContinuation("task", taskRefusal.reason);
4997
5103
  return {
4998
- content: [{ type: "text", text: taskRefusal.message }],
5104
+ content: [{ type: "text", text: budgetContinuationInstruction(taskRefusal.message, "task", userLanguage) }],
4999
5105
  details: { agent, task, status: "task_budget_refused", reason: taskRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
5000
5106
  };
5001
5107
  }
@@ -5005,14 +5111,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5005
5111
  "dispatch",
5006
5112
  { dispatches: turnDispatchCount, research: turnResearchCount },
5007
5113
  currentBudget(),
5008
- Date.now() - (currentTurnStartedAt || Date.now()),
5114
+ turnBudgetActiveElapsedMs(),
5009
5115
  hubMode,
5010
5116
  );
5011
5117
  if (budgetRefusal) {
5012
5118
  turnReport.refusals++;
5013
5119
  sessionTotals.refusals++;
5120
+ armBudgetContinuation("turn", budgetRefusal.reason);
5014
5121
  return {
5015
- content: [{ type: "text", text: budgetRefusal.message }],
5122
+ content: [{ type: "text", text: budgetContinuationInstruction(budgetRefusal.message, "turn", userLanguage) }],
5016
5123
  details: { agent, task, status: "budget_refused", reason: budgetRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
5017
5124
  };
5018
5125
  }
@@ -5145,7 +5252,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5145
5252
  const resumePrompt = "Research findings for your NEEDS_RESEARCH questions are ready. " +
5146
5253
  "Read each file with your read tool, then continue from where you paused:\n" +
5147
5254
  answered.map((a, i) => `${i + 1}. ${a.question}\n → ${a.file}`).join("\n");
5148
- result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog, backend);
5255
+ result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog, backend, true);
5149
5256
  dispatchBilled += result.billed ?? 0;
5150
5257
  dispatchOut += result.out ?? 0;
5151
5258
  }
@@ -5241,7 +5348,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5241
5348
  ? `\n\n⚠ ${agent} paused for research, but the TASK research envelope is spent ` +
5242
5349
  `(${taskResearchCount}/${currentTaskBudget().maxResearch}) — no helper was spawned and the specialist ` +
5243
5350
  `was not resumed. Its questions are unanswered. Narrow the task so it can proceed on what it has, ` +
5244
- `or open a new task window with /af-new-task if this is genuinely different work.`
5351
+ `or call set_task_tier with new_task: true if this is genuinely different work.`
5245
5352
  : "";
5246
5353
 
5247
5354
  const returnPathNotice = returnPath ? `\n\nFull specialist output: ${returnPath}` : "";
@@ -5410,15 +5517,17 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5410
5517
  pi.registerTool({
5411
5518
  name: "spawn_research",
5412
5519
  label: "Spawn Research",
5413
- description: "Spawn a READ-ONLY research helper (read/grep/find/ls — no bash, no writes) and return its findings. Use for reconnaissance, code search, and reading docs/code before dispatching a builder, or to gather context for a specialist (specialists cannot spawn their own helpers). Pass `persona` to use a research persona, or omit it for an ad-hoc helper.",
5520
+ description: "Run a read-only (read/grep/find/ls) helper and return findings.",
5414
5521
  parameters: Type.Object({
5415
- task: Type.String({ description: "What to investigate. Be specific about what to find and report." }),
5416
- persona: Type.Optional(Type.String({ description: "Optional research-persona name (see the Research personas list). It brings its own role/model/thinking. Omit for an anonymous helper." })),
5417
- model: Type.Optional(Type.String({ description: "Optional pi model spec for an anonymous helper (ignored when `persona` is set — the persona carries its own model)." })),
5418
- 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 helper must read the file itself." }))),
5522
+ task: Type.String({ description: "Investigation and expected findings." }),
5523
+ persona: Type.Optional(Type.String({ description: "Research persona; omit for ad-hoc." })),
5524
+ model: Type.Optional(Type.String({ description: "Anonymous-helper model; ignored with persona." })),
5525
+ artifacts: Type.Optional(Type.Array(Type.String({ description: "Input artifact path." }))),
5419
5526
  }),
5420
5527
 
5421
5528
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
5529
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5530
+ if (confirmationRefusal) return confirmationRefusal;
5422
5531
  const { task, persona, model, artifacts } = params as { task: string; persona?: string; model?: string; artifacts?: string[] };
5423
5532
 
5424
5533
  // Pre-flight refusals before anything is charged: an unacknowledged
@@ -5444,8 +5553,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5444
5553
  if (taskRefusal) {
5445
5554
  turnReport.refusals++;
5446
5555
  sessionTotals.refusals++;
5556
+ armBudgetContinuation("task", taskRefusal.reason);
5447
5557
  return {
5448
- content: [{ type: "text", text: taskRefusal.message }],
5558
+ content: [{ type: "text", text: budgetContinuationInstruction(taskRefusal.message, "task", userLanguage) }],
5449
5559
  details: { status: "task_budget_refused", reason: taskRefusal.reason },
5450
5560
  };
5451
5561
  }
@@ -5455,14 +5565,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5455
5565
  "research",
5456
5566
  { dispatches: turnDispatchCount, research: turnResearchCount },
5457
5567
  currentBudget(),
5458
- Date.now() - (currentTurnStartedAt || Date.now()),
5568
+ turnBudgetActiveElapsedMs(),
5459
5569
  hubMode,
5460
5570
  );
5461
5571
  if (budgetRefusal) {
5462
5572
  turnReport.refusals++;
5463
5573
  sessionTotals.refusals++;
5574
+ armBudgetContinuation("turn", budgetRefusal.reason);
5464
5575
  return {
5465
- content: [{ type: "text", text: budgetRefusal.message }],
5576
+ content: [{ type: "text", text: budgetContinuationInstruction(budgetRefusal.message, "turn", userLanguage) }],
5466
5577
  details: { status: "budget_refused", reason: budgetRefusal.reason },
5467
5578
  };
5468
5579
  }
@@ -5607,17 +5718,29 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5607
5718
  }),
5608
5719
  async execute(_callId, params, _signal, _onUpdate, _ctx) {
5609
5720
  const { tier, reason, new_task } = params as { tier: string; reason?: string; new_task?: boolean };
5610
- if (new_task) resetTaskWindow(null);
5611
- // An ASSUMED tier is the hub's fail-safe, not a declaration to ratchet
5612
- // against: the dispatcher's own first triage must not be refused as an
5613
- // "escalation" for lacking a reason it had no way to know it needed.
5614
- const change = applyTierChange(taskTierAssumed ? null : taskTier, tier, reason);
5721
+ // An explicit new-task reset is the lifecycle escape hatch and clears
5722
+ // provisional decisions; it must not itself require the old task's consent.
5723
+ if (!new_task) {
5724
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5725
+ if (confirmationRefusal) return confirmationRefusal;
5726
+ }
5727
+
5728
+ // A new task classifies from an empty ratchet. Validate the requested tier
5729
+ // before mutating/resetting anything so invalid input cannot erase a task.
5730
+ const currentTier = new_task ? null : (taskTierAssumed ? null : taskTier);
5731
+ const change = applyTierChange(currentTier, tier, reason);
5615
5732
  if (!change.ok) {
5616
5733
  return {
5617
5734
  content: [{ type: "text" as const, text: change.message }],
5618
5735
  details: { status: "error", reason: change.reason, tier: change.tier },
5619
5736
  };
5620
5737
  }
5738
+ if (new_task) {
5739
+ const resetAt = Date.now();
5740
+ const prior = taskResetSnapshot(resetAt);
5741
+ resetTaskWindow(null, resetAt);
5742
+ appendTaskResetEntry("tool:set_task_tier", null, prior, _ctx);
5743
+ }
5621
5744
  taskTier = change.tier;
5622
5745
  taskTierAssumed = false;
5623
5746
  turnReport.tier = change.tier;
@@ -5663,6 +5786,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5663
5786
  reason: Type.String({ description: "One line on why the roster must change for this task." }),
5664
5787
  }),
5665
5788
  async execute(_callId, params, _signal, _onUpdate, ctx) {
5789
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5790
+ if (confirmationRefusal) return confirmationRefusal;
5666
5791
  const { action, agent, reason } = params as { action: string; agent: string; reason: string };
5667
5792
  const act = String(action || "").trim().toLowerCase();
5668
5793
  if (hubMode === "fast") {
@@ -5708,17 +5833,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5708
5833
  pi.registerTool({
5709
5834
  name: "set_assertions",
5710
5835
  label: "Set Assertions",
5711
- description:
5712
- `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.`,
5836
+ description: `Replace this task's checkable assertion ledger (max ${MAX_OPEN_ASSERTIONS}); dispatch only evidence-gated work.`,
5713
5837
  parameters: Type.Object({
5714
5838
  assertions: Type.Array(
5715
5839
  Type.Object({
5716
- id: Type.String({ description: "Stable id, e.g. A1, A2 — referenced verbatim in dispatches and returns." }),
5717
- tag: Type.String({ description: "How it will be proven: test | runtime-ui | code-grep | manual." }),
5718
- text: Type.String({ description: "One checkable pass condition (split compound requirements into separate assertions)." }),
5719
- 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." }),
5840
+ id: Type.String({ description: "Stable id (A1, A2)." }),
5841
+ tag: Type.String({ description: "test | runtime-ui | code-grep | manual." }),
5842
+ text: Type.String({ description: "One pass condition." }),
5843
+ source: Type.String({ description: "Requirement origin." }),
5720
5844
  }),
5721
- { description: `The full assertion list — replaces any existing ledger. Soft cap ${MAX_OPEN_ASSERTIONS} per batch.` },
5845
+ { description: `Replacement list; soft cap ${MAX_OPEN_ASSERTIONS}.` },
5722
5846
  ),
5723
5847
  }),
5724
5848
  async execute(_callId, params, _signal, _onUpdate, ctx) {
@@ -5754,8 +5878,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5754
5878
  pi.registerTool({
5755
5879
  name: "update_assertion",
5756
5880
  label: "Update Assertion",
5757
- description:
5758
- "Update one acceptance assertion's status after a verification gate. status is proven (name the evidence — test name, command output, file:line, or runtime observation), unproven (not yet checked), or failed (checked and wrong). Advance the task only on proven; treat unproven/failed as not done. A runtime-ui assertion is proven only by an actual runtime observation, never a static review.",
5881
+ description: "Record a verification result. proven requires named evidence; unproven/failed are not done.",
5759
5882
  parameters: Type.Object({
5760
5883
  id: Type.String({ description: "Assertion id to update, e.g. A2." }),
5761
5884
  status: Type.String({ description: "One of: proven | unproven | failed." }),
@@ -5819,8 +5942,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5819
5942
  pi.registerTool({
5820
5943
  name: "get_assertions",
5821
5944
  label: "Get Assertions",
5822
- description:
5823
- "Read back the full acceptance-assertion ledger — every id, tag, status, pass condition, and named evidence. Use this to recover the ledger after a context compaction (the dispatcher status line shows only counts, not the assertion text) before re-dispatching or reporting done. Read-only: it never changes the ledger.",
5945
+ description: "Read the full assertion ledger, especially after compaction. Read-only.",
5824
5946
  parameters: Type.Object({}),
5825
5947
  async execute(_callId, _params, _signal, _onUpdate, _ctx) {
5826
5948
  if (assertions.length === 0) {
@@ -5848,11 +5970,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5848
5970
  pi.registerTool({
5849
5971
  name: "coms_list",
5850
5972
  label: "Coms List",
5851
- description:
5852
- "List the peer agents in your current coms pool — the ones shown in the pool widget. Returns " +
5853
- "names, models, live context-window usage, pane_id, and status (idle | working | booting). " +
5854
- "Check status before sending instead of polling the pane. Discovery is scoped to what the human " +
5855
- "displays via /af-coms; you CANNOT widen it to other projects or reveal --explicit peers yourself.",
5973
+ description: "List peers in the human-scoped pool; this tool cannot widen discovery.",
5856
5974
  parameters: Type.Object({
5857
5975
  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." })),
5858
5976
  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." })),
@@ -5964,10 +6082,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5964
6082
  pi.registerTool({
5965
6083
  name: "coms_send",
5966
6084
  label: "Coms Send",
5967
- description:
5968
- "Send a prompt to a peer agent. Returns synchronously with a msg_id once the receiver acks. " +
5969
- "Use coms_get (non-blocking) or coms_await (blocking) with the msg_id to retrieve the response. " +
5970
- "Throws if the receiver is unreachable or rejects the envelope.",
6085
+ description: "Send to an in-pool peer; use its msg_id with coms_get or coms_await.",
5971
6086
  parameters: Type.Object({
5972
6087
  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." }),
5973
6088
  prompt: Type.String({ description: "The prompt to send." }),
@@ -5977,6 +6092,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5977
6092
  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." })),
5978
6093
  }),
5979
6094
  async execute(_callId, params) {
6095
+ const confirmationRefusal = provisionalCapabilityRefusal("peer");
6096
+ if (confirmationRefusal) return confirmationRefusal;
5980
6097
  if (!identity) {
5981
6098
  throw new Error("coms not initialised");
5982
6099
  }
@@ -6140,8 +6257,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6140
6257
  pi.registerTool({
6141
6258
  name: "coms_await",
6142
6259
  label: "Coms Await",
6143
- description:
6144
- "Block until a pending coms_send reply lands or the timeout fires. Default timeout 30 minutes (PI_COMS_TIMEOUT_MS).",
6260
+ description: "Wait for a pending coms_send reply; timeout leaves it pending.",
6145
6261
  parameters: Type.Object({
6146
6262
  msg_id: Type.String({ description: "msg_id returned by coms_send." }),
6147
6263
  timeout_ms: Type.Optional(Type.Number({ description: "Override the default timeout (ms)." })),
@@ -6282,20 +6398,21 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6282
6398
  pi.registerTool({
6283
6399
  name: "herdr_spawn_peer",
6284
6400
  label: "Herdr Spawn Peer",
6285
- description:
6286
- "Spawn one reusable coms peer in a sibling pane of the CURRENT Herdr workspace. Name-only resolution is identical to `just fleet peer`: peers.yaml may select a Pi persona, personaless Fleet Core, or Claude Code plus declared model/extensions/env_file. Explicit compatible fields override the declaration, but the Hub forces its own coms project and never accepts an env path or raw command. The peer boots IDLE; this call waits for `peer_ready` before it may receive coms work.",
6401
+ description: "Spawn a reusable sibling coms peer from its declared or compatible override settings; wait for peer_ready.",
6287
6402
  parameters: Type.Object({
6288
- name: Type.String({ description: "Pane label and coms peer name." }),
6289
- runner: Type.Optional(Type.Union([Type.Literal("pi"), Type.Literal("claude-code")], { description: "Override the declared runner." })),
6290
- persona: Type.Optional(Type.String({ description: "Explicit Pi persona under agents/ or .pi/agents/." })),
6291
- no_persona: Type.Optional(Type.Boolean({ description: "Force a personaless Fleet Core Pi peer." })),
6292
- model: Type.Optional(Type.String({ description: "Override the declared model." })),
6293
- extensions: Type.Optional(Type.String({ description: "Comma-separated extensions for a Pi persona peer." })),
6294
- browser: Type.Optional(Type.Boolean({ description: "Add browser capability to a Pi peer." })),
6295
- all_extensions: Type.Optional(Type.Boolean({ description: "Load all extensions; personaless Fleet Core only." })),
6296
- direction: Type.Optional(Type.Union([Type.Literal("right"), Type.Literal("down")], { description: "Split direction (default right)." })),
6403
+ name: Type.String({ description: "Peer and pane name." }),
6404
+ runner: Type.Optional(Type.Union([Type.Literal("pi"), Type.Literal("claude-code")], { description: "Runner override." })),
6405
+ persona: Type.Optional(Type.String({ description: "Pi persona override." })),
6406
+ no_persona: Type.Optional(Type.Boolean({ description: "Use persona-less Fleet Core." })),
6407
+ model: Type.Optional(Type.String({ description: "Model override." })),
6408
+ extensions: Type.Optional(Type.String({ description: "Pi extensions." })),
6409
+ browser: Type.Optional(Type.Boolean({ description: "Enable browser." })),
6410
+ all_extensions: Type.Optional(Type.Boolean({ description: "All extensions (Fleet Core only)." })),
6411
+ direction: Type.Optional(Type.Union([Type.Literal("right"), Type.Literal("down")], { description: "Split direction." })),
6297
6412
  }),
6298
6413
  async execute(_callId, params) {
6414
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6415
+ if (confirmationRefusal) return confirmationRefusal;
6299
6416
  if (!herdrFleetReady) {
6300
6417
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6301
6418
  }
@@ -6379,14 +6496,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6379
6496
  pi.registerTool({
6380
6497
  name: "herdr_spawn_pane",
6381
6498
  label: "Herdr Spawn Pane",
6382
- description:
6383
- "Spawn a raw shell command in a sibling pane of the CURRENT Herdr workspace. This is not a coms peer: it has no persona, project, registration wait, or peer_ready result. Use herdr_spawn_peer for addressable Pi/Claude workers.",
6499
+ description: "Spawn a raw auxiliary command in a sibling pane, not a coms peer.",
6384
6500
  parameters: Type.Object({
6385
6501
  name: Type.String({ description: "Human-visible pane label." }),
6386
6502
  command: Type.String({ description: "Raw shell command executed with bash -lc." }),
6387
6503
  direction: Type.Optional(Type.Union([Type.Literal("right"), Type.Literal("down")], { description: "Split direction (default right)." })),
6388
6504
  }),
6389
6505
  async execute(_callId, params) {
6506
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6507
+ if (confirmationRefusal) return confirmationRefusal;
6390
6508
  if (!herdrFleetReady) {
6391
6509
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6392
6510
  }
@@ -6430,8 +6548,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6430
6548
  pi.registerTool({
6431
6549
  name: "herdr_read_pane",
6432
6550
  label: "Herdr Read Pane",
6433
- description:
6434
- "Read the recent output of a herdr pane (bounded; max 200 lines). Read-to-decide: check on a spawned worker or an unbridged tool before acting. Prefer coms_send/coms_await for talking to pi or bridged peers.",
6551
+ description: "Read up to 200 recent pane lines; use coms for bridged peers.",
6435
6552
  parameters: Type.Object({
6436
6553
  pane_id: Type.String({ description: "Pane id, e.g. w3:p2 (see herdr_spawn_peer result or the sidebar)." }),
6437
6554
  lines: Type.Optional(Type.Number({ description: "Line cap, default 60, max 200." })),
@@ -6462,13 +6579,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6462
6579
  pi.registerTool({
6463
6580
  name: "herdr_close_pane",
6464
6581
  label: "Herdr Close Pane",
6465
- description:
6466
- "Close a herdr pane (kills whatever runs in it). DESTRUCTIVE — the human is asked to confirm every call. Only close panes you spawned; never close the human's own panes.",
6582
+ description: "Close a Hub-spawned pane. Destructive: always asks the human.",
6467
6583
  parameters: Type.Object({
6468
6584
  pane_id: Type.String({ description: "Pane id to close." }),
6469
6585
  reason: Type.String({ description: "One line shown to the human: why this pane can die." }),
6470
6586
  }),
6471
6587
  async execute(_callId, params) {
6588
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6589
+ if (confirmationRefusal) return confirmationRefusal;
6472
6590
  if (!herdrFleetReady) {
6473
6591
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6474
6592
  }
@@ -6505,13 +6623,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6505
6623
  pi.registerTool({
6506
6624
  name: "herdr_notify",
6507
6625
  label: "Herdr Notify",
6508
- description:
6509
- "Show a desktop notification via herdr — reach the human when they are not watching this pane (long task finished, fleet needs attention). Not a substitute for ask_user.",
6626
+ description: "Notify an away human; never replaces ask_user.",
6510
6627
  parameters: Type.Object({
6511
6628
  title: Type.String({ description: "Notification title." }),
6512
6629
  body: Type.Optional(Type.String({ description: "Notification body." })),
6513
6630
  }),
6514
6631
  async execute(_callId, params) {
6632
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6633
+ if (confirmationRefusal) return confirmationRefusal;
6515
6634
  if (!herdrFleetReady) {
6516
6635
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6517
6636
  }
@@ -6549,7 +6668,69 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6549
6668
 
6550
6669
  let askUserAvailable = false;
6551
6670
  let posture: Posture = "operator";
6671
+ let rosterRecoveryRequired = false;
6672
+ let rosterRecoveryDiagnostic = "";
6552
6673
  let baselineTools: string[] = [];
6674
+ let taskCapabilityPacks: CapabilityPack[] = [];
6675
+ let taskProvisionalPacks: CapabilityPack[] = [];
6676
+ let capabilityConfirmation: CapabilityConfirmationState = {};
6677
+ let contextPressureState: ContextPressureState = createContextPressureState();
6678
+ let capabilityResolution: CapabilityResolution = resolveCapabilityPacks({
6679
+ posture, userText: "", taskPacks: [], comsReady: false, herdrReady: false,
6680
+ pendingOperations: [], contextState: "normal",
6681
+ });
6682
+
6683
+ function pendingCapabilityOperations(): PendingOperation[] {
6684
+ const pending: PendingOperation[] = [];
6685
+ if (Array.from(agentStates.values()).some(state => state.status === "running") || Array.from(researchStates.values()).some(state => state.status === "running")) pending.push({ pack: "fleet", kind: "child" });
6686
+ if (pendingReplies.size > 0 || pendingHandoff) pending.push({ pack: "peer", kind: "message" });
6687
+ if (hubSpawnedPeers.size > 0) pending.push({ pack: "workspace", kind: "pane" });
6688
+ return pending;
6689
+ }
6690
+
6691
+ function capabilityContextState(): ContextState {
6692
+ if (contextPressureState.phase === "warning") return "approaching-compaction";
6693
+ if (contextPressureState.phase !== "normal") return "imminent-compaction";
6694
+ if (contextPressureState.pressure === "imminent") return "imminent-compaction";
6695
+ if (contextPressureState.pressure === "approaching") return "approaching-compaction";
6696
+ // Before the first turn_end sample, preserve startup/input protection from
6697
+ // the live Pi measurement without mutating the single-flight state machine.
6698
+ const percent = currentCtx?.getContextUsage?.()?.percent;
6699
+ if (typeof percent === "number" && percent >= 90) return "imminent-compaction";
6700
+ if (typeof percent === "number" && percent >= 80) return "approaching-compaction";
6701
+ return "normal";
6702
+ }
6703
+
6704
+ function resolveIncomingCapabilities(userText: string, newTask = false): void {
6705
+ capabilityResolution = resolveCapabilityPacks({
6706
+ posture,
6707
+ userText,
6708
+ taskTier: taskTier === "trivial" || taskTier === "small" || taskTier === "feature" || taskTier === "project" ? taskTier : undefined,
6709
+ taskPacks: taskCapabilityPacks,
6710
+ provisionalPacks: taskProvisionalPacks,
6711
+ comsReady,
6712
+ herdrReady: herdrFleetReady,
6713
+ pendingOperations: pendingCapabilityOperations(),
6714
+ contextState: capabilityContextState(),
6715
+ newTask,
6716
+ });
6717
+ for (const pack of ["fleet", "peer", "workspace"] as const) {
6718
+ if (capabilityConfirmation[pack] === "promoted" || capabilityConfirmation[pack] === "declined") {
6719
+ capabilityResolution.provisional = capabilityResolution.provisional.filter(candidate => candidate !== pack);
6720
+ capabilityResolution.confirmationRequired = capabilityResolution.confirmationRequired.filter(candidate => candidate !== pack);
6721
+ if (capabilityConfirmation[pack] === "promoted" && !capabilityResolution.active.includes(pack)) capabilityResolution.active.push(pack);
6722
+ }
6723
+ }
6724
+ taskCapabilityPacks = capabilityResolution.nextTaskPacks = CAPABILITY_PACKS.filter(pack => pack !== "core" && pack !== "compaction" && capabilityResolution.active.includes(pack));
6725
+ taskProvisionalPacks = capabilityResolution.provisional.filter(pack => capabilityConfirmation[pack as ConfirmableCapabilityPack] !== "declined");
6726
+ try { pi.appendEntry("agent-hub-capability-packs", persistedCapabilityState(capabilityResolution, capabilityConfirmation)); } catch { /* state persistence is best-effort */ }
6727
+ }
6728
+
6729
+ function provisionalCapabilityRefusal(pack: ConfirmableCapabilityPack) {
6730
+ const gate = confirmationGate(capabilityConfirmation, pack, capabilityResolution.provisional.includes(pack));
6731
+ if (gate.allowed) return null;
6732
+ return { content: [{ type: "text" as const, text: gate.message }], details: { status: "provisional_confirmation_required", confirmation: gate.status, pack } };
6733
+ }
6553
6734
 
6554
6735
  function applyPostureTools(): void {
6555
6736
  pi.setActiveTools(resolvePostureTools({
@@ -6558,6 +6739,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6558
6739
  comsReady,
6559
6740
  herdrReady: herdrFleetReady,
6560
6741
  askUserAvailable,
6742
+ capabilityPacks: [...capabilityResolution.active, ...capabilityResolution.provisional],
6561
6743
  }));
6562
6744
  }
6563
6745
 
@@ -6565,6 +6747,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6565
6747
  ctx.ui.setStatus("hub-posture", `Posture: ${posture}`);
6566
6748
  }
6567
6749
 
6750
+ function modelWorkBlockedByRosterRecovery(ctx: ExtensionContext): boolean {
6751
+ if (posture !== "orchestrator" || !rosterRecoveryRequired) return false;
6752
+ const message = `${rosterRecoveryDiagnostic || "No valid native roster is active."} Select one with /af-agents-team, restart with --agent-team <name>, or switch explicitly with /af-posture operator.`;
6753
+ ctx.ui.notify(message, "error");
6754
+ // Print/JSON modes do not render extension notifications. Never include the
6755
+ // blocked prompt or command arguments in this metadata-only diagnostic.
6756
+ if (!ctx.hasUI) console.error(`[agent-hub] ${message}`);
6757
+ return true;
6758
+ }
6759
+
6568
6760
  function postureStatusText(): string {
6569
6761
  return [
6570
6762
  `Posture: ${posture}`,
@@ -6625,7 +6817,26 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6625
6817
 
6626
6818
  const idx = options.indexOf(choice);
6627
6819
  const name = teamNames[idx];
6628
- activateTeam(name);
6820
+ const selected = resolveSessionRoster({
6821
+ teams,
6822
+ entries: [],
6823
+ explicitRoster: name,
6824
+ availablePersonas: allAgentDefs.map(def => def.name),
6825
+ });
6826
+ if (!selected.roster) {
6827
+ ctx.ui.notify(`${selected.diagnostic} Fix .pi/agents/teams.yaml or select another team.`, "error");
6828
+ return;
6829
+ }
6830
+ activateTeam(selected.roster.name);
6831
+ rosterRecoveryRequired = false;
6832
+ rosterRecoveryDiagnostic = "";
6833
+ persistActiveRoster();
6834
+ resolveIncomingCapabilities("");
6835
+ applyPostureTools();
6836
+ if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
6837
+ await pickDispatcherPersona(ctx);
6838
+ }
6839
+ setTimeout(replayDeferredRecoveryInputs, 0);
6629
6840
  updateWidget();
6630
6841
  ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
6631
6842
  ctx.ui.notify(`Team: ${name} — ${Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ")}`, "info");
@@ -6648,17 +6859,154 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6648
6859
  const peers = fleetPeerInputs(model => `⇄ ${abbreviateModel(model)}`);
6649
6860
  return buildFleetRows({ specialists, research, peers }, unfiltered ? { showFinished: true } : { showFinished: fleetShowFinished, query: fleetFilter });
6650
6861
  }
6862
+ type FleetDetailModelTarget =
6863
+ | { kind: "specialist"; current: string; state: AgentState }
6864
+ | { kind: "research"; current: string; state: ResearchState }
6865
+ | { kind: "delegate"; current: string; delegation: NonNullable<ReturnType<typeof findDelegationChild>>; role: [string, SubagentRole]; overrideKey: string };
6866
+
6867
+ function resolveFleetDetailModelTarget(row: FleetRow, ctx: any): FleetDetailModelTarget | null {
6868
+ if (row.kind === "peer") {
6869
+ ctx.ui.notify("External coms peers control their own model; switch it in that peer's Pi session.", "info");
6870
+ return null;
6871
+ }
6872
+ if (row.kind === "specialist") {
6873
+ const state = agentStates.get(row.key);
6874
+ if (!state) { ctx.ui.notify("This specialist is no longer available.", "warning"); return null; }
6875
+ return { kind: "specialist", current: resolvedModel(state.def) ?? "", state };
6876
+ }
6877
+ if (row.kind === "research") {
6878
+ const state = researchStates.get(parseResearchHandle(row.key)!);
6879
+ if (!state) { ctx.ui.notify("This research helper is no longer available.", "warning"); return null; }
6880
+ return { kind: "research", current: state.model, state };
6881
+ }
6882
+ const delegation = findDelegationChild(row.key);
6883
+ if (!delegation) { ctx.ui.notify("This nested delegate is no longer available.", "warning"); return null; }
6884
+ const role = Object.entries(delegation.owner.def.subagents ?? {})
6885
+ .find(([name]) => name.toLowerCase() === delegation.child.role.toLowerCase());
6886
+ if (!role) {
6887
+ ctx.ui.notify(`The role for ${row.name} is no longer declared by ${displayName(delegation.owner.def.name)}.`, "warning");
6888
+ return null;
6889
+ }
6890
+ const overrideKey = `${delegation.owner.def.name.toLowerCase()}.${role[0].toLowerCase()}`;
6891
+ return { kind: "delegate", current: subagentModelOverrides.get(overrideKey) ?? role[1].model, delegation, role, overrideKey };
6892
+ }
6893
+
6894
+ /** Load every model Pi currently reports as available for the inline picker. */
6895
+ async function loadFleetDetailModelChoices(row: FleetRow, ctx: any): Promise<{ choices: FleetModelChoice[]; current: string } | null> {
6896
+ const target = resolveFleetDetailModelTarget(row, ctx);
6897
+ if (!target) return null;
6898
+ try { await ctx.modelRegistry?.refresh?.(); } catch { /* retain the registry's last-known available list */ }
6899
+ const choices = fleetModelChoices(ctx.modelRegistry?.getAvailable?.() ?? [], target.current);
6900
+ if (choices.length === 0) {
6901
+ const diagnostic = ctx.modelRegistry?.getError?.();
6902
+ ctx.ui.notify(`Pi reports no available models${diagnostic ? `: ${diagnostic}` : "."}`, "warning");
6903
+ return null;
6904
+ }
6905
+ return { choices, current: target.current };
6906
+ }
6907
+
6908
+ /** Apply an inline-picker choice to the next run; never interrupt a live child. */
6909
+ function applyFleetDetailModel(row: FleetRow, picked: string, ctx: any): boolean {
6910
+ const target = resolveFleetDetailModelTarget(row, ctx);
6911
+ if (!target) return false;
6912
+ if (picked === target.current) {
6913
+ ctx.ui.notify(`${row.name} is already on ${picked}`, "info");
6914
+ return false;
6915
+ }
6916
+ let applyHint = "applies on the next run";
6917
+ if (target.kind === "specialist") {
6918
+ const key = target.state.def.name.toLowerCase();
6919
+ if (picked === target.state.def.model) modelOverrides.delete(key);
6920
+ else modelOverrides.set(key, picked);
6921
+ applyHint = "applies on the next dispatch";
6922
+ } else if (target.kind === "research") {
6923
+ target.state.model = picked;
6924
+ applyHint = `applies when r${target.state.id} next continues or restarts`;
6925
+ } else {
6926
+ if (picked === target.role[1].model) subagentModelOverrides.delete(target.overrideKey);
6927
+ else subagentModelOverrides.set(target.overrideKey, picked);
6928
+ applyHint = `applies on the next ${displayName(target.delegation.owner.def.name)} dispatch`;
6929
+ }
6930
+ updateWidget();
6931
+ ctx.ui.notify(`${row.name} → ${picked} (${applyHint}; current runs are not interrupted)`, "success");
6932
+ if (target.kind === "specialist" && (dispatchPolicy.substitutions[target.state.def.name.toLowerCase()]?.prefer ?? dispatchPolicy.default) === "coms") {
6933
+ ctx.ui.notify("This specialist prefers a coms peer; the choice applies to native fallback runs, while the peer keeps its own model.", "info");
6934
+ }
6935
+ return true;
6936
+ }
6937
+
6938
+ function matchedFleetDetailInput(data: string): string {
6939
+ const key: FleetDetailKey | undefined =
6940
+ matchesKey(data, Key.up) ? "up"
6941
+ : matchesKey(data, Key.down) ? "down"
6942
+ : matchesKey(data, Key.pageUp) ? "pageUp"
6943
+ : matchesKey(data, Key.pageDown) ? "pageDown"
6944
+ : matchesKey(data, Key.home) ? "home"
6945
+ : matchesKey(data, Key.end) ? "end"
6946
+ : matchesKey(data, Key.enter) ? "enter"
6947
+ : matchesKey(data, Key.escape) ? "escape"
6948
+ : matchesKey(data, Key.ctrl("c")) ? "copy"
6949
+ : undefined;
6950
+ return normalizeFleetDetailInput(data, key);
6951
+ }
6952
+
6651
6953
  async function openFleetDetail(row: FleetRow, ctx: any): Promise<void> {
6652
6954
  const target = row.kind === "research" ? researchStates.get(parseResearchHandle(row.key)!) : row.kind === "delegate" ? findDelegationChild(row.key)?.child : agentStates.get(row.key);
6653
6955
  const resources = createPanelResources();
6956
+ let detailRow = row;
6957
+ let modelPicker: { choices: FleetModelChoice[]; index: number; scrollOffset: number } | null = null;
6654
6958
  let scrollOffset = 0, selectedIndex = 0, expandedIndex: number | null = null, followTail = true, lastRender = 0;
6655
6959
  const timeline = () => liveTimeline(target);
6656
6960
  try { await ctx.ui.custom((tui: any, theme: any, _kb: any, done: () => void) => {
6657
6961
  if (target) target.zoomRender = (force?: boolean) => { const now = Date.now(); if (force || now - lastRender > 80) { lastRender = now; tui.requestRender(); } };
6658
- return { render: (w: number) => { const body = bodyRows(tui.terminal?.rows, DETAIL_CHROME_ROWS); const entries = timeline(); if (followTail) scrollOffset = Math.max(0, detailContent(entries, w, expandedIndex).length - body); return renderFleetDetail(row, entries, scrollOffset, w, body, theme, expandedIndex); }, handleInput: async (data: string) => { const entries = timeline(); const state = { scrollOffset, selectedIndex, expandedIndex, followTail }; const action = detailTransition(data, state, entries, bodyRows(tui.terminal?.rows, DETAIL_CHROME_ROWS), detailContent(entries, tui.terminal?.columns ?? 80, expandedIndex).length); ({ scrollOffset, selectedIndex, expandedIndex, followTail } = state); if (action === "close") done(); else if (action === "copy") { const item = entries[selectedIndex]; if (item) { try { await copyToClipboard(item.content); ctx.ui.notify("Copied selected zoom row", "success"); } catch { ctx.ui.notify("Failed to copy selected zoom row", "error"); } } } tui.requestRender(); }, invalidate() {}, dispose: () => resources.dispose() };
6962
+ return {
6963
+ render: (w: number) => {
6964
+ const body = bodyRows(tui.terminal?.rows, DETAIL_CHROME_ROWS);
6965
+ if (modelPicker) return renderFleetModelPicker(detailRow.name, modelPicker.choices, modelPicker, w, body, theme);
6966
+ const entries = timeline();
6967
+ if (followTail) scrollOffset = Math.max(0, detailContent(entries, w, expandedIndex).length - body);
6968
+ return renderFleetDetail(detailRow, entries, scrollOffset, w, body, theme, expandedIndex);
6969
+ },
6970
+ handleInput: async (data: string) => {
6971
+ const input = matchedFleetDetailInput(data);
6972
+ const body = bodyRows(tui.terminal?.rows, DETAIL_CHROME_ROWS);
6973
+ if (modelPicker) {
6974
+ const action = modelPickerTransition(input, modelPicker, modelPicker.choices.length, body);
6975
+ if (action === "cancel") modelPicker = null;
6976
+ else if (action === "select") {
6977
+ const picked = modelPicker.choices[modelPicker.index]?.spec;
6978
+ modelPicker = null;
6979
+ if (picked && applyFleetDetailModel(detailRow, picked, ctx)) {
6980
+ detailRow = { ...detailRow, model: detailRow.status === "running" ? `${detailRow.model} → ${shortModel(picked)} next` : `${shortModel(picked)} (next)` };
6981
+ }
6982
+ }
6983
+ tui.requestRender();
6984
+ return;
6985
+ }
6986
+ const entries = timeline();
6987
+ const state = { scrollOffset, selectedIndex, expandedIndex, followTail };
6988
+ const action = detailTransition(input, state, entries, body, detailContent(entries, tui.terminal?.columns ?? 80, expandedIndex).length);
6989
+ ({ scrollOffset, selectedIndex, expandedIndex, followTail } = state);
6990
+ if (action === "close") done();
6991
+ else if (action === "copy") {
6992
+ const item = entries[selectedIndex];
6993
+ if (item) { try { await copyToClipboard(item.content); ctx.ui.notify("Copied selected zoom row", "success"); } catch { ctx.ui.notify("Failed to copy selected zoom row", "error"); } }
6994
+ } else if (action === "model") {
6995
+ const loaded = await loadFleetDetailModelChoices(detailRow, ctx);
6996
+ if (loaded) {
6997
+ const currentIndex = loaded.choices.findIndex(choice => choice.spec === loaded.current);
6998
+ modelPicker = { choices: loaded.choices, index: Math.max(0, currentIndex), scrollOffset: Math.max(0, currentIndex) };
6999
+ }
7000
+ }
7001
+ tui.requestRender();
7002
+ },
7003
+ invalidate() {},
7004
+ dispose: () => resources.dispose(),
7005
+ };
6659
7006
  }, FULLSCREEN_OVERLAY); } finally { resources.dispose(); if (target) target.zoomRender = undefined; }
6660
7007
  }
6661
7008
  async function restartFleetRow(selected: FleetRow, ctx: any): Promise<void> {
7009
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
6662
7010
  const decision = resolveFleetRestart(selected, {
6663
7011
  researchRestartable: (key) => {
6664
7012
  const state = researchStates.get(parseResearchHandle(key)!);
@@ -6822,6 +7170,120 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6822
7170
  },
6823
7171
  });
6824
7172
 
7173
+ function toolSchemaChars(toolList: string): number {
7174
+ const names = toolList.split(",").map(name => name.trim()).filter(Boolean);
7175
+ const all = typeof pi.getAllTools === "function" ? pi.getAllTools() : [];
7176
+ const byName = new Map(all.map((tool: any) => [tool.name, tool]));
7177
+ return names.reduce((sum, name) => {
7178
+ const tool = byName.get(name);
7179
+ return sum + (tool ? safeSchemaChars({ name: tool.name, description: tool.description, parameters: tool.parameters, promptGuidelines: tool.promptGuidelines }) : name.length);
7180
+ }, 0);
7181
+ }
7182
+ function contextPlanes(ctx: any): LivePlane[] {
7183
+ // Keep the projection decomposed along the same standing components native
7184
+ // spawn appends. It intentionally counts no task/history: this is cold-start.
7185
+ const baseChars = safeSchemaChars(ctx?.getSystemPromptOptions?.() ?? {});
7186
+ const projection = (def: AgentDef, research = false) => research
7187
+ ? researchStandingParts({
7188
+ replacementPrompt: nativeResearchSystemPrompt({
7189
+ personaName: def.name,
7190
+ personaPath: def.file,
7191
+ cwd: ctx?.cwd || process.cwd(),
7192
+ }),
7193
+ toolChars: toolSchemaChars(RESEARCH_TOOLS),
7194
+ // --system-prompt plus --no-skills/--no-context-files replaces
7195
+ // inherited child prompt inputs; only the explicit prompt/tools remain.
7196
+ basePromptChars: 0,
7197
+ })
7198
+ : specialistStandingParts({
7199
+ replacementPrompt: nativeSpecialistSystemPrompt({
7200
+ // An active child projects the exact metadata retained for its
7201
+ // spawn/resume; an inactive card is a task-free cold-start estimate.
7202
+ manifest: agentStates.get(def.name.toLowerCase())?.specialistManifest
7203
+ ?? buildSpecialistContextManifest({
7204
+ personaName: def.name, personaPath: def.file, personaPrompt: def.systemPrompt,
7205
+ task: "", rulesPaths: specialistProjectPolicyPaths(ctx?.cwd || process.cwd()), docsPaths: projectDocsPaths,
7206
+ hasAssertions: false, hasScope: false, hasArtifacts: false,
7207
+ delegateRoles: def.subagents && delegateExtPath ? Object.keys(def.subagents) : [],
7208
+ }),
7209
+ userLanguage, agentKey: safeAgentKey(def.name), runNumber: agentStates.get(def.name.toLowerCase())?.runCount ?? 0,
7210
+ }),
7211
+ toolChars: toolSchemaChars(def.tools),
7212
+ });
7213
+ const delegateProjection = (owner: AgentState, child: DelegationChild) => {
7214
+ const roleEntry = Object.entries(owner.def.subagents ?? {}).find(([name]) => name.toLowerCase() === child.role.toLowerCase());
7215
+ if (!roleEntry) return undefined;
7216
+ return delegateStandingParts({
7217
+ toolChars: toolSchemaChars(child.tools || roleEntry[1].tools || owner.def.tools),
7218
+ basePromptChars: baseChars,
7219
+ roleNames: [roleEntry[0]],
7220
+ });
7221
+ };
7222
+ const windowFor = (model: string) => model ? resolveContextWindow(model, { lookup: modelWindowLookup(ctx), fallbackWindow: 0 }).window || undefined : undefined;
7223
+ const local = allAgentDefs.filter(def => def.kind !== "research").map(def => {
7224
+ const state = agentStates.get(def.name.toLowerCase());
7225
+ const model = state ? (resolvedModel(state.def) ?? "") : (resolvedModel(def) ?? "");
7226
+ return { id: `specialist/${def.name}`, label: displayName(def.name), plane: "specialist" as const, model, window: windowFor(model), tokens: state?.contextTokens, projectionParts: projection(def) };
7227
+ });
7228
+ const research = researchPersonas.map(def => {
7229
+ const active = Array.from(researchStates.values()).find(state => state.def.name === def.name);
7230
+ const model = active?.model ?? resolvedModel(def) ?? "";
7231
+ return { id: `research/${def.name}`, label: displayName(def.name), plane: "research" as const, model, window: windowFor(model), tokens: active?.contextTokens, projectionParts: projection(def, true), attribution: "projected" as const };
7232
+ });
7233
+ const delegates = Array.from(agentStates.values()).flatMap(state => Array.from(state.delegations?.values() ?? []).map(child => {
7234
+ const projectionParts = delegateProjection(state, child);
7235
+ return projectionParts
7236
+ ? { id: `delegate/${child.id}`, label: child.role, plane: "delegate" as const, model: child.model, window: windowFor(child.model), tokens: child.tokens, projectionParts, attribution: "projected" as const }
7237
+ : { id: `delegate/${child.id}`, label: child.role, plane: "delegate" as const, model: child.model, window: windowFor(child.model), tokens: child.tokens, attribution: "unavailable" as const };
7238
+ }));
7239
+ const peers = Array.from(peerCards.values()).map(peer => ({ id: `peer/${peer.name}`, label: peer.name, plane: "peer" as const, model: peer.model, window: windowFor(peer.model ?? ""), percent: peer.context_used_pct, projectionChars: 0, attribution: "unavailable" as const }));
7240
+ return [...local, ...research, ...delegates, ...peers];
7241
+ }
7242
+
7243
+ async function openContextBudget(ctx: any): Promise<void> {
7244
+ const resources = createPanelResources();
7245
+ const toInput = (data: string): string => {
7246
+ if (matchesKey(data, Key.up)) return "\u001b[A";
7247
+ if (matchesKey(data, Key.down)) return "\u001b[B";
7248
+ if (matchesKey(data, Key.pageUp)) return "\u001b[5~";
7249
+ if (matchesKey(data, Key.pageDown)) return "\u001b[6~";
7250
+ if (matchesKey(data, Key.enter)) return "\r";
7251
+ if (matchesKey(data, Key.escape)) return "\u001b";
7252
+ return data;
7253
+ };
7254
+ const state: ContextBudgetViewState = { selection: { index: 0 }, expanded: new Set(), scrollOffset: 0 };
7255
+ const collect = () => {
7256
+ // Build the replacement prompt ledger now rather than waiting for the first
7257
+ // before_agent_start hook; this is pure prompt construction, not a turn.
7258
+ buildHubSystemPrompt(false);
7259
+ return collectContextBudgetSnapshot(ctx, {
7260
+ ledger: lastHubLedger,
7261
+ pressure: contextPressureDiagnostic(contextPressureState),
7262
+ planes: contextPlanes(ctx),
7263
+ tools: typeof pi.getAllTools === "function" ? pi.getAllTools() : [],
7264
+ activeToolNames: typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [],
7265
+ commands: typeof pi.getCommands === "function" ? pi.getCommands() : [],
7266
+ });
7267
+ };
7268
+ let snapshot = collect();
7269
+ const refresh = () => { snapshot = collect(); };
7270
+ try {
7271
+ await ctx.ui.custom((tui: any, _theme: any, _kb: any, done: () => void) => {
7272
+ resources.every(1000, () => { refresh(); tui.requestRender(); });
7273
+ return {
7274
+ render: (w: number) => renderContextBudget(snapshot, state, w, bodyRows(tui.terminal?.rows, CONTEXT_BUDGET_CHROME_ROWS)),
7275
+ handleInput: (data: string) => { const intent = contextBudgetTransition(toInput(data), state, snapshot, bodyRows(tui.terminal?.rows, CONTEXT_BUDGET_CHROME_ROWS)); if (intent === "close") done(); if (intent === "refresh") refresh(); tui.requestRender(); },
7276
+ invalidate() {}, dispose: () => resources.dispose(),
7277
+ };
7278
+ }, FULLSCREEN_OVERLAY);
7279
+ } finally { resources.dispose(); }
7280
+ }
7281
+
7282
+ pi.registerCommand("af-context", {
7283
+ description: "Open a read-only full-screen context budget diagnostic",
7284
+ handler: async (_args, ctx) => { widgetCtx = ctx; await openContextBudget(ctx); },
7285
+ });
7286
+
6825
7287
  // ── /af-posture: direct operator ↔ restricted orchestrator ──
6826
7288
  pi.registerCommand("af-posture", {
6827
7289
  description: "Show or set the Fleet posture: operator (direct tools) | orchestrator (delegate-only)",
@@ -6842,9 +7304,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6842
7304
  return;
6843
7305
  }
6844
7306
  posture = next;
7307
+ if (posture === "operator") {
7308
+ rosterRecoveryRequired = false;
7309
+ rosterRecoveryDiagnostic = "";
7310
+ setTimeout(replayDeferredRecoveryInputs, 0);
7311
+ }
6845
7312
  if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
6846
7313
  await pickDispatcherPersona(ctx);
6847
7314
  }
7315
+ resolveIncomingCapabilities("");
6848
7316
  applyPostureTools();
6849
7317
  updatePostureStatus(ctx);
6850
7318
  pi.appendEntry("agent-hub-posture", { posture });
@@ -6876,33 +7344,12 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6876
7344
  ctx.ui.notify(`Unknown mode "${requested}" — expected one of: ${HUB_MODES.join(", ")}`, "error");
6877
7345
  return;
6878
7346
  }
7347
+ const previousMode = hubMode;
6879
7348
  hubMode = mode;
6880
7349
  updateModeStatus();
6881
- ctx.ui.notify(`Execution mode → ${mode} (budgets apply from the next dispatch; prompt updates next turn)`, "success");
6882
- },
6883
- });
6884
-
6885
- // ── /af-new-task: open a fresh TASK window ──
6886
- // The task budget is deliberately immune to a user message — a steering
6887
- // message is a correction, not a new ask, and resetting on it is what let a
6888
- // run spend a fresh envelope per correction. Opening a new window is
6889
- // therefore an explicit, human decision, and this is where it is made.
6890
- pi.registerCommand("af-new-task", {
6891
- description: "Open a fresh task window: clears the task budget, the task tier, the duplicate guard, and any external-blocker stop. Use when moving on to different work — not for a correction to the current work.",
6892
- handler: async (args, ctx) => {
6893
- widgetCtx = ctx;
6894
- const label = (args || "").trim() || null;
6895
- const spentDispatches = taskDispatchCount;
6896
- const spentResearch = taskResearchCount;
6897
- const spentReviews = taskReviewRounds;
6898
- const spentMin = Math.round(taskActiveElapsedMs() / 60_000);
6899
- const priorTier = taskTier;
6900
- resetTaskWindow(label);
7350
+ appendHubModeEntry({ previousMode, mode, source: "slash-command", ctx });
6901
7351
  ctx.ui.notify(
6902
- `New task window${label ? `: ${label}` : ""}\n` +
6903
- `Previous task${priorTier ? ` (tier ${priorTier})` : ""} spent ${spentDispatches} dispatches, ` +
6904
- `${spentResearch} research, ${spentReviews} review round(s), ${spentMin} min active.\n` +
6905
- `Tier is unset — the dispatcher re-triages on its next dispatch.`,
7352
+ `Execution mode → ${mode} (budgets apply from the next dispatch; prompt updates next turn)` + hubLocationSuffix(ctx),
6906
7353
  "success",
6907
7354
  );
6908
7355
  },
@@ -7016,6 +7463,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7016
7463
  }
7017
7464
  teams[name] = members;
7018
7465
  activeTeamName = name;
7466
+ persistActiveRoster();
7019
7467
  ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
7020
7468
  ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "success");
7021
7469
  },
@@ -7634,6 +8082,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7634
8082
  getArgumentCompletions: researchPersonaCompletions,
7635
8083
  handler: async (args, ctx) => {
7636
8084
  widgetCtx = ctx;
8085
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7637
8086
  let rest = (args ?? "").trim();
7638
8087
  let personaName: string | undefined;
7639
8088
  let modelArg: string | undefined;
@@ -7709,6 +8158,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7709
8158
  // its /af-research-cont alias.
7710
8159
  const researchContHandler = async (args: string | undefined, ctx: any) => {
7711
8160
  widgetCtx = ctx;
8161
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7712
8162
  const trimmed = (args ?? "").trim();
7713
8163
  const sp = trimmed.indexOf(" ");
7714
8164
  if (sp === -1) {
@@ -7913,6 +8363,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7913
8363
  getArgumentCompletions: subagentTargetCompletions,
7914
8364
  handler: async (args, ctx) => {
7915
8365
  widgetCtx = ctx;
8366
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7916
8367
  const name = args?.trim();
7917
8368
  // An rN handle re-runs a finished helper's last task on a fresh session
7918
8369
  // (unlike /af-agents-cont, which resumes the existing one). A running helper
@@ -8093,6 +8544,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8093
8544
  description: "Hand the session off to a coms peer (the dispatcher composes a self-contained brief): /af-handoff <peer>",
8094
8545
  getArgumentCompletions: comsPeerCompletions,
8095
8546
  handler: async (args, ctx) => {
8547
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
8096
8548
  if (!comsReady) { ctx.ui.notify("coms is not active in this session — /af-handoff unavailable.", "warning"); return; }
8097
8549
  const target = (args ?? "").trim();
8098
8550
  if (!target) {
@@ -8130,6 +8582,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8130
8582
  pi.registerCommand("af-compound", {
8131
8583
  description: "Capture this session's lessons into the project's rules/docs via the documenter: /af-compound [focus]",
8132
8584
  handler: async (args, ctx) => {
8585
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
8133
8586
  if (!agentStates.has("documenter")) {
8134
8587
  ctx.ui.notify(
8135
8588
  "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.",
@@ -8174,29 +8627,79 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8174
8627
  pi.on("tool_execution_start", async (event) => {
8175
8628
  if (event.toolName !== "ask_user") return;
8176
8629
  askUserStarts.set(event.toolCallId, Date.now());
8630
+ const kind = budgetContinuationKind(event.args?.context);
8631
+ if (kind && pendingBudgetContinuation?.kind === kind) {
8632
+ budgetContinuationAsks.set(event.toolCallId, {
8633
+ kind,
8634
+ reason: pendingBudgetContinuation.reason,
8635
+ params: event.args,
8636
+ });
8637
+ }
8177
8638
  // Asking the human IS the escalation the external-blocker breaker demands:
8178
8639
  // once it is under way, the gate opens.
8179
8640
  externalBlockerAcknowledged = true;
8180
8641
  externalBlockerRefusedOnce = false;
8181
8642
  });
8643
+ observeAskUserResults(({ params, result, phase }) => {
8644
+ const pack = capabilityConfirmationPack(params.context);
8645
+ if (!pack) return;
8646
+ if (phase === "start") capabilityConfirmation[pack] = "pending";
8647
+ else {
8648
+ const outcome = confirmationOutcome(result);
8649
+ if (!outcome) return;
8650
+ capabilityConfirmation[pack] = outcome;
8651
+ resolveIncomingCapabilities("");
8652
+ applyPostureTools();
8653
+ }
8654
+ });
8655
+
8182
8656
  pi.on("tool_execution_end", async (event) => {
8183
8657
  if (event.toolName !== "ask_user") return;
8184
8658
  const startedAt = askUserStarts.get(event.toolCallId);
8185
8659
  askUserStarts.delete(event.toolCallId);
8186
8660
  // The task clock bills active time only — the human's answer is not the
8187
8661
  // fleet's work, and billing it is what would false-stop a steered session.
8188
- if (startedAt) turnAskUserWaitMs += Math.max(0, Date.now() - startedAt);
8189
- if (startedAt == null) return;
8190
- const interval: [number, number] = [startedAt, Date.now()];
8191
- // Attach to the live dispatcher entry, or buffer until one is created this turn.
8192
- if (currentOrchestratorEntry) (currentOrchestratorEntry.awaitIntervals ??= []).push(interval);
8193
- else turnAskUserIntervals.push(interval);
8194
- historyRender?.();
8662
+ const endedAt = Date.now();
8663
+ const waitMs = startedAt == null ? 0 : Math.max(0, endedAt - startedAt);
8664
+ if (startedAt) taskClock = addTaskClockWait(taskClock, waitMs);
8665
+ turnBudgetAskUserWaitMs += waitMs;
8666
+ if (startedAt != null) {
8667
+ const interval: [number, number] = [startedAt, endedAt];
8668
+ // Attach to the live dispatcher entry, or buffer until one is created this turn.
8669
+ if (currentOrchestratorEntry) (currentOrchestratorEntry.awaitIntervals ??= []).push(interval);
8670
+ else turnAskUserIntervals.push(interval);
8671
+ historyRender?.();
8672
+ }
8673
+
8674
+ // Renew only when this exact marked ask selected its first option. This uses
8675
+ // Pi's tool events rather than wrapper internals, so it also works when the
8676
+ // stock ask_user package owns the tool under extension discovery.
8677
+ const confirmation = budgetContinuationAsks.get(event.toolCallId);
8678
+ budgetContinuationAsks.delete(event.toolCallId);
8679
+ if (confirmation) {
8680
+ const outcome = budgetContinuationOutcome(confirmation.params, event.result);
8681
+ if (outcome) pendingBudgetContinuation = null;
8682
+ if (outcome === "continue") {
8683
+ const prior = budgetContinuationSnapshot(confirmation.kind, endedAt);
8684
+ if (confirmation.kind === "task") continueTaskBudgetWindow(endedAt);
8685
+ else renewTurnBudgetWindow(endedAt);
8686
+ appendBudgetContinuationEntry(confirmation.kind, confirmation.reason, prior, currentCtx ?? undefined);
8687
+ widgetCtx?.ui?.notify(
8688
+ confirmation.kind === "task"
8689
+ ? "Task budget continued; task tier, assertions, capabilities, and progress were preserved."
8690
+ : "Turn budget continued; continuing without another message.",
8691
+ "success",
8692
+ );
8693
+ }
8694
+ }
8195
8695
  });
8196
8696
 
8197
8697
  // ── System Prompt Override ───────────────────
8198
8698
 
8199
- pi.on("before_agent_start", async (_event, _ctx) => {
8699
+ // This is also called by /af-context before the first turn. Keep prompt assembly
8700
+ // in this one production path so its ledger describes the exact next replacement.
8701
+ function buildHubSystemPrompt(forTurn: boolean): { systemPrompt: string } {
8702
+ if (forTurn) {
8200
8703
  // Re-assert the selected posture for every turn so prompt and tool policy stay
8201
8704
  // synchronized after commands or runtime capability changes.
8202
8705
  applyPostureTools();
@@ -8211,18 +8714,24 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8211
8714
  // Fold the turn that just ended into the task's active-time accumulator
8212
8715
  // before the clock is re-based; inter-turn idle is never charged because
8213
8716
  // no turn is open across it.
8214
- closeTurnActiveTime();
8717
+ const turnStartedAt = Date.now();
8718
+ closeTurnActiveTime(turnStartedAt);
8719
+ taskClock = openTaskClock(taskClock, turnStartedAt);
8215
8720
  turnActive = true;
8216
- currentTurnStartedAt = Date.now();
8721
+ currentTurnStartedAt = turnStartedAt;
8217
8722
  currentOrchestratorEntry = null;
8218
8723
  askUserStarts.clear();
8219
8724
  turnAskUserIntervals.length = 0;
8725
+ turnBudgetAskUserWaitMs = 0;
8726
+ budgetContinuationAsks.clear();
8727
+ if (pendingBudgetContinuation?.kind === "turn") pendingBudgetContinuation = null;
8220
8728
  // Fresh turn → fresh TURN budget window (mode persists across turns). The
8221
8729
  // TASK budget, the tier, and the external-blocker breaker deliberately do
8222
8730
  // NOT reset here: a steering message is a correction to the same work, not
8223
8731
  // a new ask, and resetting on it is precisely how a run spent eight fresh
8224
- // dispatches per correction and never hit a bound. Only /af-new-task (or
8225
- // set_task_tier `new_task: true`) opens a new task window.
8732
+ // dispatches per correction and never hit a bound. A task continuation is
8733
+ // instead an explicit Yes/No confirmation; genuinely different work uses
8734
+ // set_task_tier with new_task: true.
8226
8735
  turnDispatchCount = 0;
8227
8736
  turnResearchCount = 0;
8228
8737
  turnDispatchFingerprints.clear();
@@ -8237,20 +8746,26 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8237
8746
  }
8238
8747
  turnReport = freshTurnReport();
8239
8748
  updateModeStatus();
8749
+ }
8240
8750
 
8241
- // Build dynamic agent catalog from active team only
8242
- const agentCatalog = Array.from(agentStates.values())
8243
- .map(s => `### ${displayName(s.def.name)}\n**Dispatch as:** \`${s.def.name}\`\n${s.def.description}\n**Tools:** ${s.def.tools}`)
8244
- .join("\n\n");
8751
+ const modelPacks = new Set<CapabilityPack>([...capabilityResolution.active, ...capabilityResolution.provisional]);
8752
+ const fleetActive = modelPacks.has("fleet");
8753
+ const verificationActive = modelPacks.has("verification");
8754
+ const peerActive = modelPacks.has("peer");
8755
+ const workspaceActive = modelPacks.has("workspace");
8756
+ const compactionActive = modelPacks.has("compaction");
8757
+ // Fleet roster and research policy are absent unless the fleet pack is model-visible.
8758
+ const agentCards = fleetActive ? Array.from(agentStates.values())
8759
+ .map(s => ({ id: s.def.name, text: `### ${displayName(s.def.name)}\n**Dispatch as:** \`${s.def.name}\`\n${s.def.description}\n**Tools:** ${s.def.tools}` })) : [];
8760
+ const agentCatalog = agentCards.map(card => card.text).join("\n\n");
8245
8761
 
8246
- const teamMembers = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
8762
+ const teamMembers = fleetActive ? Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ") : "";
8247
8763
 
8248
8764
  // Research personas (kind: research) the dispatcher can spawn read-only via
8249
8765
  // spawn_research. Independent of team membership.
8250
- const researchCatalog = researchPersonas.length > 0
8251
- ? researchPersonas
8252
- .map(d => `### ${displayName(d.name)}\n**Spawn as:** \`spawn_research(persona: "${d.name}")\`\n**Model:** ${resolvedModel(d) || "(dispatcher's default)"} · **Thinking:** ${resolveThinkingLevel(resolvedThinking(d))}\n${d.description}`)
8253
- .join("\n\n")
8766
+ const researchCards = fleetActive ? researchPersonas.map(d => ({ id: d.name, text: `### ${displayName(d.name)}\n**Spawn as:** \`spawn_research(persona: "${d.name}")\`\n**Model:** ${resolvedModel(d) || "(dispatcher’s default)"} · **Thinking:** ${resolveThinkingLevel(resolvedThinking(d))}\n${d.description}` })) : [];
8767
+ const researchCatalog = !fleetActive ? "" : researchCards.length > 0
8768
+ ? researchCards.map(card => card.text).join("\n\n")
8254
8769
  : "(No research personas defined. Call `spawn_research` without `persona` for an ad-hoc read-only helper.)";
8255
8770
 
8256
8771
  // Two flavors of the system prompt depending on whether ask_user is
@@ -8285,11 +8800,9 @@ ask the human. You MUST instead:
8285
8800
  - For \`ASK_USER:\` markers raised by specialists, relay the question verbatim to
8286
8801
  the user in ${userLanguage} and wait for their reply in the next turn.`;
8287
8802
 
8288
- const toolList = askUserAvailable
8289
- ? "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_task_tier` (classify the ask before the first dispatch), `team_adjust` (add/drop a team persona, sparingly), `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger), and `ask_user` (talk to the human)"
8290
- : "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_task_tier` (classify the ask before the first dispatch), `team_adjust` (add/drop a team persona, sparingly), and `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger). `ask_user` is NOT available — see the section below";
8803
+ const toolList = `these active packs: ${[...modelPacks].join(", ")}. Tools: ${pi.getActiveTools().map(name => `\`${name}\``).join(", ") || "(none)"}`;
8291
8804
 
8292
- const dispatchSection = askUserAvailable
8805
+ const dispatchSection = !fleetActive ? "" : askUserAvailable
8293
8806
  ? `- BEFORE dispatching: if anything is ambiguous, missing, or could go several valid
8294
8807
  ways, call \`ask_user\` first. Never invent constraints or "reasonable defaults"
8295
8808
  the user did not state.
@@ -8337,114 +8850,22 @@ ask the human. You MUST instead:
8337
8850
  const taskBudget = currentTaskBudget();
8338
8851
  const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
8339
8852
  const capMin = (ms: number | null) => (ms == null ? "unlimited" : `${Math.round(ms / 60_000)} min`);
8340
- const modeSection = `## Task triage (FIRST, before any dispatch)
8341
- Call \`set_task_tier\` to classify THIS turn's ask — the hub lowers the enforced caps
8342
- to min(mode, tier), so an honest tier is how you avoid burning budget on ceremony:
8343
- - trivial — one obvious, low-risk change (1 dispatch, 1 research). No ledger, no review pipeline.
8344
- - small — a contained change in familiar code (2 dispatches, 2 research). At most 3 narrow assertions.
8345
- - feature — a normal multi-step feature (6 dispatches, 4 research). Ledger + one review gate.
8346
- - project — a large, multi-phase effort (mode budget applies). Full rigor per the mode.
8347
- If you skip the call, the hub assumes "feature". Re-call it (say why) if the ask turns
8348
- out bigger — raising the tier mid-turn is allowed. Tie the tier to the USER'S ask, not
8349
- to how interesting the work is.
8350
- - A provided plan is a SPEC: when the user hands you an existing plan/task list (a PLAN
8351
- file, a numbered breakdown), do NOT re-plan or re-spec it. Skip planner and
8352
- plan-reviewer; batch the plan's tasks straight to the builder and use the plan's own
8353
- acceptance criteria as the assertions.
8354
- - A plan is a spec, NOT a mandate to execute all of it. When the plan is larger than what
8355
- the user actually asked for, do the asked-for part and say which parts you left — the
8356
- plan's existence is not consent to run its every gate. If a plan for a small ask has
8357
- grown gates, manifests, or provenance machinery nobody requested, name that to the user
8358
- instead of executing it.
8359
- - Using every persona is a smell, not a virtue: each dispatch must change the outcome.
8360
- If a dispatch's absence would change nothing, don't make it.
8361
- - THE TIER IS THE TASK'S, NOT THE TURN'S. It survives the user's next message and moves by
8362
- ratchet: lowering it is always free, raising it needs a \`reason\` naming what the ask
8363
- turned out to contain. A correction or follow-up ("no, only the one line") is the SAME
8364
- task — do not re-triage it upward, and do not pass \`new_task\` for it. At trivial/small
8365
- tiers the hub refuses planner, plan-reviewer, architect, security-auditor and
8366
- deep-researcher in code; that refusal is a signal to do the work, not to raise the tier.
8367
-
8368
- ## Execution mode: ${hubMode}${taskTier ? ` · tier: ${taskTier}` : ""}
8369
- Budgets for THIS user turn (enforced by the hub — exhausted budgets make dispatch_agent/
8370
- spawn_research refuse; a new user message opens a fresh window; /af-hub-mode switches mode):
8371
- - dispatch_agent calls: ${cap(budget.maxDispatches)} · spawn_research calls: ${cap(budget.maxResearch)}
8372
- - turn wall clock: ${capMin(budget.wallMs)} · per-run deadline: ${capMin(budget.agentTurnMs)}
8373
- Budgets for the WHOLE TASK (${TASK_BUDGET_MULTIPLIER}× the turn envelope; NOT reset by a user message —
8374
- only by /af-new-task or set_task_tier \`new_task: true\`). Spent so far:
8375
- - dispatches ${taskDispatchCount}/${cap(taskBudget.maxDispatches)} · research ${taskResearchCount}/${cap(taskBudget.maxResearch)} · active time ${Math.round(taskActiveElapsedMs() / 60_000)}/${capMin(taskBudget.wallMs)} min
8376
- - review rounds ${taskReviewRounds}/${cap(reviewRoundCap(taskTier))} (a review is a gate, not a loop)
8377
- Exhausting the TASK budget is a hard stop: it means the work outgrew its envelope three
8378
- times over, which is a re-scoping decision for the human, not something to spend through.
8379
- Plan within the budget: batch related work into ONE dispatch (a coherent slice of 4–6
8380
- plan tasks, not one dispatch per micro-task), and when a budget refusal comes back, STOP —
8381
- summarize progress and ask the user; never retry the refused call in the same turn.
8382
- Repeating an identical task to the same agent in one turn is refused in code
8383
- (duplicate guard) — use the earlier result or change the task materially.
8384
- Every task you dispatch states four things: the objective, the expected output format,
8385
- the files in scope (also pass them as \`scope\` globs — they arm the live drift watchdog),
8386
- and the boundaries (what NOT to touch). Vague tasks produce duplicated or drifting work.
8387
- ${hubMode === "fast"
8388
- ? `FAST mode rules: this is a single-specialist path for small, low-risk asks.
8389
- - Use at most ONE specialist dispatch (plus one research call only if truly needed).
8390
- - Skip the assertion ledger and the plan/review pipeline; rely on the specialist's own
8391
- verification and report back.
8392
- - Nested delegation is disabled; do not commission inventories or parity audits.
8393
- - If the task turns out to be larger than fast mode fits, say so and ask the user to
8394
- switch modes (/af-hub-mode standard) instead of burning the budget.`
8395
- : hubMode === "standard"
8396
- ? `STANDARD mode rules: rigor where it pays, batching everywhere else.
8397
- - At most ONE reconnaissance pass before building (skip it for familiar code); prefer the
8398
- specialist's own recon over a separate research run.
8399
- - Execute plans in a FEW large batches (4–6 tasks per builder dispatch), each followed by
8400
- ONE verification gate; do not re-audit everything after every small fix — re-verify only
8401
- the assertions the fix touched.
8402
- - One review gate at the end (code review; security only when the change is
8403
- security-sensitive) — not one per micro-slice.
8404
- - Reserve deep-researcher for genuinely cross-cutting questions (max 1–2 per task).`
8405
- : `STRICT mode rules: the full Verification Contract below applies — use for production
8406
- migrations, security-sensitive work, or when the user explicitly asks for it. The wide
8407
- budgets are a checkpoint, not a target: when one is hit, stop and check in with the user.`}
8408
- `;
8409
-
8410
- const fullVerificationContract = `## Verification Contract (assertion ledger)
8411
- A clearly stated requirement must never be silently dropped. You OWN a ledger of checkable
8412
- acceptance assertions; build it before you dispatch, and refuse "done" until each is proven.
8413
- - BEFORE dispatching a builder for any non-trivial task, convert the request into numbered
8414
- assertions and record them with \`set_assertions\` — one pass condition each, tagged
8415
- test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
8416
- Pass the relevant assertions VERBATIM into each dispatch.
8417
- - Every assertion NAMES ITS SOURCE (\`source: "PLAN-x.md:585-595"\`, \`"user request"\`,
8418
- \`"review finding F3"\`). The hub refuses a sourceless batch by id: a specialist told to
8419
- prove A9 must be able to read where A9 came from instead of asking you.
8420
- - Keep at most ${MAX_OPEN_ASSERTIONS} assertions OPEN at once. A large task still has many
8421
- assertions — declare the batch the next dispatches actually prove, and \`set_assertions\`
8422
- the next batch when it starts. Over the cap the hub accepts the call but warns.
8423
- - Keep assertions NARROW: one subsystem / one behavior each. Never bundle several
8424
- subsystems into one giant assertion — a compound assertion forces a full re-audit after
8425
- every small fix. After a fix, re-verify the touched assertions only.
8426
- - After each verification gate, call \`update_assertion\` with proven (and name the evidence),
8427
- unproven, or failed. Advance ONLY on proven; unproven and failed both mean not done.
8428
- - A runtime-ui assertion (visibility, placement, "appears in the table") is proven only by an
8429
- actual runtime observation — dispatch a browser-capable specialist; a static review never
8430
- closes it.
8431
- - For "make X behave like existing Y" requests, FIRST spawn_research a deep-researcher parity
8432
- inventory of every site where the exemplar is special-cased, and turn each site into an
8433
- assertion — otherwise the exemplar ships and its siblings are missed.
8434
- - On a "wrong again" correction, call \`set_assertions\` again to rebuild the ledger from the
8435
- LATEST correction before re-dispatching (a regression reset — old summaries are now suspect).
8436
- - After a context compaction your status line shows only counts (e.g. "2✓ 3○"), not the
8437
- assertion text. Call \`get_assertions\` to read the full ledger back — ids, tags, pass
8438
- conditions, and the named evidence on each proven/failed assertion — before you re-dispatch
8439
- or report done. This is your bounded read-only window onto recorded ground truth; you do not
8440
- author code.
8441
- - Specialist returns land pre-parsed in \`details.structuredReturn\` with the raw return at
8442
- \`details.returnPath\` — read the digest/path directly; NEVER spawn a research helper just to
8443
- read a return artifact you already hold.
8444
- The ledger is persisted and its status is shown to the human; it is advisory — it informs your
8445
- gating, it does not auto-block a dispatch.`;
8446
-
8447
- const verificationSection = hubMode === "fast"
8853
+ const capabilityState = [...capabilityResolution.active].map(pack => `${pack}:${capabilityResolution.reasons[pack]}`).join(", ");
8854
+ const provisionalState = capabilityResolution.provisional.map(pack => `${pack}:${capabilityResolution.reasons[pack]}`).join(", ");
8855
+ const stateCapsule = `## Current task state
8856
+ - mode: ${hubMode}${taskTier ? ` · tier: ${taskTier}` : ""}; turn dispatches: ${turnDispatchCount}; research: ${turnResearchCount}
8857
+ - task dispatches: ${taskDispatchCount}; research: ${taskResearchCount}; review rounds: ${taskReviewRounds}
8858
+ - packs active: ${capabilityState}; provisional: ${provisionalState || "none"}
8859
+ - provisional confirmation: ${capabilityResolution.provisional.filter(pack => capabilityConfirmation[pack as ConfirmableCapabilityPack] !== "declined").map(pack => `${pack} (${capabilityResolution.reasons[pack]}) → call ask_user exactly once with ${JSON.stringify(capabilityConfirmationQuestion(pack as ConfirmableCapabilityPack))}`).join("; ") || "none"}
8860
+ - budgets: dispatch ${cap(budget.maxDispatches)}, research ${cap(budget.maxResearch)}, task wall ${capMin(taskBudget.wallMs)}.`;
8861
+
8862
+ const stableModeSection = fleetActive ? `## Task triage (before dispatch)
8863
+ Call \`set_task_tier\` honestly: trivial/small work uses minimal ceremony; feature/project work uses the assertion ledger and a review gate. A provided plan is the specification, not consent to execute unrequested phases. Keep related plan work in coherent batches, pass a narrow scope, and treat a budget refusal as a stop-and-ask-human signal; code enforcement remains authoritative.` : "";
8864
+
8865
+ const fullVerificationContract = `## Verification Contract
8866
+ For non-trivial work, record at most ${MAX_OPEN_ASSERTIONS} narrow, sourced assertions before building and pass them verbatim to specialists. Advance only on named evidence; unproven/failed is not done. Runtime-UI claims require runtime observation. Use \`skills/orchestration-verification/SKILL.md\` for formats, parity inventories, and regression resets. After compaction, read the ledger before continuing.`;
8867
+
8868
+ const verificationSection = !verificationActive ? "" : hubMode === "fast"
8448
8869
  ? `## Verification (fast mode)
8449
8870
  The assertion ledger is OPTIONAL in fast mode. State what was asked, dispatch the one
8450
8871
  specialist, and verify from its returned evidence (command output, file:line). If the
@@ -8455,127 +8876,274 @@ standard/strict instead of improvising rigor here.`
8455
8876
  // Peer section only when coms initialised. Decision G4: the coms_* tools are
8456
8877
  // already in the active tool surface when ready; here we just teach the
8457
8878
  // dispatcher how and when to reach for them.
8458
- const comsSection = comsReady && identity
8879
+ const comsSection = peerActive && comsReady && identity
8459
8880
  ? `
8460
8881
  ## Peer agents (coms)
8461
- You are ALSO a peer on the coms mesh — project "${identity.project}", name "${identity.name}". Beyond
8462
- your own team you can talk to the peers in your coms POOL — the agents shown in the pool widget:
8463
- - \`coms_list\` — discover the peers in your pool (names, models, live context usage). The pool is
8464
- scoped to YOUR project and excludes private (explicit) peers. You CANNOT widen this — only the human
8465
- can, with \`/af-coms --project <name>\` or \`/af-coms --all\`. Do not ask coms_list for other projects.
8466
- - \`coms_send\` returns a msg_id; then \`coms_await\` (blocking) or \`coms_get\` (poll) reads the reply.
8467
- For long work put the SAME budget on both calls: \`coms_send(reply_timeout_ms: N, ...)\`, then
8468
- \`coms_await(timeout_ms: N, ...)\`. The send controls the receiver; await controls only your local
8469
- wait. A timeout returns pending — await/get the same msg_id again, never re-send the task.
8470
- This lets you use a peer as an on-demand subagent: send a SELF-CONTAINED task, await it, and fold the
8471
- result into your plan. A peer does NOT share your context — spell out everything it needs.
8472
- - Only peers in your pool are reachable. \`coms_send\`/\`/af-handoff\` to anyone outside it is refused. If
8473
- you need a peer that is not in the pool, ASK THE HUMAN to widen scope (\`/af-coms --project\`/\`--all\`),
8474
- then retry. Do not pass cross-project context to a peer unless the human approved that reach.
8475
- - Prefer \`dispatch_agent\`/\`spawn_research\` for in-team work; reach for coms when a task needs another
8476
- STANDING agent already in your pool (a human-driven peer, a specialist outside this team).
8477
- - A peer can also address YOU as a subagent — answer an inbound coms prompt as a normal turn.
8478
- - Some team members may be transparently served by a same-name pool peer (dispatch-policy.yaml).
8479
- This changes NOTHING for you: keep dispatching them via \`dispatch_agent\`; never coms_send the
8480
- same task to their peer as well.
8882
+ You are peer "${identity.name}" in project "${identity.project}". Use \`coms_list\` for the human-scoped pool and status; the Hub cannot widen it. Send one self-contained prompt, then await/get the returned msg_id without resending. Match send/await deadlines. Prefer team dispatch unless the task needs a standing peer, and never duplicate a dispatch to its same-name peer.
8481
8883
  `
8482
8884
  : "";
8483
8885
 
8484
8886
  const postureText = posturePrompt(posture);
8485
- const orchestratorPrompt = `${postureText.intro} You have ${toolList}.
8486
-
8487
- ## Language
8488
- ${languageLines}
8489
-
8490
- ## Native Roster: ${activeTeamName || "(none)"}
8491
- Members: ${teamMembers || "(none — add a persona before using dispatch_agent)"}
8492
- You can ONLY dispatch to agents listed below. Do not attempt to dispatch to agents
8493
- outside this team. The roster CAN change mid-session: the human via /af-agents-add,
8494
- /af-agents-drop, /af-agents-team — or you via \`team_adjust\` (add/drop with a reason)
8495
- when the current roster genuinely cannot serve the task. Use it sparingly; more
8496
- personas is usually the wrong answer.
8497
-
8498
- ## How to Work
8499
- - Analyze the user's request and break it into clear sub-tasks.
8500
- - Choose the right agent(s) for each sub-task.
8501
- ${dispatchSection}
8502
- - Choose \`backend: native\` when the user explicitly requests a local Pi specialist, \`backend: coms\` when they explicitly request a live same-name peer, and \`backend: auto\` otherwise. Never substitute one explicit backend for another.
8503
- - Review results and dispatch follow-up agents if needed.
8504
- - If a task fails, try a different agent or adjust the task description.
8505
- - Summarize the outcome for the user in ${userLanguage}.
8506
-
8507
- ${askUserBlock}
8508
-
8509
- ${modeSection}
8510
- ${verificationSection}
8511
-
8512
- ## Research helpers (read-only)
8513
- - \`spawn_research\` runs a READ-ONLY helper (read/grep/find/ls — no bash, no writes)
8514
- and returns its findings to you inline. Use it for reconnaissance, code search, and
8515
- reading docs/code BEFORE you dispatch a builder — or to fan out background research.
8516
- - Two flavours: pass \`persona\` to spawn one of the research personas listed below (it
8517
- brings its own role/model); omit \`persona\` for an ad-hoc helper (optional \`model\`).
8518
- - Match the helper to the job: use a lighter/faster persona for simple reads and a
8519
- higher-capability one for ambiguous, cross-cutting, or high-stakes research. Compare
8520
- the **Model** / **Thinking** shown for each persona below and pick deliberately.
8521
- - Specialists you dispatch are sandboxed and CANNOT spawn their own helpers. When a
8522
- specialist needs research help, YOU run \`spawn_research\`, collect the findings, and
8523
- fold them into the specialist's task — do not ask the specialist to do it itself.
8524
- - Research helpers are ephemeral and read-only, so they are always safe to run.
8525
- ${comsSection}${herdrFleetReady ? `
8526
- ## Fleet (herdr)
8527
- This session runs inside a herdr workspace and can drive panes:
8528
- - \`herdr_spawn_peer\` starts an addressable Pi persona, personaless Fleet Core, or Claude Code
8529
- peer next to you. Name-only calls inherit peers.yaml; explicit fields use the same resolver as
8530
- \`just fleet peer\`. Every peer is locked to this Hub's coms project.
8531
- - \`herdr_spawn_pane\` starts a raw command pane (for example a build watcher or server). It is
8532
- not a coms peer and has no readiness result. Spawn deliberately; every pane is human-visible.
8533
- - A spawned peer BOOTS IDLE and waits for \`coms_send\`: the spawn hands it no task.
8534
- The call waits for it to register and returns \`peer_ready\` with its coms name. Spawn one
8535
- only immediately before the first message you will send it — a peer spawned "to have it
8536
- ready" and never addressed is an empty pane named like a worker. If you sent it no work
8537
- by the end of the turn, say so and offer to close it; the hub names unaddressed
8538
- hub-spawned peers in the session digest.
8539
- - \`peer_ready: false\` is a FAILED start, not a slow one. The result carries the pane's last
8540
- output — read it, then fix the cause or close the pane and spawn again. Never \`coms_send\`
8541
- to a name that never registered, and never spawn a second peer to route around the first.
8542
- - \`herdr_read_pane\` is read-to-decide: peek at a worker/tool pane's recent output before
8543
- acting on it. It is NOT a messaging channel and NOT a status poll — \`coms_list\` already
8544
- reports each peer's \`pane_id\` and \`status\` (idle | working | booting), so check that
8545
- before sending. Prefer \`coms_send\`/\`coms_await\` for pi and bridged peers; reading screens
8546
- is the last resort for unbridged tools and post-mortems.
8547
- - \`herdr_close_pane\` kills a pane and asks the HUMAN to confirm first. Close only panes you
8548
- spawned, when their job is done or they are stuck.
8549
- - \`herdr_notify\` reaches the human via desktop notification when they are away — use it when
8550
- a long fleet task finishes or needs attention; it does not replace \`ask_user\`.
8551
- ` : ""}
8552
- ## Hard Rules
8553
- ${postureText.hardRules}
8554
- ${ambiguityRule}
8555
- - You can chain agents: spawn_research to gather context, builder to implement.
8556
- - You can dispatch the same agent multiple times with different tasks.
8557
- - Keep tasks focused — one clear objective per dispatch.
8558
-
8559
- ## Agents
8560
-
8561
- ${agentCatalog}
8562
-
8563
- ## Research personas
8564
-
8565
- ${researchCatalog}`;
8566
-
8567
- // Flavor-only persona merge (decision 9 / G4): the dispatcher persona's body
8568
- // goes FIRST, then the orchestration rules. The persona enriches the role; it
8569
- // never replaces the orchestrator prompt and never narrows the tool surface.
8570
- const systemPrompt = dispatcherPersona
8571
- ? `${dispatcherPersona.systemPrompt}\n\n${orchestratorPrompt}`
8572
- : orchestratorPrompt;
8887
+ const herdrSection = workspaceActive && herdrFleetReady ? HUB_HERDR_SECTION : "";
8888
+ const compactionSection = compactionActive ? `
8889
+ ## Context recovery
8890
+ - Context pressure is approaching or above the automatic recovery threshold. Keep tool output concise; redirect full test/package logs to files and inspect summaries or tails.
8891
+ - \`request_compaction\` is available for explicit recovery. Automatic recovery preserves task state and continues from the compaction summary.
8892
+ ` : "";
8893
+ const systemPrompt = assembleHubSystemPrompt({
8894
+ intro: postureText.intro,
8895
+ toolList,
8896
+ languageLines,
8897
+ activeTeamName,
8898
+ teamMembers,
8899
+ dispatchSection,
8900
+ userLanguage,
8901
+ askUserBlock,
8902
+ modeSection: stableModeSection,
8903
+ verificationSection,
8904
+ stateCapsule,
8905
+ comsSection,
8906
+ herdrSection,
8907
+ compactionSection,
8908
+ hardRules: postureText.hardRules,
8909
+ ambiguityRule,
8910
+ agentCatalog,
8911
+ researchCatalog,
8912
+ dispatcherPersonaPrompt: dispatcherPersona?.systemPrompt,
8913
+ });
8914
+ // Ledger is metadata-only and never written back into the replacement prompt.
8915
+ lastHubLedger = recordHubLedger(systemPrompt, namedHubLedgerParts({
8916
+ intro: postureText.intro,
8917
+ languageLines,
8918
+ teamMembers,
8919
+ agentCards,
8920
+ dispatchSection,
8921
+ modeSection: stableModeSection,
8922
+ verificationSection,
8923
+ stateCapsule,
8924
+ researchCards,
8925
+ researchCatalog,
8926
+ comsSection,
8927
+ herdrSection,
8928
+ compactionSection,
8929
+ dispatcherPersonaPrompt: dispatcherPersona?.systemPrompt,
8930
+ })).concat(CAPABILITY_PACKS.map(pack => {
8931
+ const status = capabilityResolution.active.includes(pack) ? "active"
8932
+ : capabilityResolution.provisional.includes(pack) ? "provisional"
8933
+ : (pack === "peer" && comsReady) || (pack === "workspace" && herdrFleetReady) ? "ready-inactive"
8934
+ : pack === "peer" || pack === "workspace" ? "unavailable" : "inactive";
8935
+ return component({
8936
+ id: `hub/capability/${pack}`, plane: "hub", category: "system", label: `Capability ${pack}: ${status}`,
8937
+ source: capabilityResolution.reasons[pack], persistence: "turn", visibility: "ui-only", confidence: "exact-chars", chars: 0,
8938
+ });
8939
+ }));
8573
8940
 
8574
8941
  return { systemPrompt };
8942
+ }
8943
+
8944
+ pi.on("before_agent_start", async (_event, _ctx) => buildHubSystemPrompt(true));
8945
+
8946
+ const AUTOMATIC_COMPACTION_INSTRUCTIONS = "Preserve the current goal, completed and open assertions, decisions, modified/read files, pending child or peer operations, blockers, and the concrete next step.";
8947
+ type DeferredRecoveryInput = { text: string; images?: ImageContent[]; streamingBehavior?: "steer" | "followUp" };
8948
+ let automaticCompactionPending = false;
8949
+ let automaticCompactionRunning = false;
8950
+ let deferredReplayAllowance = 0;
8951
+ const deferredRecoveryInputs: DeferredRecoveryInput[] = [];
8952
+
8953
+ function recordContextPressure(source: "message_end" | "turn_end" | "context" | "input" | "agent_settled" | "session_start" | "session_compact" | "compaction_callback", action: string, reason: string): void {
8954
+ const diagnostic = contextPressureDiagnostic(contextPressureState);
8955
+ try {
8956
+ pi.appendEntry("agent-hub-context-pressure", {
8957
+ version: 1,
8958
+ source,
8959
+ phase: diagnostic.phase,
8960
+ pressure: diagnostic.pressure,
8961
+ episode: diagnostic.episode,
8962
+ tokens: diagnostic.tokens,
8963
+ context_window: diagnostic.contextWindow,
8964
+ percent: diagnostic.percent,
8965
+ warning_percent: diagnostic.warningPercent,
8966
+ automatic_percent: diagnostic.automaticPercent,
8967
+ last_recovery_outcome: diagnostic.lastRecoveryOutcome,
8968
+ action,
8969
+ reason,
8970
+ });
8971
+ } catch { /* diagnostics are best-effort */ }
8972
+ }
8973
+
8974
+ function updateContextPressureStatus(ctx: ExtensionContext): void {
8975
+ const diagnostic = contextPressureDiagnostic(contextPressureState);
8976
+ const percent = diagnostic.percent === null ? "unknown" : `${diagnostic.percent.toFixed(1)}%`;
8977
+ ctx.ui.setStatus("context-pressure", `Context: ${contextPressureState.phase} · ${percent} · auto ${diagnostic.automaticPercent}% · last ${diagnostic.lastRecoveryOutcome}`);
8978
+ }
8979
+
8980
+ function observeContextPressure(ctx: ExtensionContext, source: "message_end" | "turn_end" | "input" | "session_start", additionalTokens = 0): "none" | "expose-compaction" | "compact-now" {
8981
+ const usage = ctx.getContextUsage();
8982
+ const contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? null;
8983
+ const tokens = usage?.tokens == null ? null : usage.tokens + Math.max(0, additionalTokens);
8984
+ const percent = tokens != null && contextWindow != null && contextWindow > 0
8985
+ ? tokens / contextWindow * 100
8986
+ : usage?.percent ?? null;
8987
+ const decision = transitionContextPressure(contextPressureState, {
8988
+ type: "usage",
8989
+ usage: { tokens, contextWindow, percent },
8990
+ });
8991
+ const previousPhase = contextPressureState.phase;
8992
+ contextPressureState = decision.state;
8993
+ updateContextPressureStatus(ctx);
8994
+ resolveIncomingCapabilities("");
8995
+ applyPostureTools();
8996
+ if (decision.action !== "none" || previousPhase !== decision.state.phase) {
8997
+ recordContextPressure(source, decision.action, decision.reason);
8998
+ }
8999
+ if (decision.action === "compact-now") {
9000
+ automaticCompactionPending = true;
9001
+ if (ctx.hasUI) ctx.ui.notify("Context reached 90%; pausing the tool loop for automatic compaction.", "warning");
9002
+ }
9003
+ return decision.action;
9004
+ }
9005
+
9006
+ function markContextCompactionSucceeded(): void {
9007
+ automaticCompactionPending = false;
9008
+ if (contextPressureState.phase === "recovered") return;
9009
+ const decision = transitionContextPressure(contextPressureState, { type: "compaction-succeeded" });
9010
+ contextPressureState = decision.state;
9011
+ if (currentCtx) updateContextPressureStatus(currentCtx);
9012
+ resolveIncomingCapabilities("");
9013
+ applyPostureTools();
9014
+ recordContextPressure("session_compact", decision.action, decision.reason);
9015
+ }
9016
+
9017
+ function replayDeferredRecoveryInputs(): void {
9018
+ if (automaticCompactionPending || automaticCompactionRunning || deferredRecoveryInputs.length === 0) return;
9019
+ const queued = deferredRecoveryInputs.splice(0);
9020
+ deferredReplayAllowance += queued.length;
9021
+ for (let index = 0; index < queued.length; index++) {
9022
+ const input = queued[index];
9023
+ const content = input.images?.length
9024
+ ? [{ type: "text" as const, text: input.text }, ...input.images]
9025
+ : input.text;
9026
+ pi.sendUserMessage(content, {
9027
+ deliverAs: index === 0 ? input.streamingBehavior : "followUp",
9028
+ });
9029
+ }
9030
+ }
9031
+
9032
+ function runAutomaticCompaction(ctx: ExtensionContext, source: "input" | "agent_settled" | "session_start"): void {
9033
+ if (!automaticCompactionPending || automaticCompactionRunning) return;
9034
+ automaticCompactionPending = false;
9035
+ automaticCompactionRunning = true;
9036
+ recordContextPressure(source, "compact-now", "automatic-threshold");
9037
+ if (ctx.hasUI) ctx.ui.notify("Automatic context compaction started.", "warning");
9038
+ ctx.compact({
9039
+ customInstructions: AUTOMATIC_COMPACTION_INSTRUCTIONS,
9040
+ onComplete: () => {
9041
+ automaticCompactionRunning = false;
9042
+ markContextCompactionSucceeded();
9043
+ if (ctx.hasUI) ctx.ui.notify("Automatic context compaction completed.", "success");
9044
+ replayDeferredRecoveryInputs();
9045
+ },
9046
+ onError: (error) => {
9047
+ automaticCompactionRunning = false;
9048
+ const failed = transitionContextPressure(contextPressureState, { type: "compaction-failed", error: "automatic compaction failed" });
9049
+ contextPressureState = failed.state;
9050
+ updateContextPressureStatus(ctx);
9051
+ resolveIncomingCapabilities("");
9052
+ applyPostureTools();
9053
+ recordContextPressure("compaction_callback", failed.action, failed.reason);
9054
+ if (ctx.hasUI) ctx.ui.notify(`Automatic compaction failed: ${error.message}. Deferred input is retained; run /compact or switch to a larger-context model.`, "error");
9055
+ },
9056
+ });
9057
+ }
9058
+
9059
+ // A finalized tool result is already present in Agent state when message_end
9060
+ // fires, so live usage includes its size. Abort synchronously here: compacting
9061
+ // directly from turn_end races the next provider request in Pi 0.84.x.
9062
+ pi.on("message_end", async (event, ctx) => {
9063
+ if (event.message.role !== "toolResult") return;
9064
+ // Pi persists the tool result after this hook, so project its model-visible
9065
+ // content onto the last trusted usage sample. JSON includes text and image
9066
+ // payload sizes while excluding non-contextual tool details.
9067
+ const projectedResultTokens = estimatePromptTokens(JSON.stringify(event.message.content ?? []));
9068
+ if (observeContextPressure(ctx, "message_end", projectedResultTokens) === "compact-now") ctx.abort();
9069
+ });
9070
+
9071
+ pi.on("turn_end", async (_event, ctx) => {
9072
+ observeContextPressure(ctx, "turn_end");
9073
+ });
9074
+
9075
+ // Abort again at Pi's pre-model context boundary. The message_end abort can
9076
+ // race agent-core's tool-loop continuation; this signal belongs to the next
9077
+ // request and prevents a network call while recovery is pending.
9078
+ pi.on("context", async (_event, ctx) => {
9079
+ if (!automaticCompactionPending) return;
9080
+ recordContextPressure("context", "compact-now", "single-flight");
9081
+ ctx.abort();
9082
+ });
9083
+
9084
+ // Wait until abort persistence and agent cleanup finish before compaction. This
9085
+ // gives prepareCompaction the finalized tool result and prevents a continuation
9086
+ // request from winning the race.
9087
+ pi.on("agent_settled", async (_event, ctx) => {
9088
+ runAutomaticCompaction(ctx, "agent_settled");
9089
+ });
9090
+
9091
+ pi.on("session_compact", async () => {
9092
+ markContextCompactionSucceeded();
9093
+ if (!automaticCompactionRunning) setTimeout(replayDeferredRecoveryInputs, 0);
8575
9094
  });
8576
9095
 
8577
9096
  // ── Persona gate: block input until a dispatcher persona is picked ──
8578
- pi.on("input", async (_event, ctx) => {
9097
+ function incomingText(event: unknown): string {
9098
+ const value = event as { text?: unknown; message?: unknown; input?: unknown } | null;
9099
+ if (typeof value?.text === "string") return value.text;
9100
+ if (typeof value?.message === "string") return value.message;
9101
+ if (typeof value?.input === "string") return value.input;
9102
+ const message = value?.message as { content?: unknown } | undefined;
9103
+ return typeof message?.content === "string" ? message.content : "";
9104
+ }
9105
+
9106
+ pi.on("input", async (event, ctx) => {
9107
+ const replayingDeferredRecoveryInput = event.source === "extension" && deferredReplayAllowance > 0;
9108
+ if (replayingDeferredRecoveryInput) {
9109
+ deferredReplayAllowance--;
9110
+ } else {
9111
+ // Session usage can already be over threshold before the first model turn
9112
+ // (resume/startup). Sample it here as a final preflight, retain the exact
9113
+ // input in memory, and replay only after compaction has completed.
9114
+ if (contextPressureState.phase === "normal") observeContextPressure(ctx, "input");
9115
+ if (automaticCompactionPending || automaticCompactionRunning || contextPressureState.phase === "failed") {
9116
+ deferredRecoveryInputs.push({
9117
+ text: event.text,
9118
+ images: event.images ? [...event.images] : undefined,
9119
+ streamingBehavior: event.streamingBehavior,
9120
+ });
9121
+ if (automaticCompactionPending && ctx.isIdle()) setTimeout(() => runAutomaticCompaction(ctx, "input"), 0);
9122
+ ctx.ui.notify(
9123
+ contextPressureState.phase === "failed"
9124
+ ? "Context recovery failed; input is retained. Run /compact or switch to a larger-context model."
9125
+ : "Input retained until automatic context recovery completes.",
9126
+ "warning",
9127
+ );
9128
+ return { action: "handled" as const };
9129
+ }
9130
+ }
9131
+ if (replayingDeferredRecoveryInput && modelWorkBlockedByRosterRecovery(ctx)) {
9132
+ // Compaction succeeded, but this resumed orchestrator still needs an
9133
+ // explicit roster decision. Retain the exact replay payload again and
9134
+ // resume it only after the live recovery command clears the gate.
9135
+ deferredRecoveryInputs.push({
9136
+ text: event.text,
9137
+ images: event.images ? [...event.images] : undefined,
9138
+ streamingBehavior: event.streamingBehavior,
9139
+ });
9140
+ return { action: "handled" as const };
9141
+ }
9142
+ if (modelWorkBlockedByRosterRecovery(ctx)) return { action: "handled" as const };
9143
+ // Pi routes normal, resumed, and remote prompts through this hook before
9144
+ // before_agent_start, so this local resolver changes the same request's surface.
9145
+ resolveIncomingCapabilities(incomingText(event));
9146
+ applyPostureTools();
8579
9147
  if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
8580
9148
  ctx.ui.notify("Pick a dispatcher persona first (see the select dialog).", "warning");
8581
9149
  return { action: "handled" as const };
@@ -8587,6 +9155,14 @@ ${researchCatalog}`;
8587
9155
 
8588
9156
  pi.on("session_start", async (_event, _ctx) => {
8589
9157
  registerVersionStatus(_ctx);
9158
+ contextPressureState = createContextPressureState();
9159
+ updateContextPressureStatus(_ctx);
9160
+ automaticCompactionPending = false;
9161
+ automaticCompactionRunning = false;
9162
+ deferredReplayAllowance = 0;
9163
+ deferredRecoveryInputs.length = 0;
9164
+ rosterRecoveryRequired = false;
9165
+ rosterRecoveryDiagnostic = "";
8590
9166
  // Capture the configured surface before Agent Hub applies either posture.
8591
9167
  // Operator mode restores this baseline (minus gated Hub-owned tools).
8592
9168
  baselineTools = pi.getActiveTools();
@@ -8601,8 +9177,15 @@ ${researchCatalog}`;
8601
9177
  executionHistory.length = 0;
8602
9178
  currentOrchestratorEntry = null;
8603
9179
  turnActive = false;
9180
+ currentTurnStartedAt = 0;
9181
+ taskClock = createTaskClock();
8604
9182
  askUserStarts.clear();
8605
9183
  turnAskUserIntervals.length = 0;
9184
+ turnBudgetAskUserWaitMs = 0;
9185
+ turnContinuationCount = 0;
9186
+ taskContinuationCount = 0;
9187
+ pendingBudgetContinuation = null;
9188
+ budgetContinuationAsks.clear();
8606
9189
  if (widgetCtx) {
8607
9190
  widgetCtx.ui.setWidget("agent-team", undefined);
8608
9191
  widgetCtx.ui.setWidget("agent-research", undefined);
@@ -8893,6 +9476,7 @@ ${researchCatalog}`;
8893
9476
  userLanguage = overrides.language;
8894
9477
  researchKeep = overrides.researchKeep;
8895
9478
  reconSearchTimeoutMs = overrides.reconSearchTimeoutMs;
9479
+ const previousMode = hubMode;
8896
9480
  hubMode = overrides.hubMode;
8897
9481
  budgetOverrides = overrides.budgetOverrides;
8898
9482
  watchdogSetting = overrides.watchdogSetting;
@@ -8902,6 +9486,13 @@ ${researchCatalog}`;
8902
9486
  // A new session is a new task by definition.
8903
9487
  resetTaskWindow(null);
8904
9488
  updateModeStatus();
9489
+ appendHubModeEntry({
9490
+ previousMode,
9491
+ mode: hubMode,
9492
+ source: overrides.hubModeSource,
9493
+ overrideFile: overrides.hubModeSource === "project-override" ? ".ai/agent-fleet-overrides.md" : null,
9494
+ ctx: _ctx,
9495
+ });
8905
9496
  if (overrides.warnings.length > 0) {
8906
9497
  _ctx.ui.notify(`agent-fleet-overrides warnings:\n${overrides.warnings.join("\n")}`, "warning");
8907
9498
  }
@@ -8993,22 +9584,49 @@ ${researchCatalog}`;
8993
9584
  personaGateEnabled = overrides.personaGate && orchestratorPersonas.length > 0;
8994
9585
  personaGateSatisfied = !personaGateEnabled;
8995
9586
 
8996
- // A roster is opt-in. Resolve it before posture so --agent-team can imply
8997
- // orchestrator while an explicit --posture operator still wins.
9587
+ // Explicit CLI selection wins; otherwise restore only the canonical team name
9588
+ // and re-resolve it against current teams.yaml/persona files. An explicit
9589
+ // operator posture suppresses an ambient persisted roster unless --agent-team
9590
+ // was also supplied.
8998
9591
  agentStates.clear();
8999
9592
  activeTeamName = "";
9000
9593
  comsMissNotified.clear();
9001
9594
  recomputeGrid();
9002
- const startupRoster = resolveStartupRoster(teams, pi.getFlag("agent-team"));
9595
+ const sessionEntries = _ctx.sessionManager.getEntries();
9596
+ const explicitPosture = pi.getFlag("posture");
9597
+ const explicitRoster = pi.getFlag("agent-team");
9598
+ const hasExplicitRoster = typeof explicitRoster === "string" && explicitRoster.trim() !== "";
9599
+ const startupRoster = resolveSessionRoster({
9600
+ teams,
9601
+ entries: sessionEntries,
9602
+ explicitRoster,
9603
+ availablePersonas: allAgentDefs.map(def => def.name),
9604
+ includePersisted: !(explicitPosture === "operator" && !hasExplicitRoster),
9605
+ });
9003
9606
  posture = resolveSessionPosture({
9004
- entries: _ctx.sessionManager.getEntries(),
9005
- explicitPosture: pi.getFlag("posture"),
9006
- hasExplicitRoster: startupRoster !== null,
9607
+ entries: sessionEntries,
9608
+ explicitPosture,
9609
+ hasExplicitRoster: startupRoster.source === "explicit",
9007
9610
  });
9008
- if (orchestratorNeedsRoster(posture, startupRoster?.members.length ?? 0)) {
9009
- throw new Error("Orchestrator posture requires --agent-team <name> with at least one native specialist.");
9611
+ if (startupRoster.roster) {
9612
+ activateTeam(startupRoster.roster.name);
9613
+ persistActiveRoster();
9614
+ }
9615
+ rosterRecoveryRequired = orchestratorNeedsRoster(posture, agentStates.size);
9616
+ rosterRecoveryDiagnostic = rosterRecoveryRequired
9617
+ ? startupRoster.diagnostic || "Persisted orchestrator posture has no native roster."
9618
+ : "";
9619
+ if (startupRoster.diagnostic) {
9620
+ _ctx.ui.notify(
9621
+ `${startupRoster.diagnostic} ${rosterRecoveryRequired ? "Model input is blocked until you select /af-agents-team, restart with --agent-team <name>, or switch explicitly with --posture operator." : "Continuing without that roster."}`,
9622
+ rosterRecoveryRequired ? "error" : "warning",
9623
+ );
9624
+ } else if (rosterRecoveryRequired) {
9625
+ _ctx.ui.notify(
9626
+ `${rosterRecoveryDiagnostic} Model input is blocked until you select /af-agents-team, restart with --agent-team <name>, or switch explicitly with --posture operator.`,
9627
+ "error",
9628
+ );
9010
9629
  }
9011
- if (startupRoster) activateTeam(startupRoster.name);
9012
9630
 
9013
9631
  // Probe for `ask_user` (registered by the `pi-ask-user` companion package
9014
9632
  // when installed). Action methods like getAllTools are runtime-only, so
@@ -9018,7 +9636,15 @@ ${researchCatalog}`;
9018
9636
  // Fleet tools are available only inside a herdr pane with a live server.
9019
9637
  // The posture policy adds gated groups without activating unavailable tools.
9020
9638
  herdrFleetReady = herdrPaneId() !== null && (await herdrAvailable()) !== null;
9639
+ const persistedCapabilities = latestPersistedCapabilityState(_ctx.sessionManager.getEntries());
9640
+ taskCapabilityPacks = persistedCapabilities?.taskPacks ?? [];
9641
+ taskProvisionalPacks = persistedCapabilities?.provisional ?? [];
9642
+ capabilityConfirmation = persistedCapabilities?.confirmation ?? {};
9643
+ resolveIncomingCapabilities("");
9021
9644
  applyPostureTools();
9645
+ if (observeContextPressure(_ctx, "session_start") === "compact-now") {
9646
+ setTimeout(() => runAutomaticCompaction(_ctx, "session_start"), 0);
9647
+ }
9022
9648
  updatePostureStatus(_ctx);
9023
9649
 
9024
9650
  _ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"} (${agentStates.size})`);
@@ -9061,6 +9687,7 @@ ${researchCatalog}`;
9061
9687
  `/af-agents-team Select a team\n` +
9062
9688
  `/af-agents-list Open Fleet Dashboard\n` +
9063
9689
  `/af-agents-history Timeline of agent runs — durations, parallel markers, grand total\n` +
9690
+ `/af-context Read-only full-screen context budget diagnostic\n` +
9064
9691
  `/af-agent-model <persona>[.<role>] Switch a persona's or sub-role's model\n` +
9065
9692
  `/af-agent-model-thinking <persona> Switch a persona's thinking level\n` +
9066
9693
  `/af-models [profile] Apply a named model profile to the team\n` +
@@ -9084,7 +9711,7 @@ ${researchCatalog}`;
9084
9711
 
9085
9712
  // The persona gate restricts only orchestrator posture. Operators can work
9086
9713
  // directly and choose a dispatcher persona later without being blocked.
9087
- if (posture === "orchestrator" && personaGateEnabled) {
9714
+ if (posture === "orchestrator" && personaGateEnabled && !rosterRecoveryRequired) {
9088
9715
  void pickDispatcherPersona(_ctx);
9089
9716
  }
9090
9717
 
@@ -9138,15 +9765,18 @@ ${researchCatalog}`;
9138
9765
  // When this agent was addressed by a peer (an inbound prompt in the queue), the
9139
9766
  // turn's final assistant text becomes the response we ship back to the sender.
9140
9767
  pi.on("agent_end", async (_event, ctx) => {
9141
- // Close the /af-agents-history dispatcher turn (if this turn opened one). The
9142
- // orchestrator entry's span covers all of its dispatches plus the wrap-up.
9768
+ // Close both the task clock and /af-agents-history dispatcher turn at the
9769
+ // actual end event, so time awaiting the next user message is never charged.
9770
+ const turnEndedAt = Date.now();
9771
+ closeTurnActiveTime(turnEndedAt);
9143
9772
  turnActive = false;
9144
9773
  if (currentOrchestratorEntry) {
9145
- currentOrchestratorEntry.endedAt = Date.now();
9774
+ currentOrchestratorEntry.endedAt = turnEndedAt;
9146
9775
  if (currentOrchestratorEntry.status === "running") currentOrchestratorEntry.status = "done";
9147
9776
  currentOrchestratorEntry = null;
9148
9777
  historyRender?.();
9149
9778
  }
9779
+ currentTurnStartedAt = 0;
9150
9780
 
9151
9781
  // End-of-turn sweep: a peer spawned this turn and never sent to is still
9152
9782
  // running. Named once per turn it stays unaddressed; the close itself is