@chankov/agent-fleet 1.0.1 → 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 (316) hide show
  1. package/.pi/extensions/package-lock.json +77 -45
  2. package/.pi/harnesses/agent-hub/README.md +109 -18
  3. package/.pi/harnesses/agent-hub/budget-continuation.ts +73 -0
  4. package/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  5. package/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  6. package/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  7. package/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  8. package/.pi/harnesses/agent-hub/hub-state-audit.js +18 -0
  9. package/.pi/harnesses/agent-hub/index.ts +988 -422
  10. package/.pi/harnesses/agent-hub/package.json +1 -1
  11. package/.pi/harnesses/agent-hub/posture.ts +72 -17
  12. package/.pi/harnesses/agent-hub/run-budget.js +12 -13
  13. package/.pi/harnesses/agent-hub/spawn.ts +14 -2
  14. package/.pi/harnesses/ask-user-remote/index.ts +59 -4
  15. package/.pi/harnesses/coms/package.json +1 -1
  16. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  17. package/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  18. package/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  19. package/.pi/harnesses/lib/context-budget-view.ts +107 -0
  20. package/.pi/harnesses/lib/context-budget.ts +114 -0
  21. package/.pi/harnesses/lib/fleet-detail-view.ts +92 -2
  22. package/.pi/harnesses/package-lock.json +73 -80
  23. package/.versions/1.0.2/.pi/agents/dispatch-policy.yaml +32 -0
  24. package/.versions/1.0.2/.pi/agents/model-profiles.yaml +27 -0
  25. package/.versions/1.0.2/.pi/agents/peers.yaml +142 -0
  26. package/.versions/1.0.2/.pi/agents/teams.yaml +41 -0
  27. package/.versions/1.0.2/.pi/damage-control-rules.yaml +297 -0
  28. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/README.md +57 -0
  29. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  30. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  31. package/.versions/1.0.2/.pi/extensions/btw/README.md +120 -0
  32. package/.versions/1.0.2/.pi/extensions/btw/index.ts +914 -0
  33. package/.versions/1.0.2/.pi/extensions/btw/package.json +6 -0
  34. package/.versions/1.0.2/.pi/extensions/btw/state.js +179 -0
  35. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  36. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  37. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  38. package/.versions/1.0.2/.pi/extensions/compact-and-continue/README.md +42 -0
  39. package/.versions/1.0.2/.pi/extensions/compact-and-continue/index.ts +120 -0
  40. package/.versions/1.0.2/.pi/extensions/compact-and-continue/package.json +6 -0
  41. package/.versions/1.0.2/.pi/extensions/mcp-bridge/README.md +46 -0
  42. package/.versions/1.0.2/.pi/extensions/mcp-bridge/index.ts +206 -0
  43. package/.versions/1.0.2/.pi/extensions/mcp-bridge/package.json +6 -0
  44. package/.versions/1.0.2/.pi/extensions/package-lock.json +1175 -0
  45. package/.versions/1.0.2/.pi/extensions/package.json +9 -0
  46. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/README.md +205 -0
  47. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/config.ts +198 -0
  48. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  49. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/index.ts +248 -0
  50. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/package.json +6 -0
  51. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  52. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  53. package/.versions/1.0.2/.pi/harnesses/agent-hub/README.md +1156 -0
  54. package/.versions/1.0.2/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  55. package/.versions/1.0.2/.pi/harnesses/agent-hub/artifacts.js +146 -0
  56. package/.versions/1.0.2/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  57. package/.versions/1.0.2/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  58. package/.versions/1.0.2/.pi/harnesses/agent-hub/budget-continuation.ts +73 -0
  59. package/.versions/1.0.2/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  60. package/.versions/1.0.2/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  61. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  62. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  63. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-window.js +106 -0
  64. package/.versions/1.0.2/.pi/harnesses/agent-hub/delegate.ts +435 -0
  65. package/.versions/1.0.2/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  66. package/.versions/1.0.2/.pi/harnesses/agent-hub/drift-watchdog.js +211 -0
  67. package/.versions/1.0.2/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  68. package/.versions/1.0.2/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  69. package/.versions/1.0.2/.pi/harnesses/agent-hub/footer.ts +35 -0
  70. package/.versions/1.0.2/.pi/harnesses/agent-hub/helpers.ts +266 -0
  71. package/.versions/1.0.2/.pi/harnesses/agent-hub/hub-state-audit.js +73 -0
  72. package/.versions/1.0.2/.pi/harnesses/agent-hub/index.ts +9909 -0
  73. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  74. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  75. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  76. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  77. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  78. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  79. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  80. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  81. package/.versions/1.0.2/.pi/harnesses/agent-hub/package.json +7 -0
  82. package/.versions/1.0.2/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  83. package/.versions/1.0.2/.pi/harnesses/agent-hub/posture.ts +158 -0
  84. package/.versions/1.0.2/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  85. package/.versions/1.0.2/.pi/harnesses/agent-hub/research-retention.js +34 -0
  86. package/.versions/1.0.2/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  87. package/.versions/1.0.2/.pi/harnesses/agent-hub/return-contract.js +293 -0
  88. package/.versions/1.0.2/.pi/harnesses/agent-hub/return-extract.js +75 -0
  89. package/.versions/1.0.2/.pi/harnesses/agent-hub/review-findings.js +102 -0
  90. package/.versions/1.0.2/.pi/harnesses/agent-hub/run-budget.js +539 -0
  91. package/.versions/1.0.2/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  92. package/.versions/1.0.2/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  93. package/.versions/1.0.2/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  94. package/.versions/1.0.2/.pi/harnesses/agent-hub/session-health.js +110 -0
  95. package/.versions/1.0.2/.pi/harnesses/agent-hub/spawn.ts +366 -0
  96. package/.versions/1.0.2/.pi/harnesses/agent-hub/version.ts +42 -0
  97. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/README.md +53 -0
  98. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/index.ts +532 -0
  99. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  100. package/.versions/1.0.2/.pi/harnesses/coms/README.md +100 -0
  101. package/.versions/1.0.2/.pi/harnesses/coms/index.ts +1767 -0
  102. package/.versions/1.0.2/.pi/harnesses/coms/package.json +7 -0
  103. package/.versions/1.0.2/.pi/harnesses/coms/version.ts +42 -0
  104. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/README.md +124 -0
  105. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/index.ts +536 -0
  106. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/package.json +7 -0
  107. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/version.ts +42 -0
  108. package/.versions/1.0.2/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  109. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  110. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  111. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-view.ts +107 -0
  112. package/.versions/1.0.2/.pi/harnesses/lib/context-budget.ts +114 -0
  113. package/.versions/1.0.2/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  114. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  115. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  116. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  117. package/.versions/1.0.2/.pi/harnesses/lib/fleet-dashboard-ops.ts +155 -0
  118. package/.versions/1.0.2/.pi/harnesses/lib/fleet-dashboard-view.ts +140 -0
  119. package/.versions/1.0.2/.pi/harnesses/lib/fleet-detail-view.ts +133 -0
  120. package/.versions/1.0.2/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  121. package/.versions/1.0.2/.pi/harnesses/lib/fleet-panel.ts +34 -0
  122. package/.versions/1.0.2/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  123. package/.versions/1.0.2/.pi/harnesses/lib/fleet-selection.ts +24 -0
  124. package/.versions/1.0.2/.pi/harnesses/lib/herdr-client.ts +472 -0
  125. package/.versions/1.0.2/.pi/harnesses/lib/herdr-presence.ts +399 -0
  126. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  127. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  128. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  129. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  130. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  131. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  132. package/.versions/1.0.2/.pi/harnesses/lib/spawned-peers.js +190 -0
  133. package/.versions/1.0.2/.pi/harnesses/package-lock.json +2039 -0
  134. package/.versions/1.0.2/.pi/harnesses/package.json +10 -0
  135. package/.versions/1.0.2/.pi/prompts/af-build.md +24 -0
  136. package/.versions/1.0.2/.pi/prompts/af-code-simplify.md +22 -0
  137. package/.versions/1.0.2/.pi/prompts/af-plan.md +16 -0
  138. package/.versions/1.0.2/.pi/prompts/af-review.md +16 -0
  139. package/.versions/1.0.2/.pi/prompts/af-set-hermes-telegram.md +15 -0
  140. package/.versions/1.0.2/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  141. package/.versions/1.0.2/.pi/prompts/af-ship.md +17 -0
  142. package/.versions/1.0.2/.pi/prompts/af-spec.md +15 -0
  143. package/.versions/1.0.2/.pi/prompts/af-test.md +19 -0
  144. package/.versions/1.0.2/.pi/skills/bowser/SKILL.md +145 -0
  145. package/.versions/1.0.2/.version +1 -0
  146. package/.versions/1.0.2/agents/architect.md +24 -0
  147. package/.versions/1.0.2/agents/bowser.md +27 -0
  148. package/.versions/1.0.2/agents/builder.md +54 -0
  149. package/.versions/1.0.2/agents/code-reviewer.md +208 -0
  150. package/.versions/1.0.2/agents/deep-researcher.md +32 -0
  151. package/.versions/1.0.2/agents/documenter.md +18 -0
  152. package/.versions/1.0.2/agents/orchestrator.md +20 -0
  153. package/.versions/1.0.2/agents/plan-reviewer.md +83 -0
  154. package/.versions/1.0.2/agents/planner.md +70 -0
  155. package/.versions/1.0.2/agents/releaser.md +24 -0
  156. package/.versions/1.0.2/agents/researcher.md +28 -0
  157. package/.versions/1.0.2/agents/security-auditor.md +167 -0
  158. package/.versions/1.0.2/agents/test-engineer.md +153 -0
  159. package/.versions/1.0.2/agents/web-debugger.md +43 -0
  160. package/.versions/1.0.2/agents/web-performance-auditor.md +193 -0
  161. package/.versions/1.0.2/bin/catalog/harness-runtime-closure.json +38 -0
  162. package/.versions/1.0.2/codex/CONDUCTOR.md +148 -0
  163. package/.versions/1.0.2/docs/ARCHITECTURE.md +369 -0
  164. package/.versions/1.0.2/docs/agent-fleet-setup.md +468 -0
  165. package/.versions/1.0.2/docs/claude-code-coms-bridge.md +128 -0
  166. package/.versions/1.0.2/docs/codex-remote-conductor.md +170 -0
  167. package/.versions/1.0.2/docs/coms-hermes-bridge.md +189 -0
  168. package/.versions/1.0.2/docs/getting-started.md +98 -0
  169. package/.versions/1.0.2/docs/npm-install.md +292 -0
  170. package/.versions/1.0.2/docs/pi-extensions.md +439 -0
  171. package/.versions/1.0.2/docs/pi-setup.md +74 -0
  172. package/.versions/1.0.2/docs/skill-anatomy.md +150 -0
  173. package/.versions/1.0.2/hermes/README.md +347 -0
  174. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  175. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  176. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  177. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  178. package/.versions/1.0.2/hermes/gates/gate-o-capability.md +8 -0
  179. package/.versions/1.0.2/hermes/gates/gate-o-validator-fixtures.json +1 -0
  180. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  181. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  182. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  183. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  184. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  185. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  186. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  187. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  188. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  189. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  190. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  191. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  192. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  193. package/.versions/1.0.2/hermes/skills/hub-conductor/SKILL.md +84 -0
  194. package/.versions/1.0.2/hermes/skills/hub-liaison/SKILL.md +84 -0
  195. package/.versions/1.0.2/hermes/skills/hub-watchdog/SKILL.md +76 -0
  196. package/.versions/1.0.2/hermes/skills/hub-watchdog/manifest.json +1 -0
  197. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  198. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  199. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  200. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  201. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  202. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  203. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  204. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  205. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  206. package/.versions/1.0.2/hermes/watchdog-tests/__init__.py +0 -0
  207. package/.versions/1.0.2/hooks/coms-stop-hook.mjs +84 -0
  208. package/.versions/1.0.2/install-manifest.json +2745 -0
  209. package/.versions/1.0.2/justfile +272 -0
  210. package/.versions/1.0.2/manifest-meta.json +882 -0
  211. package/.versions/1.0.2/references/accessibility-checklist.md +160 -0
  212. package/.versions/1.0.2/references/definition-of-done.md +67 -0
  213. package/.versions/1.0.2/references/fleet-coordination-patterns.md +151 -0
  214. package/.versions/1.0.2/references/observability-checklist.md +91 -0
  215. package/.versions/1.0.2/references/orchestration-patterns.md +370 -0
  216. package/.versions/1.0.2/references/performance-checklist.md +153 -0
  217. package/.versions/1.0.2/references/prompting-patterns.md +380 -0
  218. package/.versions/1.0.2/references/security-checklist.md +179 -0
  219. package/.versions/1.0.2/references/testing-patterns.md +236 -0
  220. package/.versions/1.0.2/scripts/codex-conductor.ts +41 -0
  221. package/.versions/1.0.2/scripts/codex-remote-control.ts +167 -0
  222. package/.versions/1.0.2/scripts/coms-claude-bridge.ts +411 -0
  223. package/.versions/1.0.2/scripts/coms-cli.ts +484 -0
  224. package/.versions/1.0.2/scripts/coms-hermes-bridge.ts +413 -0
  225. package/.versions/1.0.2/scripts/fleet.ts +185 -0
  226. package/.versions/1.0.2/scripts/hermes-monitor-capability-runner.ts +25 -0
  227. package/.versions/1.0.2/scripts/hermes-monitor-scenario.ts +474 -0
  228. package/.versions/1.0.2/scripts/hermes-watchdog-capability-probe.ts +45 -0
  229. package/.versions/1.0.2/scripts/install-hermes-plugin.sh +180 -0
  230. package/.versions/1.0.2/scripts/lib/claude-bridge-core.ts +210 -0
  231. package/.versions/1.0.2/scripts/lib/codex-conductor.ts +88 -0
  232. package/.versions/1.0.2/scripts/lib/codex-remote-control.ts +480 -0
  233. package/.versions/1.0.2/scripts/lib/coms-envelope.ts +582 -0
  234. package/.versions/1.0.2/scripts/lib/fake-herdr-server.ts +88 -0
  235. package/.versions/1.0.2/scripts/lib/fleet-command.ts +266 -0
  236. package/.versions/1.0.2/scripts/lib/herdr-layout.ts +281 -0
  237. package/.versions/1.0.2/scripts/lib/hermes-bridge-core.ts +241 -0
  238. package/.versions/1.0.2/scripts/lib/hermes-monitor-events.ts +1 -0
  239. package/.versions/1.0.2/scripts/lib/hermes-monitor-herdr.ts +2 -0
  240. package/.versions/1.0.2/scripts/lib/hermes-monitor-model.ts +3 -0
  241. package/.versions/1.0.2/scripts/lib/hermes-monitor-registry.ts +2 -0
  242. package/.versions/1.0.2/scripts/lib/hermes-monitor-socket.ts +2 -0
  243. package/.versions/1.0.2/scripts/lib/hermes-monitor-store.ts +2 -0
  244. package/.versions/1.0.2/scripts/lib/monitor-env.ts +146 -0
  245. package/.versions/1.0.2/scripts/lib/peer-launch.ts +318 -0
  246. package/.versions/1.0.2/scripts/lib/persona-banner.ts +62 -0
  247. package/.versions/1.0.2/scripts/lib/spawn-stagger.ts +101 -0
  248. package/.versions/1.0.2/scripts/lib/team-project.ts +213 -0
  249. package/.versions/1.0.2/scripts/lib/team-snapshot.ts +147 -0
  250. package/.versions/1.0.2/scripts/peer-banner.ts +40 -0
  251. package/.versions/1.0.2/scripts/peer-launch.ts +259 -0
  252. package/.versions/1.0.2/scripts/team-snapshot.ts +237 -0
  253. package/.versions/1.0.2/scripts/team-up.ts +406 -0
  254. package/.versions/1.0.2/skills/_internal/grilling.md +11 -0
  255. package/.versions/1.0.2/skills/browser-testing-with-devtools/SKILL.md +351 -0
  256. package/.versions/1.0.2/skills/code-review-and-quality/SKILL.md +381 -0
  257. package/.versions/1.0.2/skills/compound-learning/SKILL.md +137 -0
  258. package/.versions/1.0.2/skills/context-engineering/SKILL.md +291 -0
  259. package/.versions/1.0.2/skills/deprecation-and-migration/SKILL.md +206 -0
  260. package/.versions/1.0.2/skills/designing-agents/SKILL.md +394 -0
  261. package/.versions/1.0.2/skills/designing-agents/pi-harness-authoring.md +222 -0
  262. package/.versions/1.0.2/skills/frontend-ui-engineering/SKILL.md +328 -0
  263. package/.versions/1.0.2/skills/git-workflow-and-versioning/SKILL.md +316 -0
  264. package/.versions/1.0.2/skills/idea-refine/SKILL.md +182 -0
  265. package/.versions/1.0.2/skills/idea-refine/examples.md +238 -0
  266. package/.versions/1.0.2/skills/idea-refine/frameworks.md +99 -0
  267. package/.versions/1.0.2/skills/idea-refine/refinement-criteria.md +113 -0
  268. package/.versions/1.0.2/skills/idea-refine/scripts/idea-refine.sh +15 -0
  269. package/.versions/1.0.2/skills/incremental-implementation/SKILL.md +287 -0
  270. package/.versions/1.0.2/skills/interview-me/SKILL.md +226 -0
  271. package/.versions/1.0.2/skills/orchestration-verification/SKILL.md +181 -0
  272. package/.versions/1.0.2/skills/peer-coms/SKILL.md +90 -0
  273. package/.versions/1.0.2/skills/performance-optimization/SKILL.md +350 -0
  274. package/.versions/1.0.2/skills/planning-and-task-breakdown/SKILL.md +254 -0
  275. package/.versions/1.0.2/skills/security-and-hardening/SKILL.md +461 -0
  276. package/.versions/1.0.2/skills/spec-driven-development/SKILL.md +257 -0
  277. package/.versions/1.0.2/skills/using-agent-skills/SKILL.md +199 -0
  278. package/.versions/1.0.2/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  279. package/.versions/1.0.2/vendor/agent-skills-upstream/LICENSE +21 -0
  280. package/.versions/1.0.2/vendor/agent-skills-upstream/README.md +11 -0
  281. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  282. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  283. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  284. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  285. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  286. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  287. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  288. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  289. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  290. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  291. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  292. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  293. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  294. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  295. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  296. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  297. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  298. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  299. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  300. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  301. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  302. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  303. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  304. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  305. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  306. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  307. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  308. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  309. package/CHANGELOG.md +9 -0
  310. package/README.md +4 -2
  311. package/agents/orchestrator.md +4 -56
  312. package/docs/ARCHITECTURE.md +48 -16
  313. package/docs/agent-fleet-setup.md +33 -2
  314. package/docs/pi-extensions.md +29 -2
  315. package/install-manifest.json +2 -2
  316. 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,9 +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 { applyModelOverride, clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
92
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";
93
- import { buildHubAuditIdentity, buildHubModeAudit, buildTaskResetAudit } from "./hub-state-audit.js";
94
+ import { buildBudgetContinuationAudit, buildHubAuditIdentity, buildHubModeAudit, buildTaskResetAudit } from "./hub-state-audit.js";
94
95
  import { countReviewFindings, findingBudgetNotice } from "./review-findings.js";
95
96
  import { checkDocsLane, docsLaneNotice } from "./docs-lane.js";
96
97
  import { checkExternalBlockerGate, externalBlockedProtocol, extractExternalBlockers } from "./external-blocker.js";
@@ -115,7 +116,12 @@ import { crossCheck, deliveryDisposition, extractAssertionIds, parseDeliveredRet
115
116
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
116
117
  import { validateEvidence } from "./evidence-rules.js";
117
118
  import { comsRequiredRefusal, explicitComsRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
118
- 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";
119
125
  import { buildHubPeerSpawnPlan, launchHubPeerInPane } from "./peer-spawn-plan.ts";
120
126
  import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
121
127
  import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
@@ -136,8 +142,21 @@ import { createPanelResources } from "../lib/fleet-panel.ts";
136
142
  import { buildFleetRows, fleetTiming, summarise, unionMs, type DelegateInput, type FleetRow, type FleetSource, type PeerInput, type ResearchInput, type SpecialistInput } from "../lib/fleet-read-model.ts";
137
143
  import { attachFleetDashboardTicker, compactWidgetsEnabled, gridColumnsForItems, gridColumnsForSize, liveTimeline, renderCardGrid, resolveFleetKill, resolveFleetRestart } from "../lib/fleet-dashboard-ops.ts";
138
144
  import { dashboardTransition, renderFleetDashboard, FLEET_CHROME_ROWS, type DashboardConfirm } from "../lib/fleet-dashboard-view.ts";
139
- 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";
140
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";
141
160
  import { parseEnvFile, resolveEnvFilePath } from "../../../scripts/lib/herdr-layout.ts";
142
161
  import { worktreeTag } from "../../../scripts/lib/team-project.ts";
143
162
  import { STAGGER_ENV_VAR, WARMUP_SECONDS, oauthNeedsWarmup } from "../../../scripts/lib/spawn-stagger.ts";
@@ -238,6 +257,8 @@ interface AgentState {
238
257
  // a percentage cannot be compared against a window it was not divided by.
239
258
  contextTokens: number;
240
259
  sessionFile: string | null;
260
+ /** Metadata-only child context retained across research-pause resume. */
261
+ specialistManifest?: SpecialistContextManifest;
241
262
  runCount: number;
242
263
  // Runs served by the CURRENT accumulated session (-c resume chain). Reset on
243
264
  // recycle; drives shouldRecycleSession together with the measured contextPct.
@@ -298,6 +319,7 @@ interface ResearchState {
298
319
  elapsed: number;
299
320
  lastWork: string;
300
321
  contextPct: number;
322
+ contextTokens: number;
301
323
  sessionFile: string | null; // set after a successful run → enables `-c` resume
302
324
  turnCount: number;
303
325
  finishedAt?: number; // last time a run ended (any status) — LRU key for retention
@@ -429,7 +451,7 @@ function extractNeedsResearch(output: string): string[] {
429
451
  // max-dispatches-per-turn: <n>|off — dispatch_agent calls allowed per user turn
430
452
  // (replaces the mode default; "off" = unlimited).
431
453
  // max-research-per-turn: <n>|off — spawn_research calls allowed per user turn.
432
- // 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).
433
455
  // agent-turn-timeout-s: <n>|off — whole-run deadline for each spawned
434
456
  // specialist/research/delegate run (not per tool).
435
457
  // session-recycle-runs: <n>|off — recycle a specialist's accumulated session
@@ -873,18 +895,6 @@ const CONTEXT_WARN_THRESHOLD = 70;
873
895
  // child spawns reserved tree-wide for a dispatch.
874
896
  const DELEGATE_CALL_BUDGET = DELEGATE_TREE_SPAWN_BUDGET;
875
897
 
876
- // Appended to every research helper's system prompt so it knows its sandbox and how to
877
- // report. Kept separate from the dispatcher's clarification protocol: helpers don't
878
- // bubble up ASK_USER — they report findings and the dispatcher decides what to do.
879
- const RESEARCH_PROTOCOL = `
880
-
881
- ## You are a READ-ONLY research helper
882
- You can ONLY read, search, and list files (tools: read, grep, find, ls). You CANNOT
883
- edit, write, or run shell/bash commands — they are not available to you. Investigate
884
- what you're asked, then report findings concisely, citing concrete locations as
885
- path:line. Do not propose or attempt edits; another agent will act on your findings.
886
- If something can't be found or is ambiguous, say so plainly rather than guessing.`;
887
-
888
898
  // System prompt for an ad-hoc (anonymous) research helper — one with no persona file.
889
899
  const ANON_RESEARCH_PROMPT = `# Research Helper
890
900
 
@@ -1854,6 +1864,8 @@ export default function (pi: ExtensionAPI) {
1854
1864
  // Read-only research helpers (Phase 4), keyed by numeric id (handle `rN`). Lives
1855
1865
  // alongside the standing team but renders in its own widget row.
1856
1866
  const researchStates: Map<number, ResearchState> = new Map();
1867
+ // Metadata only: prompt text is never retained by this ledger.
1868
+ let lastHubLedger: ContextBudgetComponent[] = [];
1857
1869
  let nextResearchId = 1;
1858
1870
  // Retention cap for finished durable (manual/persona) helpers — set from the
1859
1871
  // overrides file's `research-keep:` key at session start (default 4, Infinity
@@ -2063,6 +2075,12 @@ than bulk-reading doc trees; when an entry point is a folder, start from its REA
2063
2075
  or index file. If your work changes something the docs describe (architecture, public
2064
2076
  APIs, commands, structure), say so in your final response so the docs can be updated.`;
2065
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
+ }
2066
2084
  // The one supported safety harness. Every native specialist, researcher, and
2067
2085
  // nested delegate receives it; a missing harness refuses child dispatch.
2068
2086
  let safetyHarnessPath: string | null = null;
@@ -2075,18 +2093,27 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2075
2093
  // ── Execution mode & per-turn budgets (run-budget.js) ──
2076
2094
  // hubMode: overrides-file default, switchable live via /af-hub-mode (session-
2077
2095
  // lifetime). Budgets are per USER TURN: counters reset in before_agent_start,
2078
- // so exhaustion means "stop, summarize, ask" and the next user message opens
2079
- // 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.
2080
2098
  let hubMode: string = DEFAULT_HUB_MODE;
2081
2099
  let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
2082
2100
  let turnDispatchCount = 0;
2083
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;
2084
2110
  // ── Task-scoped budget & tier (run-budget.js) ──
2085
2111
  // A per-message allowance cannot bound a task: every steering message opened a
2086
2112
  // fresh turn window, so a run could spend 8 dispatches and 60 minutes again and
2087
2113
  // again without any counter ever binding. These counters span the whole TASK
2088
- // and are cleared only by an explicit new task (/af-new-task or
2089
- // 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.
2090
2117
  let taskDispatchCount = 0;
2091
2118
  let taskResearchCount = 0;
2092
2119
  let taskLabel: string | null = null;
@@ -2149,6 +2176,33 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2149
2176
  for (const startedAt of askUserStarts.values()) openWait += Math.max(0, now - startedAt);
2150
2177
  return taskClockElapsedMs(taskClock, now, openWait);
2151
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);
2205
+ }
2152
2206
  /** Fold the turn that is ending into the task's active-time accumulator. */
2153
2207
  function closeTurnActiveTime(now = Date.now()) {
2154
2208
  taskClock = closeTaskClock(taskClock, now);
@@ -2159,13 +2213,21 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2159
2213
  taskResearchCount = 0;
2160
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
  }
2171
2233
  function hubAuditIdentity(ctx?: ExtensionContext) {
@@ -2208,7 +2270,16 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2208
2270
  activeMs: taskActiveElapsedMs(now),
2209
2271
  };
2210
2272
  }
2211
- function appendTaskResetEntry(source: "slash-command" | "tool:set_task_tier", label: string | null, prior: ReturnType<typeof taskResetSnapshot>, ctx?: ExtensionContext) {
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) {
2212
2283
  try {
2213
2284
  pi.appendEntry("agent-hub-task-reset", buildTaskResetAudit({
2214
2285
  source,
@@ -2218,6 +2289,17 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2218
2289
  }));
2219
2290
  } catch { /* diagnostics are best-effort; state changes still succeed */ }
2220
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
+ }
2221
2303
  function updateModeStatus() {
2222
2304
  try {
2223
2305
  widgetCtx?.ui?.setStatus(
@@ -2733,6 +2815,11 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2733
2815
  recomputeGrid();
2734
2816
  }
2735
2817
 
2818
+ function persistActiveRoster(): void {
2819
+ if (!activeTeamName || agentStates.size === 0) return;
2820
+ pi.appendEntry(NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState(activeTeamName));
2821
+ }
2822
+
2736
2823
  // ── Dynamic roster (add/drop/save; /af-agents-add, /af-agents-drop, team_adjust) ──
2737
2824
  // The system prompt is rebuilt every turn from agentStates, so a roster
2738
2825
  // change takes effect on the dispatcher's next turn with no restart.
@@ -3478,6 +3565,7 @@ ${externalBlockedProtocol()}
3478
3565
  scopeGlobs: string[] = [],
3479
3566
  watchdogParam?: boolean,
3480
3567
  requestedBackend: "auto" | "native" | "coms" = "auto",
3568
+ preserveManifest = false,
3481
3569
  ): Promise<{
3482
3570
  output: string;
3483
3571
  exitCode: number;
@@ -3686,44 +3774,6 @@ ${externalBlockedProtocol()}
3686
3774
  }
3687
3775
  }
3688
3776
 
3689
- // Clarification protocol — every specialist learns to bubble up questions
3690
- // to the dispatcher instead of guessing.
3691
- const clarificationProtocol = `
3692
-
3693
- ## Clarification protocol
3694
- If at any point you need a decision from the human user (ambiguity, missing input,
3695
- contradiction, or a destructive/irreversible next step), DO NOT guess. Stop and
3696
- return a single line of the form:
3697
-
3698
- ASK_USER: <your question in one clear English sentence>
3699
-
3700
- You may emit multiple ASK_USER lines if you have several questions. The dispatcher
3701
- will surface each to the human user in ${userLanguage} and re-dispatch you with the
3702
- answers. Do not invent values, do not pick "reasonable defaults" silently — ask.
3703
-
3704
- ## External-blocker protocol
3705
- ${externalBlockedProtocol()}
3706
-
3707
- ## Research protocol
3708
- If you need reconnaissance you cannot perform with your own tools (broad code search,
3709
- reading unfamiliar areas of the codebase, summarizing docs), DO NOT guess and DO NOT
3710
- ask the user. Pause for research instead: end your turn with one or more lines of the
3711
- form
3712
-
3713
- NEEDS_RESEARCH: <one specific, self-contained question>
3714
-
3715
- with nothing after them. Your session pauses there; read-only research helpers are
3716
- spawned for you, each helper's findings are saved to a file, and you are resumed in
3717
- this same session with the file paths — read them and continue from where you left
3718
- off. Ask at most ${MAX_AUTO_RESEARCH_QUESTIONS} questions per pause. Use ASK_USER only
3719
- for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked up.`;
3720
-
3721
- // Project rules and docs — when the overrides file lists rule folders or
3722
- // doc entry points, every specialist learns where they are and how to
3723
- // resolve them (rules index-first, docs as orientation entry points).
3724
- const rulesProtocol = buildRulesProtocol();
3725
- const docsProtocol = buildDocsProtocol();
3726
-
3727
3777
  // Mid-turn delegation: a persona that declares `subagents:` gets the
3728
3778
  // delegate extension injected (`-e delegate.ts`), the `delegate` tool
3729
3779
  // added to its allowlist (pi filters extension tools too), and its
@@ -3746,7 +3796,6 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3746
3796
  const extensions = [...safety.extensions];
3747
3797
  let effectiveTools = state.def.tools;
3748
3798
  let delegateEnv: Record<string, string> | undefined;
3749
- let delegationProtocol = "";
3750
3799
  if (delegationActive) {
3751
3800
  const delegationDir = safePathWithin(sessionDir, "delegations", agentKey);
3752
3801
  try { rmSync(delegationDir, { recursive: true, force: true }); } catch {}
@@ -3771,25 +3820,25 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3771
3820
  cwd: ctx.cwd || process.cwd(),
3772
3821
  }),
3773
3822
  };
3774
- delegationProtocol = `
3775
-
3776
- ## Delegation protocol
3777
- You have a \`delegate\` tool with pre-configured sub-agents on cheaper models
3778
- (roles: ${Object.keys(subagentRoles!).join(", ")}). Prefer delegating scoped, self-contained
3779
- sub-tasks to them over doing everything yourself. A child shares NONE of your
3780
- context — put everything it needs into its instruction/context. You may run up
3781
- to ${DELEGATE_TREE_SPAWN_BUDGET} delegate calls for this dispatch; parallel children are forced read-only.
3782
- Children are terminal workers: they do not receive delegate tooling at remaining depth 0.`;
3783
3823
  startDelegationWatch(state, delegationDir);
3784
3824
  }
3785
3825
 
3786
- const deliverableProtocol = `
3787
-
3788
- ## Deliverable-to-file protocol
3789
- 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.
3790
- 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.`;
3791
-
3792
- 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 });
3793
3842
 
3794
3843
  // Per-agent thinking: the persona's `thinking:` frontmatter (or a
3795
3844
  // /af-agent-model-thinking session override) sets the pi --thinking reasoning
@@ -3850,7 +3899,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3850
3899
  if (state.sessionFile && !sessionRecycled) {
3851
3900
  const overflow = shouldRecycleBeforeSpawn({
3852
3901
  priorTokens: state.contextTokens,
3853
- promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(appendedSystemPrompt),
3902
+ promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(replacementSystemPrompt),
3854
3903
  window: agentWindow.window,
3855
3904
  });
3856
3905
  if (overflow) {
@@ -3874,10 +3923,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3874
3923
  model,
3875
3924
  tools: effectiveTools,
3876
3925
  thinking: thinkingLevel,
3877
- appendSystemPrompt: appendedSystemPrompt,
3926
+ systemPrompt: replacementSystemPrompt,
3927
+ noSkills: true,
3928
+ noContextFiles: true,
3878
3929
  sessionFile: agentSessionFile,
3879
3930
  resume: !!state.sessionFile,
3880
3931
  prompt: runPrompt,
3932
+ cwd: ctx.cwd || process.cwd(),
3881
3933
  extensions,
3882
3934
  env: { ...guardrailEnv(agentKey), ...(delegateEnv || {}) },
3883
3935
  detached: true,
@@ -4209,6 +4261,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4209
4261
  elapsed: 0,
4210
4262
  lastWork: "",
4211
4263
  contextPct: 0,
4264
+ contextTokens: 0,
4212
4265
  sessionFile: null,
4213
4266
  turnCount: 1,
4214
4267
  timeline: [],
@@ -4288,13 +4341,18 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4288
4341
  model: state.model,
4289
4342
  tools: RESEARCH_TOOLS,
4290
4343
  thinking: thinkingLevel,
4291
- // Research helpers get the docs orientation block (WHAT/WHY entry
4292
- // points) but not the rules block — rules govern producing/validating
4293
- // changes, which read-only research does not do.
4294
- 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,
4295
4352
  sessionFile: sessionPath,
4296
4353
  resume: !!state.sessionFile,
4297
4354
  prompt: appendInputArtifacts(prompt, inputArtifacts),
4355
+ cwd: ctx.cwd || process.cwd(),
4298
4356
  // A blocked read feeds back so the helper can adapt without aborting.
4299
4357
  extensions: safety.extensions,
4300
4358
  env: guardrailEnv(`research-r${state.id}`),
@@ -4334,7 +4392,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4334
4392
  state.zoomRender?.();
4335
4393
  },
4336
4394
  onUsage: (usage) => {
4337
- if (researchWindow.window > 0) {
4395
+ state.contextTokens = (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
4396
+ if (researchWindow.window > 0) {
4338
4397
  // Same context truth as dispatchAgent: include cache reads/writes,
4339
4398
  // measured against THIS helper's window rather than the dispatcher's.
4340
4399
  state.contextPct = contextPct(usage, researchWindow.window);
@@ -4473,6 +4532,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4473
4532
  }
4474
4533
 
4475
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
+ }
4476
4539
  // 1. Hop limit check
4477
4540
  if (typeof env.hops !== "number" || env.hops >= MAX_HOPS) {
4478
4541
  nack(socket, env.msg_id, "hops exceeded");
@@ -4977,22 +5040,24 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4977
5040
  pi.registerTool({
4978
5041
  name: "dispatch_agent",
4979
5042
  label: "Dispatch Agent",
4980
- 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.",
4981
5044
  parameters: Type.Object({
4982
5045
  agent: Type.String({ description: "Agent name (case-insensitive)" }),
4983
5046
  task: Type.String({ description: "Task description for the agent to execute" }),
4984
- 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." }))),
4985
- 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." }))),
4986
- 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)." })),
4987
- 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." })),
4988
5051
  backend: Type.Optional(Type.Union([
4989
5052
  Type.Literal("auto"),
4990
5053
  Type.Literal("native"),
4991
5054
  Type.Literal("coms"),
4992
- ], { 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)." })),
4993
5056
  }),
4994
5057
 
4995
5058
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
5059
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5060
+ if (confirmationRefusal) return confirmationRefusal;
4996
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" };
4997
5062
  // Display names / underscores resolve to the persona slug key space, so
4998
5063
  // `agent: "Test Engineer"` never burns a dispatch on a lookup error.
@@ -5034,8 +5099,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5034
5099
  if (taskRefusal) {
5035
5100
  turnReport.refusals++;
5036
5101
  sessionTotals.refusals++;
5102
+ armBudgetContinuation("task", taskRefusal.reason);
5037
5103
  return {
5038
- content: [{ type: "text", text: taskRefusal.message }],
5104
+ content: [{ type: "text", text: budgetContinuationInstruction(taskRefusal.message, "task", userLanguage) }],
5039
5105
  details: { agent, task, status: "task_budget_refused", reason: taskRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
5040
5106
  };
5041
5107
  }
@@ -5045,14 +5111,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5045
5111
  "dispatch",
5046
5112
  { dispatches: turnDispatchCount, research: turnResearchCount },
5047
5113
  currentBudget(),
5048
- Date.now() - (currentTurnStartedAt || Date.now()),
5114
+ turnBudgetActiveElapsedMs(),
5049
5115
  hubMode,
5050
5116
  );
5051
5117
  if (budgetRefusal) {
5052
5118
  turnReport.refusals++;
5053
5119
  sessionTotals.refusals++;
5120
+ armBudgetContinuation("turn", budgetRefusal.reason);
5054
5121
  return {
5055
- content: [{ type: "text", text: budgetRefusal.message }],
5122
+ content: [{ type: "text", text: budgetContinuationInstruction(budgetRefusal.message, "turn", userLanguage) }],
5056
5123
  details: { agent, task, status: "budget_refused", reason: budgetRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
5057
5124
  };
5058
5125
  }
@@ -5185,7 +5252,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5185
5252
  const resumePrompt = "Research findings for your NEEDS_RESEARCH questions are ready. " +
5186
5253
  "Read each file with your read tool, then continue from where you paused:\n" +
5187
5254
  answered.map((a, i) => `${i + 1}. ${a.question}\n → ${a.file}`).join("\n");
5188
- result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog, backend);
5255
+ result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog, backend, true);
5189
5256
  dispatchBilled += result.billed ?? 0;
5190
5257
  dispatchOut += result.out ?? 0;
5191
5258
  }
@@ -5281,7 +5348,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5281
5348
  ? `\n\n⚠ ${agent} paused for research, but the TASK research envelope is spent ` +
5282
5349
  `(${taskResearchCount}/${currentTaskBudget().maxResearch}) — no helper was spawned and the specialist ` +
5283
5350
  `was not resumed. Its questions are unanswered. Narrow the task so it can proceed on what it has, ` +
5284
- `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.`
5285
5352
  : "";
5286
5353
 
5287
5354
  const returnPathNotice = returnPath ? `\n\nFull specialist output: ${returnPath}` : "";
@@ -5450,15 +5517,17 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5450
5517
  pi.registerTool({
5451
5518
  name: "spawn_research",
5452
5519
  label: "Spawn Research",
5453
- 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.",
5454
5521
  parameters: Type.Object({
5455
- task: Type.String({ description: "What to investigate. Be specific about what to find and report." }),
5456
- 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." })),
5457
- 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)." })),
5458
- 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." }))),
5459
5526
  }),
5460
5527
 
5461
5528
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
5529
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5530
+ if (confirmationRefusal) return confirmationRefusal;
5462
5531
  const { task, persona, model, artifacts } = params as { task: string; persona?: string; model?: string; artifacts?: string[] };
5463
5532
 
5464
5533
  // Pre-flight refusals before anything is charged: an unacknowledged
@@ -5484,8 +5553,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5484
5553
  if (taskRefusal) {
5485
5554
  turnReport.refusals++;
5486
5555
  sessionTotals.refusals++;
5556
+ armBudgetContinuation("task", taskRefusal.reason);
5487
5557
  return {
5488
- content: [{ type: "text", text: taskRefusal.message }],
5558
+ content: [{ type: "text", text: budgetContinuationInstruction(taskRefusal.message, "task", userLanguage) }],
5489
5559
  details: { status: "task_budget_refused", reason: taskRefusal.reason },
5490
5560
  };
5491
5561
  }
@@ -5495,14 +5565,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5495
5565
  "research",
5496
5566
  { dispatches: turnDispatchCount, research: turnResearchCount },
5497
5567
  currentBudget(),
5498
- Date.now() - (currentTurnStartedAt || Date.now()),
5568
+ turnBudgetActiveElapsedMs(),
5499
5569
  hubMode,
5500
5570
  );
5501
5571
  if (budgetRefusal) {
5502
5572
  turnReport.refusals++;
5503
5573
  sessionTotals.refusals++;
5574
+ armBudgetContinuation("turn", budgetRefusal.reason);
5504
5575
  return {
5505
- content: [{ type: "text", text: budgetRefusal.message }],
5576
+ content: [{ type: "text", text: budgetContinuationInstruction(budgetRefusal.message, "turn", userLanguage) }],
5506
5577
  details: { status: "budget_refused", reason: budgetRefusal.reason },
5507
5578
  };
5508
5579
  }
@@ -5647,6 +5718,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5647
5718
  }),
5648
5719
  async execute(_callId, params, _signal, _onUpdate, _ctx) {
5649
5720
  const { tier, reason, new_task } = params as { tier: string; reason?: string; new_task?: boolean };
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
+
5650
5728
  // A new task classifies from an empty ratchet. Validate the requested tier
5651
5729
  // before mutating/resetting anything so invalid input cannot erase a task.
5652
5730
  const currentTier = new_task ? null : (taskTierAssumed ? null : taskTier);
@@ -5708,6 +5786,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5708
5786
  reason: Type.String({ description: "One line on why the roster must change for this task." }),
5709
5787
  }),
5710
5788
  async execute(_callId, params, _signal, _onUpdate, ctx) {
5789
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5790
+ if (confirmationRefusal) return confirmationRefusal;
5711
5791
  const { action, agent, reason } = params as { action: string; agent: string; reason: string };
5712
5792
  const act = String(action || "").trim().toLowerCase();
5713
5793
  if (hubMode === "fast") {
@@ -5753,17 +5833,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5753
5833
  pi.registerTool({
5754
5834
  name: "set_assertions",
5755
5835
  label: "Set Assertions",
5756
- description:
5757
- `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.`,
5758
5837
  parameters: Type.Object({
5759
5838
  assertions: Type.Array(
5760
5839
  Type.Object({
5761
- id: Type.String({ description: "Stable id, e.g. A1, A2 — referenced verbatim in dispatches and returns." }),
5762
- tag: Type.String({ description: "How it will be proven: test | runtime-ui | code-grep | manual." }),
5763
- text: Type.String({ description: "One checkable pass condition (split compound requirements into separate assertions)." }),
5764
- 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." }),
5765
5844
  }),
5766
- { 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}.` },
5767
5846
  ),
5768
5847
  }),
5769
5848
  async execute(_callId, params, _signal, _onUpdate, ctx) {
@@ -5799,8 +5878,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5799
5878
  pi.registerTool({
5800
5879
  name: "update_assertion",
5801
5880
  label: "Update Assertion",
5802
- description:
5803
- "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.",
5804
5882
  parameters: Type.Object({
5805
5883
  id: Type.String({ description: "Assertion id to update, e.g. A2." }),
5806
5884
  status: Type.String({ description: "One of: proven | unproven | failed." }),
@@ -5864,8 +5942,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5864
5942
  pi.registerTool({
5865
5943
  name: "get_assertions",
5866
5944
  label: "Get Assertions",
5867
- description:
5868
- "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.",
5869
5946
  parameters: Type.Object({}),
5870
5947
  async execute(_callId, _params, _signal, _onUpdate, _ctx) {
5871
5948
  if (assertions.length === 0) {
@@ -5893,11 +5970,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5893
5970
  pi.registerTool({
5894
5971
  name: "coms_list",
5895
5972
  label: "Coms List",
5896
- description:
5897
- "List the peer agents in your current coms pool — the ones shown in the pool widget. Returns " +
5898
- "names, models, live context-window usage, pane_id, and status (idle | working | booting). " +
5899
- "Check status before sending instead of polling the pane. Discovery is scoped to what the human " +
5900
- "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.",
5901
5974
  parameters: Type.Object({
5902
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." })),
5903
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." })),
@@ -6009,10 +6082,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6009
6082
  pi.registerTool({
6010
6083
  name: "coms_send",
6011
6084
  label: "Coms Send",
6012
- description:
6013
- "Send a prompt to a peer agent. Returns synchronously with a msg_id once the receiver acks. " +
6014
- "Use coms_get (non-blocking) or coms_await (blocking) with the msg_id to retrieve the response. " +
6015
- "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.",
6016
6086
  parameters: Type.Object({
6017
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." }),
6018
6088
  prompt: Type.String({ description: "The prompt to send." }),
@@ -6022,6 +6092,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6022
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." })),
6023
6093
  }),
6024
6094
  async execute(_callId, params) {
6095
+ const confirmationRefusal = provisionalCapabilityRefusal("peer");
6096
+ if (confirmationRefusal) return confirmationRefusal;
6025
6097
  if (!identity) {
6026
6098
  throw new Error("coms not initialised");
6027
6099
  }
@@ -6185,8 +6257,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6185
6257
  pi.registerTool({
6186
6258
  name: "coms_await",
6187
6259
  label: "Coms Await",
6188
- description:
6189
- "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.",
6190
6261
  parameters: Type.Object({
6191
6262
  msg_id: Type.String({ description: "msg_id returned by coms_send." }),
6192
6263
  timeout_ms: Type.Optional(Type.Number({ description: "Override the default timeout (ms)." })),
@@ -6327,20 +6398,21 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6327
6398
  pi.registerTool({
6328
6399
  name: "herdr_spawn_peer",
6329
6400
  label: "Herdr Spawn Peer",
6330
- description:
6331
- "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.",
6332
6402
  parameters: Type.Object({
6333
- name: Type.String({ description: "Pane label and coms peer name." }),
6334
- runner: Type.Optional(Type.Union([Type.Literal("pi"), Type.Literal("claude-code")], { description: "Override the declared runner." })),
6335
- persona: Type.Optional(Type.String({ description: "Explicit Pi persona under agents/ or .pi/agents/." })),
6336
- no_persona: Type.Optional(Type.Boolean({ description: "Force a personaless Fleet Core Pi peer." })),
6337
- model: Type.Optional(Type.String({ description: "Override the declared model." })),
6338
- extensions: Type.Optional(Type.String({ description: "Comma-separated extensions for a Pi persona peer." })),
6339
- browser: Type.Optional(Type.Boolean({ description: "Add browser capability to a Pi peer." })),
6340
- all_extensions: Type.Optional(Type.Boolean({ description: "Load all extensions; personaless Fleet Core only." })),
6341
- 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." })),
6342
6412
  }),
6343
6413
  async execute(_callId, params) {
6414
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6415
+ if (confirmationRefusal) return confirmationRefusal;
6344
6416
  if (!herdrFleetReady) {
6345
6417
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6346
6418
  }
@@ -6424,14 +6496,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6424
6496
  pi.registerTool({
6425
6497
  name: "herdr_spawn_pane",
6426
6498
  label: "Herdr Spawn Pane",
6427
- description:
6428
- "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.",
6429
6500
  parameters: Type.Object({
6430
6501
  name: Type.String({ description: "Human-visible pane label." }),
6431
6502
  command: Type.String({ description: "Raw shell command executed with bash -lc." }),
6432
6503
  direction: Type.Optional(Type.Union([Type.Literal("right"), Type.Literal("down")], { description: "Split direction (default right)." })),
6433
6504
  }),
6434
6505
  async execute(_callId, params) {
6506
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6507
+ if (confirmationRefusal) return confirmationRefusal;
6435
6508
  if (!herdrFleetReady) {
6436
6509
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6437
6510
  }
@@ -6475,8 +6548,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6475
6548
  pi.registerTool({
6476
6549
  name: "herdr_read_pane",
6477
6550
  label: "Herdr Read Pane",
6478
- description:
6479
- "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.",
6480
6552
  parameters: Type.Object({
6481
6553
  pane_id: Type.String({ description: "Pane id, e.g. w3:p2 (see herdr_spawn_peer result or the sidebar)." }),
6482
6554
  lines: Type.Optional(Type.Number({ description: "Line cap, default 60, max 200." })),
@@ -6507,13 +6579,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6507
6579
  pi.registerTool({
6508
6580
  name: "herdr_close_pane",
6509
6581
  label: "Herdr Close Pane",
6510
- description:
6511
- "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.",
6512
6583
  parameters: Type.Object({
6513
6584
  pane_id: Type.String({ description: "Pane id to close." }),
6514
6585
  reason: Type.String({ description: "One line shown to the human: why this pane can die." }),
6515
6586
  }),
6516
6587
  async execute(_callId, params) {
6588
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6589
+ if (confirmationRefusal) return confirmationRefusal;
6517
6590
  if (!herdrFleetReady) {
6518
6591
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6519
6592
  }
@@ -6550,13 +6623,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6550
6623
  pi.registerTool({
6551
6624
  name: "herdr_notify",
6552
6625
  label: "Herdr Notify",
6553
- description:
6554
- "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.",
6555
6627
  parameters: Type.Object({
6556
6628
  title: Type.String({ description: "Notification title." }),
6557
6629
  body: Type.Optional(Type.String({ description: "Notification body." })),
6558
6630
  }),
6559
6631
  async execute(_callId, params) {
6632
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6633
+ if (confirmationRefusal) return confirmationRefusal;
6560
6634
  if (!herdrFleetReady) {
6561
6635
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6562
6636
  }
@@ -6594,7 +6668,69 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6594
6668
 
6595
6669
  let askUserAvailable = false;
6596
6670
  let posture: Posture = "operator";
6671
+ let rosterRecoveryRequired = false;
6672
+ let rosterRecoveryDiagnostic = "";
6597
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
+ }
6598
6734
 
6599
6735
  function applyPostureTools(): void {
6600
6736
  pi.setActiveTools(resolvePostureTools({
@@ -6603,6 +6739,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6603
6739
  comsReady,
6604
6740
  herdrReady: herdrFleetReady,
6605
6741
  askUserAvailable,
6742
+ capabilityPacks: [...capabilityResolution.active, ...capabilityResolution.provisional],
6606
6743
  }));
6607
6744
  }
6608
6745
 
@@ -6610,6 +6747,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6610
6747
  ctx.ui.setStatus("hub-posture", `Posture: ${posture}`);
6611
6748
  }
6612
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
+
6613
6760
  function postureStatusText(): string {
6614
6761
  return [
6615
6762
  `Posture: ${posture}`,
@@ -6670,7 +6817,26 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6670
6817
 
6671
6818
  const idx = options.indexOf(choice);
6672
6819
  const name = teamNames[idx];
6673
- 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);
6674
6840
  updateWidget();
6675
6841
  ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
6676
6842
  ctx.ui.notify(`Team: ${name} — ${Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ")}`, "info");
@@ -6693,17 +6859,154 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6693
6859
  const peers = fleetPeerInputs(model => `⇄ ${abbreviateModel(model)}`);
6694
6860
  return buildFleetRows({ specialists, research, peers }, unfiltered ? { showFinished: true } : { showFinished: fleetShowFinished, query: fleetFilter });
6695
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
+
6696
6953
  async function openFleetDetail(row: FleetRow, ctx: any): Promise<void> {
6697
6954
  const target = row.kind === "research" ? researchStates.get(parseResearchHandle(row.key)!) : row.kind === "delegate" ? findDelegationChild(row.key)?.child : agentStates.get(row.key);
6698
6955
  const resources = createPanelResources();
6956
+ let detailRow = row;
6957
+ let modelPicker: { choices: FleetModelChoice[]; index: number; scrollOffset: number } | null = null;
6699
6958
  let scrollOffset = 0, selectedIndex = 0, expandedIndex: number | null = null, followTail = true, lastRender = 0;
6700
6959
  const timeline = () => liveTimeline(target);
6701
6960
  try { await ctx.ui.custom((tui: any, theme: any, _kb: any, done: () => void) => {
6702
6961
  if (target) target.zoomRender = (force?: boolean) => { const now = Date.now(); if (force || now - lastRender > 80) { lastRender = now; tui.requestRender(); } };
6703
- 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
+ };
6704
7006
  }, FULLSCREEN_OVERLAY); } finally { resources.dispose(); if (target) target.zoomRender = undefined; }
6705
7007
  }
6706
7008
  async function restartFleetRow(selected: FleetRow, ctx: any): Promise<void> {
7009
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
6707
7010
  const decision = resolveFleetRestart(selected, {
6708
7011
  researchRestartable: (key) => {
6709
7012
  const state = researchStates.get(parseResearchHandle(key)!);
@@ -6867,6 +7170,120 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6867
7170
  },
6868
7171
  });
6869
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
+
6870
7287
  // ── /af-posture: direct operator ↔ restricted orchestrator ──
6871
7288
  pi.registerCommand("af-posture", {
6872
7289
  description: "Show or set the Fleet posture: operator (direct tools) | orchestrator (delegate-only)",
@@ -6887,9 +7304,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6887
7304
  return;
6888
7305
  }
6889
7306
  posture = next;
7307
+ if (posture === "operator") {
7308
+ rosterRecoveryRequired = false;
7309
+ rosterRecoveryDiagnostic = "";
7310
+ setTimeout(replayDeferredRecoveryInputs, 0);
7311
+ }
6890
7312
  if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
6891
7313
  await pickDispatcherPersona(ctx);
6892
7314
  }
7315
+ resolveIncomingCapabilities("");
6893
7316
  applyPostureTools();
6894
7317
  updatePostureStatus(ctx);
6895
7318
  pi.appendEntry("agent-hub-posture", { posture });
@@ -6932,30 +7355,6 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6932
7355
  },
6933
7356
  });
6934
7357
 
6935
- // ── /af-new-task: open a fresh TASK window ──
6936
- // The task budget is deliberately immune to a user message — a steering
6937
- // message is a correction, not a new ask, and resetting on it is what let a
6938
- // run spend a fresh envelope per correction. Opening a new window is
6939
- // therefore an explicit, human decision, and this is where it is made.
6940
- pi.registerCommand("af-new-task", {
6941
- 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.",
6942
- handler: async (args, ctx) => {
6943
- widgetCtx = ctx;
6944
- const label = (args || "").trim() || null;
6945
- const resetAt = Date.now();
6946
- const prior = taskResetSnapshot(resetAt);
6947
- resetTaskWindow(label, resetAt);
6948
- appendTaskResetEntry("slash-command", label, prior, ctx);
6949
- ctx.ui.notify(
6950
- `New task window${label ? `: ${label}` : ""}\n` +
6951
- `Previous task${prior.tier ? ` (tier ${prior.tier})` : ""} spent ${prior.dispatches} dispatches, ` +
6952
- `${prior.research} research, ${prior.reviewRounds} review round(s), ${Math.round(prior.activeMs / 60_000)} min active.\n` +
6953
- `Tier is unset — the dispatcher re-triages on its next dispatch.` + hubLocationSuffix(ctx),
6954
- "success",
6955
- );
6956
- },
6957
- });
6958
-
6959
7358
  pi.registerCommand("af-watchdog", {
6960
7359
  description: "Drift watchdog: /af-watchdog [on|off|auto] hub-wide, /af-watchdog <agent> [on|off|clear] per agent, no args to show",
6961
7360
  handler: async (args, ctx) => {
@@ -7064,6 +7463,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7064
7463
  }
7065
7464
  teams[name] = members;
7066
7465
  activeTeamName = name;
7466
+ persistActiveRoster();
7067
7467
  ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
7068
7468
  ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "success");
7069
7469
  },
@@ -7682,6 +8082,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7682
8082
  getArgumentCompletions: researchPersonaCompletions,
7683
8083
  handler: async (args, ctx) => {
7684
8084
  widgetCtx = ctx;
8085
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7685
8086
  let rest = (args ?? "").trim();
7686
8087
  let personaName: string | undefined;
7687
8088
  let modelArg: string | undefined;
@@ -7757,6 +8158,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7757
8158
  // its /af-research-cont alias.
7758
8159
  const researchContHandler = async (args: string | undefined, ctx: any) => {
7759
8160
  widgetCtx = ctx;
8161
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7760
8162
  const trimmed = (args ?? "").trim();
7761
8163
  const sp = trimmed.indexOf(" ");
7762
8164
  if (sp === -1) {
@@ -7961,6 +8363,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7961
8363
  getArgumentCompletions: subagentTargetCompletions,
7962
8364
  handler: async (args, ctx) => {
7963
8365
  widgetCtx = ctx;
8366
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7964
8367
  const name = args?.trim();
7965
8368
  // An rN handle re-runs a finished helper's last task on a fresh session
7966
8369
  // (unlike /af-agents-cont, which resumes the existing one). A running helper
@@ -8141,6 +8544,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8141
8544
  description: "Hand the session off to a coms peer (the dispatcher composes a self-contained brief): /af-handoff <peer>",
8142
8545
  getArgumentCompletions: comsPeerCompletions,
8143
8546
  handler: async (args, ctx) => {
8547
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
8144
8548
  if (!comsReady) { ctx.ui.notify("coms is not active in this session — /af-handoff unavailable.", "warning"); return; }
8145
8549
  const target = (args ?? "").trim();
8146
8550
  if (!target) {
@@ -8178,6 +8582,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8178
8582
  pi.registerCommand("af-compound", {
8179
8583
  description: "Capture this session's lessons into the project's rules/docs via the documenter: /af-compound [focus]",
8180
8584
  handler: async (args, ctx) => {
8585
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
8181
8586
  if (!agentStates.has("documenter")) {
8182
8587
  ctx.ui.notify(
8183
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.",
@@ -8222,11 +8627,32 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8222
8627
  pi.on("tool_execution_start", async (event) => {
8223
8628
  if (event.toolName !== "ask_user") return;
8224
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
+ }
8225
8638
  // Asking the human IS the escalation the external-blocker breaker demands:
8226
8639
  // once it is under way, the gate opens.
8227
8640
  externalBlockerAcknowledged = true;
8228
8641
  externalBlockerRefusedOnce = false;
8229
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
+
8230
8656
  pi.on("tool_execution_end", async (event) => {
8231
8657
  if (event.toolName !== "ask_user") return;
8232
8658
  const startedAt = askUserStarts.get(event.toolCallId);
@@ -8234,18 +8660,46 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8234
8660
  // The task clock bills active time only — the human's answer is not the
8235
8661
  // fleet's work, and billing it is what would false-stop a steered session.
8236
8662
  const endedAt = Date.now();
8237
- if (startedAt) taskClock = addTaskClockWait(taskClock, Math.max(0, endedAt - startedAt));
8238
- if (startedAt == null) return;
8239
- const interval: [number, number] = [startedAt, endedAt];
8240
- // Attach to the live dispatcher entry, or buffer until one is created this turn.
8241
- if (currentOrchestratorEntry) (currentOrchestratorEntry.awaitIntervals ??= []).push(interval);
8242
- else turnAskUserIntervals.push(interval);
8243
- historyRender?.();
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
+ }
8244
8695
  });
8245
8696
 
8246
8697
  // ── System Prompt Override ───────────────────
8247
8698
 
8248
- 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) {
8249
8703
  // Re-assert the selected posture for every turn so prompt and tool policy stay
8250
8704
  // synchronized after commands or runtime capability changes.
8251
8705
  applyPostureTools();
@@ -8268,12 +8722,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8268
8722
  currentOrchestratorEntry = null;
8269
8723
  askUserStarts.clear();
8270
8724
  turnAskUserIntervals.length = 0;
8725
+ turnBudgetAskUserWaitMs = 0;
8726
+ budgetContinuationAsks.clear();
8727
+ if (pendingBudgetContinuation?.kind === "turn") pendingBudgetContinuation = null;
8271
8728
  // Fresh turn → fresh TURN budget window (mode persists across turns). The
8272
8729
  // TASK budget, the tier, and the external-blocker breaker deliberately do
8273
8730
  // NOT reset here: a steering message is a correction to the same work, not
8274
8731
  // a new ask, and resetting on it is precisely how a run spent eight fresh
8275
- // dispatches per correction and never hit a bound. Only /af-new-task (or
8276
- // 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.
8277
8735
  turnDispatchCount = 0;
8278
8736
  turnResearchCount = 0;
8279
8737
  turnDispatchFingerprints.clear();
@@ -8288,20 +8746,26 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8288
8746
  }
8289
8747
  turnReport = freshTurnReport();
8290
8748
  updateModeStatus();
8749
+ }
8291
8750
 
8292
- // Build dynamic agent catalog from active team only
8293
- const agentCatalog = Array.from(agentStates.values())
8294
- .map(s => `### ${displayName(s.def.name)}\n**Dispatch as:** \`${s.def.name}\`\n${s.def.description}\n**Tools:** ${s.def.tools}`)
8295
- .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");
8296
8761
 
8297
- 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(", ") : "";
8298
8763
 
8299
8764
  // Research personas (kind: research) the dispatcher can spawn read-only via
8300
8765
  // spawn_research. Independent of team membership.
8301
- const researchCatalog = researchPersonas.length > 0
8302
- ? researchPersonas
8303
- .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}`)
8304
- .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")
8305
8769
  : "(No research personas defined. Call `spawn_research` without `persona` for an ad-hoc read-only helper.)";
8306
8770
 
8307
8771
  // Two flavors of the system prompt depending on whether ask_user is
@@ -8336,11 +8800,9 @@ ask the human. You MUST instead:
8336
8800
  - For \`ASK_USER:\` markers raised by specialists, relay the question verbatim to
8337
8801
  the user in ${userLanguage} and wait for their reply in the next turn.`;
8338
8802
 
8339
- const toolList = askUserAvailable
8340
- ? "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)"
8341
- : "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)"}`;
8342
8804
 
8343
- const dispatchSection = askUserAvailable
8805
+ const dispatchSection = !fleetActive ? "" : askUserAvailable
8344
8806
  ? `- BEFORE dispatching: if anything is ambiguous, missing, or could go several valid
8345
8807
  ways, call \`ask_user\` first. Never invent constraints or "reasonable defaults"
8346
8808
  the user did not state.
@@ -8388,114 +8850,22 @@ ask the human. You MUST instead:
8388
8850
  const taskBudget = currentTaskBudget();
8389
8851
  const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
8390
8852
  const capMin = (ms: number | null) => (ms == null ? "unlimited" : `${Math.round(ms / 60_000)} min`);
8391
- const modeSection = `## Task triage (FIRST, before any dispatch)
8392
- Call \`set_task_tier\` to classify THIS turn's ask — the hub lowers the enforced caps
8393
- to min(mode, tier), so an honest tier is how you avoid burning budget on ceremony:
8394
- - trivial — one obvious, low-risk change (1 dispatch, 1 research). No ledger, no review pipeline.
8395
- - small — a contained change in familiar code (2 dispatches, 2 research). At most 3 narrow assertions.
8396
- - feature — a normal multi-step feature (6 dispatches, 4 research). Ledger + one review gate.
8397
- - project — a large, multi-phase effort (mode budget applies). Full rigor per the mode.
8398
- If you skip the call, the hub assumes "feature". Re-call it (say why) if the ask turns
8399
- out bigger — raising the tier mid-turn is allowed. Tie the tier to the USER'S ask, not
8400
- to how interesting the work is.
8401
- - A provided plan is a SPEC: when the user hands you an existing plan/task list (a PLAN
8402
- file, a numbered breakdown), do NOT re-plan or re-spec it. Skip planner and
8403
- plan-reviewer; batch the plan's tasks straight to the builder and use the plan's own
8404
- acceptance criteria as the assertions.
8405
- - A plan is a spec, NOT a mandate to execute all of it. When the plan is larger than what
8406
- the user actually asked for, do the asked-for part and say which parts you left — the
8407
- plan's existence is not consent to run its every gate. If a plan for a small ask has
8408
- grown gates, manifests, or provenance machinery nobody requested, name that to the user
8409
- instead of executing it.
8410
- - Using every persona is a smell, not a virtue: each dispatch must change the outcome.
8411
- If a dispatch's absence would change nothing, don't make it.
8412
- - THE TIER IS THE TASK'S, NOT THE TURN'S. It survives the user's next message and moves by
8413
- ratchet: lowering it is always free, raising it needs a \`reason\` naming what the ask
8414
- turned out to contain. A correction or follow-up ("no, only the one line") is the SAME
8415
- task — do not re-triage it upward, and do not pass \`new_task\` for it. At trivial/small
8416
- tiers the hub refuses planner, plan-reviewer, architect, security-auditor and
8417
- deep-researcher in code; that refusal is a signal to do the work, not to raise the tier.
8418
-
8419
- ## Execution mode: ${hubMode}${taskTier ? ` · tier: ${taskTier}` : ""}
8420
- Budgets for THIS user turn (enforced by the hub — exhausted budgets make dispatch_agent/
8421
- spawn_research refuse; a new user message opens a fresh window; /af-hub-mode switches mode):
8422
- - dispatch_agent calls: ${cap(budget.maxDispatches)} · spawn_research calls: ${cap(budget.maxResearch)}
8423
- - turn wall clock: ${capMin(budget.wallMs)} · per-run deadline: ${capMin(budget.agentTurnMs)}
8424
- Budgets for the WHOLE TASK (${TASK_BUDGET_MULTIPLIER}× the turn envelope; NOT reset by a user message —
8425
- only by /af-new-task or set_task_tier \`new_task: true\`). Spent so far:
8426
- - dispatches ${taskDispatchCount}/${cap(taskBudget.maxDispatches)} · research ${taskResearchCount}/${cap(taskBudget.maxResearch)} · active time ${Math.round(taskActiveElapsedMs() / 60_000)}/${capMin(taskBudget.wallMs)} min
8427
- - review rounds ${taskReviewRounds}/${cap(reviewRoundCap(taskTier))} (a review is a gate, not a loop)
8428
- Exhausting the TASK budget is a hard stop: it means the work outgrew its envelope three
8429
- times over, which is a re-scoping decision for the human, not something to spend through.
8430
- Plan within the budget: batch related work into ONE dispatch (a coherent slice of 4–6
8431
- plan tasks, not one dispatch per micro-task), and when a budget refusal comes back, STOP —
8432
- summarize progress and ask the user; never retry the refused call in the same turn.
8433
- Repeating an identical task to the same agent in one turn is refused in code
8434
- (duplicate guard) — use the earlier result or change the task materially.
8435
- Every task you dispatch states four things: the objective, the expected output format,
8436
- the files in scope (also pass them as \`scope\` globs — they arm the live drift watchdog),
8437
- and the boundaries (what NOT to touch). Vague tasks produce duplicated or drifting work.
8438
- ${hubMode === "fast"
8439
- ? `FAST mode rules: this is a single-specialist path for small, low-risk asks.
8440
- - Use at most ONE specialist dispatch (plus one research call only if truly needed).
8441
- - Skip the assertion ledger and the plan/review pipeline; rely on the specialist's own
8442
- verification and report back.
8443
- - Nested delegation is disabled; do not commission inventories or parity audits.
8444
- - If the task turns out to be larger than fast mode fits, say so and ask the user to
8445
- switch modes (/af-hub-mode standard) instead of burning the budget.`
8446
- : hubMode === "standard"
8447
- ? `STANDARD mode rules: rigor where it pays, batching everywhere else.
8448
- - At most ONE reconnaissance pass before building (skip it for familiar code); prefer the
8449
- specialist's own recon over a separate research run.
8450
- - Execute plans in a FEW large batches (4–6 tasks per builder dispatch), each followed by
8451
- ONE verification gate; do not re-audit everything after every small fix — re-verify only
8452
- the assertions the fix touched.
8453
- - One review gate at the end (code review; security only when the change is
8454
- security-sensitive) — not one per micro-slice.
8455
- - Reserve deep-researcher for genuinely cross-cutting questions (max 1–2 per task).`
8456
- : `STRICT mode rules: the full Verification Contract below applies — use for production
8457
- migrations, security-sensitive work, or when the user explicitly asks for it. The wide
8458
- budgets are a checkpoint, not a target: when one is hit, stop and check in with the user.`}
8459
- `;
8460
-
8461
- const fullVerificationContract = `## Verification Contract (assertion ledger)
8462
- A clearly stated requirement must never be silently dropped. You OWN a ledger of checkable
8463
- acceptance assertions; build it before you dispatch, and refuse "done" until each is proven.
8464
- - BEFORE dispatching a builder for any non-trivial task, convert the request into numbered
8465
- assertions and record them with \`set_assertions\` — one pass condition each, tagged
8466
- test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
8467
- Pass the relevant assertions VERBATIM into each dispatch.
8468
- - Every assertion NAMES ITS SOURCE (\`source: "PLAN-x.md:585-595"\`, \`"user request"\`,
8469
- \`"review finding F3"\`). The hub refuses a sourceless batch by id: a specialist told to
8470
- prove A9 must be able to read where A9 came from instead of asking you.
8471
- - Keep at most ${MAX_OPEN_ASSERTIONS} assertions OPEN at once. A large task still has many
8472
- assertions — declare the batch the next dispatches actually prove, and \`set_assertions\`
8473
- the next batch when it starts. Over the cap the hub accepts the call but warns.
8474
- - Keep assertions NARROW: one subsystem / one behavior each. Never bundle several
8475
- subsystems into one giant assertion — a compound assertion forces a full re-audit after
8476
- every small fix. After a fix, re-verify the touched assertions only.
8477
- - After each verification gate, call \`update_assertion\` with proven (and name the evidence),
8478
- unproven, or failed. Advance ONLY on proven; unproven and failed both mean not done.
8479
- - A runtime-ui assertion (visibility, placement, "appears in the table") is proven only by an
8480
- actual runtime observation — dispatch a browser-capable specialist; a static review never
8481
- closes it.
8482
- - For "make X behave like existing Y" requests, FIRST spawn_research a deep-researcher parity
8483
- inventory of every site where the exemplar is special-cased, and turn each site into an
8484
- assertion — otherwise the exemplar ships and its siblings are missed.
8485
- - On a "wrong again" correction, call \`set_assertions\` again to rebuild the ledger from the
8486
- LATEST correction before re-dispatching (a regression reset — old summaries are now suspect).
8487
- - After a context compaction your status line shows only counts (e.g. "2✓ 3○"), not the
8488
- assertion text. Call \`get_assertions\` to read the full ledger back — ids, tags, pass
8489
- conditions, and the named evidence on each proven/failed assertion — before you re-dispatch
8490
- or report done. This is your bounded read-only window onto recorded ground truth; you do not
8491
- author code.
8492
- - Specialist returns land pre-parsed in \`details.structuredReturn\` with the raw return at
8493
- \`details.returnPath\` — read the digest/path directly; NEVER spawn a research helper just to
8494
- read a return artifact you already hold.
8495
- The ledger is persisted and its status is shown to the human; it is advisory — it informs your
8496
- gating, it does not auto-block a dispatch.`;
8497
-
8498
- 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"
8499
8869
  ? `## Verification (fast mode)
8500
8870
  The assertion ledger is OPTIONAL in fast mode. State what was asked, dispatch the one
8501
8871
  specialist, and verify from its returned evidence (command output, file:line). If the
@@ -8506,127 +8876,274 @@ standard/strict instead of improvising rigor here.`
8506
8876
  // Peer section only when coms initialised. Decision G4: the coms_* tools are
8507
8877
  // already in the active tool surface when ready; here we just teach the
8508
8878
  // dispatcher how and when to reach for them.
8509
- const comsSection = comsReady && identity
8879
+ const comsSection = peerActive && comsReady && identity
8510
8880
  ? `
8511
8881
  ## Peer agents (coms)
8512
- You are ALSO a peer on the coms mesh — project "${identity.project}", name "${identity.name}". Beyond
8513
- your own team you can talk to the peers in your coms POOL — the agents shown in the pool widget:
8514
- - \`coms_list\` — discover the peers in your pool (names, models, live context usage). The pool is
8515
- scoped to YOUR project and excludes private (explicit) peers. You CANNOT widen this — only the human
8516
- can, with \`/af-coms --project <name>\` or \`/af-coms --all\`. Do not ask coms_list for other projects.
8517
- - \`coms_send\` returns a msg_id; then \`coms_await\` (blocking) or \`coms_get\` (poll) reads the reply.
8518
- For long work put the SAME budget on both calls: \`coms_send(reply_timeout_ms: N, ...)\`, then
8519
- \`coms_await(timeout_ms: N, ...)\`. The send controls the receiver; await controls only your local
8520
- wait. A timeout returns pending — await/get the same msg_id again, never re-send the task.
8521
- This lets you use a peer as an on-demand subagent: send a SELF-CONTAINED task, await it, and fold the
8522
- result into your plan. A peer does NOT share your context — spell out everything it needs.
8523
- - Only peers in your pool are reachable. \`coms_send\`/\`/af-handoff\` to anyone outside it is refused. If
8524
- you need a peer that is not in the pool, ASK THE HUMAN to widen scope (\`/af-coms --project\`/\`--all\`),
8525
- then retry. Do not pass cross-project context to a peer unless the human approved that reach.
8526
- - Prefer \`dispatch_agent\`/\`spawn_research\` for in-team work; reach for coms when a task needs another
8527
- STANDING agent already in your pool (a human-driven peer, a specialist outside this team).
8528
- - A peer can also address YOU as a subagent — answer an inbound coms prompt as a normal turn.
8529
- - Some team members may be transparently served by a same-name pool peer (dispatch-policy.yaml).
8530
- This changes NOTHING for you: keep dispatching them via \`dispatch_agent\`; never coms_send the
8531
- 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.
8532
8883
  `
8533
8884
  : "";
8534
8885
 
8535
8886
  const postureText = posturePrompt(posture);
8536
- const orchestratorPrompt = `${postureText.intro} You have ${toolList}.
8537
-
8538
- ## Language
8539
- ${languageLines}
8540
-
8541
- ## Native Roster: ${activeTeamName || "(none)"}
8542
- Members: ${teamMembers || "(none — add a persona before using dispatch_agent)"}
8543
- You can ONLY dispatch to agents listed below. Do not attempt to dispatch to agents
8544
- outside this team. The roster CAN change mid-session: the human via /af-agents-add,
8545
- /af-agents-drop, /af-agents-team — or you via \`team_adjust\` (add/drop with a reason)
8546
- when the current roster genuinely cannot serve the task. Use it sparingly; more
8547
- personas is usually the wrong answer.
8548
-
8549
- ## How to Work
8550
- - Analyze the user's request and break it into clear sub-tasks.
8551
- - Choose the right agent(s) for each sub-task.
8552
- ${dispatchSection}
8553
- - 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.
8554
- - Review results and dispatch follow-up agents if needed.
8555
- - If a task fails, try a different agent or adjust the task description.
8556
- - Summarize the outcome for the user in ${userLanguage}.
8557
-
8558
- ${askUserBlock}
8559
-
8560
- ${modeSection}
8561
- ${verificationSection}
8562
-
8563
- ## Research helpers (read-only)
8564
- - \`spawn_research\` runs a READ-ONLY helper (read/grep/find/ls — no bash, no writes)
8565
- and returns its findings to you inline. Use it for reconnaissance, code search, and
8566
- reading docs/code BEFORE you dispatch a builder — or to fan out background research.
8567
- - Two flavours: pass \`persona\` to spawn one of the research personas listed below (it
8568
- brings its own role/model); omit \`persona\` for an ad-hoc helper (optional \`model\`).
8569
- - Match the helper to the job: use a lighter/faster persona for simple reads and a
8570
- higher-capability one for ambiguous, cross-cutting, or high-stakes research. Compare
8571
- the **Model** / **Thinking** shown for each persona below and pick deliberately.
8572
- - Specialists you dispatch are sandboxed and CANNOT spawn their own helpers. When a
8573
- specialist needs research help, YOU run \`spawn_research\`, collect the findings, and
8574
- fold them into the specialist's task — do not ask the specialist to do it itself.
8575
- - Research helpers are ephemeral and read-only, so they are always safe to run.
8576
- ${comsSection}${herdrFleetReady ? `
8577
- ## Fleet (herdr)
8578
- This session runs inside a herdr workspace and can drive panes:
8579
- - \`herdr_spawn_peer\` starts an addressable Pi persona, personaless Fleet Core, or Claude Code
8580
- peer next to you. Name-only calls inherit peers.yaml; explicit fields use the same resolver as
8581
- \`just fleet peer\`. Every peer is locked to this Hub's coms project.
8582
- - \`herdr_spawn_pane\` starts a raw command pane (for example a build watcher or server). It is
8583
- not a coms peer and has no readiness result. Spawn deliberately; every pane is human-visible.
8584
- - A spawned peer BOOTS IDLE and waits for \`coms_send\`: the spawn hands it no task.
8585
- The call waits for it to register and returns \`peer_ready\` with its coms name. Spawn one
8586
- only immediately before the first message you will send it — a peer spawned "to have it
8587
- ready" and never addressed is an empty pane named like a worker. If you sent it no work
8588
- by the end of the turn, say so and offer to close it; the hub names unaddressed
8589
- hub-spawned peers in the session digest.
8590
- - \`peer_ready: false\` is a FAILED start, not a slow one. The result carries the pane's last
8591
- output — read it, then fix the cause or close the pane and spawn again. Never \`coms_send\`
8592
- to a name that never registered, and never spawn a second peer to route around the first.
8593
- - \`herdr_read_pane\` is read-to-decide: peek at a worker/tool pane's recent output before
8594
- acting on it. It is NOT a messaging channel and NOT a status poll — \`coms_list\` already
8595
- reports each peer's \`pane_id\` and \`status\` (idle | working | booting), so check that
8596
- before sending. Prefer \`coms_send\`/\`coms_await\` for pi and bridged peers; reading screens
8597
- is the last resort for unbridged tools and post-mortems.
8598
- - \`herdr_close_pane\` kills a pane and asks the HUMAN to confirm first. Close only panes you
8599
- spawned, when their job is done or they are stuck.
8600
- - \`herdr_notify\` reaches the human via desktop notification when they are away — use it when
8601
- a long fleet task finishes or needs attention; it does not replace \`ask_user\`.
8602
- ` : ""}
8603
- ## Hard Rules
8604
- ${postureText.hardRules}
8605
- ${ambiguityRule}
8606
- - You can chain agents: spawn_research to gather context, builder to implement.
8607
- - You can dispatch the same agent multiple times with different tasks.
8608
- - Keep tasks focused — one clear objective per dispatch.
8609
-
8610
- ## Agents
8611
-
8612
- ${agentCatalog}
8613
-
8614
- ## Research personas
8615
-
8616
- ${researchCatalog}`;
8617
-
8618
- // Flavor-only persona merge (decision 9 / G4): the dispatcher persona's body
8619
- // goes FIRST, then the orchestration rules. The persona enriches the role; it
8620
- // never replaces the orchestrator prompt and never narrows the tool surface.
8621
- const systemPrompt = dispatcherPersona
8622
- ? `${dispatcherPersona.systemPrompt}\n\n${orchestratorPrompt}`
8623
- : 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
+ }));
8624
8940
 
8625
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);
8626
9094
  });
8627
9095
 
8628
9096
  // ── Persona gate: block input until a dispatcher persona is picked ──
8629
- 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();
8630
9147
  if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
8631
9148
  ctx.ui.notify("Pick a dispatcher persona first (see the select dialog).", "warning");
8632
9149
  return { action: "handled" as const };
@@ -8638,6 +9155,14 @@ ${researchCatalog}`;
8638
9155
 
8639
9156
  pi.on("session_start", async (_event, _ctx) => {
8640
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 = "";
8641
9166
  // Capture the configured surface before Agent Hub applies either posture.
8642
9167
  // Operator mode restores this baseline (minus gated Hub-owned tools).
8643
9168
  baselineTools = pi.getActiveTools();
@@ -8656,6 +9181,11 @@ ${researchCatalog}`;
8656
9181
  taskClock = createTaskClock();
8657
9182
  askUserStarts.clear();
8658
9183
  turnAskUserIntervals.length = 0;
9184
+ turnBudgetAskUserWaitMs = 0;
9185
+ turnContinuationCount = 0;
9186
+ taskContinuationCount = 0;
9187
+ pendingBudgetContinuation = null;
9188
+ budgetContinuationAsks.clear();
8659
9189
  if (widgetCtx) {
8660
9190
  widgetCtx.ui.setWidget("agent-team", undefined);
8661
9191
  widgetCtx.ui.setWidget("agent-research", undefined);
@@ -9054,22 +9584,49 @@ ${researchCatalog}`;
9054
9584
  personaGateEnabled = overrides.personaGate && orchestratorPersonas.length > 0;
9055
9585
  personaGateSatisfied = !personaGateEnabled;
9056
9586
 
9057
- // A roster is opt-in. Resolve it before posture so --agent-team can imply
9058
- // 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.
9059
9591
  agentStates.clear();
9060
9592
  activeTeamName = "";
9061
9593
  comsMissNotified.clear();
9062
9594
  recomputeGrid();
9063
- 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
+ });
9064
9606
  posture = resolveSessionPosture({
9065
- entries: _ctx.sessionManager.getEntries(),
9066
- explicitPosture: pi.getFlag("posture"),
9067
- hasExplicitRoster: startupRoster !== null,
9607
+ entries: sessionEntries,
9608
+ explicitPosture,
9609
+ hasExplicitRoster: startupRoster.source === "explicit",
9068
9610
  });
9069
- if (orchestratorNeedsRoster(posture, startupRoster?.members.length ?? 0)) {
9070
- 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
+ );
9071
9629
  }
9072
- if (startupRoster) activateTeam(startupRoster.name);
9073
9630
 
9074
9631
  // Probe for `ask_user` (registered by the `pi-ask-user` companion package
9075
9632
  // when installed). Action methods like getAllTools are runtime-only, so
@@ -9079,7 +9636,15 @@ ${researchCatalog}`;
9079
9636
  // Fleet tools are available only inside a herdr pane with a live server.
9080
9637
  // The posture policy adds gated groups without activating unavailable tools.
9081
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("");
9082
9644
  applyPostureTools();
9645
+ if (observeContextPressure(_ctx, "session_start") === "compact-now") {
9646
+ setTimeout(() => runAutomaticCompaction(_ctx, "session_start"), 0);
9647
+ }
9083
9648
  updatePostureStatus(_ctx);
9084
9649
 
9085
9650
  _ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"} (${agentStates.size})`);
@@ -9122,6 +9687,7 @@ ${researchCatalog}`;
9122
9687
  `/af-agents-team Select a team\n` +
9123
9688
  `/af-agents-list Open Fleet Dashboard\n` +
9124
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` +
9125
9691
  `/af-agent-model <persona>[.<role>] Switch a persona's or sub-role's model\n` +
9126
9692
  `/af-agent-model-thinking <persona> Switch a persona's thinking level\n` +
9127
9693
  `/af-models [profile] Apply a named model profile to the team\n` +
@@ -9145,7 +9711,7 @@ ${researchCatalog}`;
9145
9711
 
9146
9712
  // The persona gate restricts only orchestrator posture. Operators can work
9147
9713
  // directly and choose a dispatcher persona later without being blocked.
9148
- if (posture === "orchestrator" && personaGateEnabled) {
9714
+ if (posture === "orchestrator" && personaGateEnabled && !rosterRecoveryRequired) {
9149
9715
  void pickDispatcherPersona(_ctx);
9150
9716
  }
9151
9717