@chankov/agent-fleet 1.0.1 → 1.0.3

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 (625) hide show
  1. package/.pi/extensions/package-lock.json +77 -45
  2. package/.pi/harnesses/agent-hub/README.md +167 -76
  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/context-window.js +1 -1
  9. package/.pi/harnesses/agent-hub/drift-watchdog.js +11 -4
  10. package/.pi/harnesses/agent-hub/execution-profile.ts +69 -0
  11. package/.pi/harnesses/agent-hub/footer.ts +3 -2
  12. package/.pi/harnesses/agent-hub/hub-state-audit.js +14 -10
  13. package/.pi/harnesses/agent-hub/index.ts +1316 -660
  14. package/.pi/harnesses/agent-hub/package.json +1 -1
  15. package/.pi/harnesses/agent-hub/posture.ts +72 -17
  16. package/.pi/harnesses/agent-hub/provider-semaphore.js +1 -1
  17. package/.pi/harnesses/agent-hub/run-budget.js +77 -80
  18. package/.pi/harnesses/agent-hub/spawn.ts +14 -2
  19. package/.pi/harnesses/ask-user-remote/index.ts +59 -4
  20. package/.pi/harnesses/coms/package.json +1 -1
  21. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  22. package/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  23. package/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  24. package/.pi/harnesses/lib/context-budget-view.ts +107 -0
  25. package/.pi/harnesses/lib/context-budget.ts +114 -0
  26. package/.pi/harnesses/lib/fleet-dashboard-view.ts +3 -1
  27. package/.pi/harnesses/lib/fleet-detail-view.ts +127 -2
  28. package/.pi/harnesses/package-lock.json +73 -80
  29. package/.versions/1.0.2/.pi/agents/dispatch-policy.yaml +32 -0
  30. package/.versions/1.0.2/.pi/agents/model-profiles.yaml +27 -0
  31. package/.versions/1.0.2/.pi/agents/peers.yaml +142 -0
  32. package/.versions/1.0.2/.pi/agents/teams.yaml +41 -0
  33. package/.versions/1.0.2/.pi/damage-control-rules.yaml +297 -0
  34. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/README.md +57 -0
  35. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  36. package/.versions/1.0.2/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  37. package/.versions/1.0.2/.pi/extensions/btw/README.md +120 -0
  38. package/.versions/1.0.2/.pi/extensions/btw/index.ts +914 -0
  39. package/.versions/1.0.2/.pi/extensions/btw/package.json +6 -0
  40. package/.versions/1.0.2/.pi/extensions/btw/state.js +179 -0
  41. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  42. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  43. package/.versions/1.0.2/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  44. package/.versions/1.0.2/.pi/extensions/compact-and-continue/README.md +42 -0
  45. package/.versions/1.0.2/.pi/extensions/compact-and-continue/index.ts +120 -0
  46. package/.versions/1.0.2/.pi/extensions/compact-and-continue/package.json +6 -0
  47. package/.versions/1.0.2/.pi/extensions/mcp-bridge/README.md +46 -0
  48. package/.versions/1.0.2/.pi/extensions/mcp-bridge/index.ts +206 -0
  49. package/.versions/1.0.2/.pi/extensions/mcp-bridge/package.json +6 -0
  50. package/.versions/1.0.2/.pi/extensions/package-lock.json +1175 -0
  51. package/.versions/1.0.2/.pi/extensions/package.json +9 -0
  52. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/README.md +205 -0
  53. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/config.ts +198 -0
  54. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  55. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/index.ts +248 -0
  56. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/package.json +6 -0
  57. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  58. package/.versions/1.0.2/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  59. package/.versions/1.0.2/.pi/harnesses/agent-hub/README.md +1156 -0
  60. package/.versions/1.0.2/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  61. package/.versions/1.0.2/.pi/harnesses/agent-hub/artifacts.js +146 -0
  62. package/.versions/1.0.2/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  63. package/.versions/1.0.2/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  64. package/.versions/1.0.2/.pi/harnesses/agent-hub/budget-continuation.ts +73 -0
  65. package/.versions/1.0.2/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  66. package/.versions/1.0.2/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  67. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  68. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  69. package/.versions/1.0.2/.pi/harnesses/agent-hub/context-window.js +106 -0
  70. package/.versions/1.0.2/.pi/harnesses/agent-hub/delegate.ts +435 -0
  71. package/.versions/1.0.2/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  72. package/.versions/1.0.2/.pi/harnesses/agent-hub/drift-watchdog.js +211 -0
  73. package/.versions/1.0.2/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  74. package/.versions/1.0.2/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  75. package/.versions/1.0.2/.pi/harnesses/agent-hub/footer.ts +35 -0
  76. package/.versions/1.0.2/.pi/harnesses/agent-hub/helpers.ts +266 -0
  77. package/.versions/1.0.2/.pi/harnesses/agent-hub/hub-state-audit.js +73 -0
  78. package/.versions/1.0.2/.pi/harnesses/agent-hub/index.ts +9909 -0
  79. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  80. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  81. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  82. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  83. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  84. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  85. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  86. package/.versions/1.0.2/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  87. package/.versions/1.0.2/.pi/harnesses/agent-hub/package.json +7 -0
  88. package/.versions/1.0.2/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  89. package/.versions/1.0.2/.pi/harnesses/agent-hub/posture.ts +158 -0
  90. package/.versions/1.0.2/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  91. package/.versions/1.0.2/.pi/harnesses/agent-hub/research-retention.js +34 -0
  92. package/.versions/1.0.2/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  93. package/.versions/1.0.2/.pi/harnesses/agent-hub/return-contract.js +293 -0
  94. package/.versions/1.0.2/.pi/harnesses/agent-hub/return-extract.js +75 -0
  95. package/.versions/1.0.2/.pi/harnesses/agent-hub/review-findings.js +102 -0
  96. package/.versions/1.0.2/.pi/harnesses/agent-hub/run-budget.js +539 -0
  97. package/.versions/1.0.2/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  98. package/.versions/1.0.2/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  99. package/.versions/1.0.2/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  100. package/.versions/1.0.2/.pi/harnesses/agent-hub/session-health.js +110 -0
  101. package/.versions/1.0.2/.pi/harnesses/agent-hub/spawn.ts +366 -0
  102. package/.versions/1.0.2/.pi/harnesses/agent-hub/version.ts +42 -0
  103. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/README.md +53 -0
  104. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/index.ts +532 -0
  105. package/.versions/1.0.2/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  106. package/.versions/1.0.2/.pi/harnesses/coms/README.md +100 -0
  107. package/.versions/1.0.2/.pi/harnesses/coms/index.ts +1767 -0
  108. package/.versions/1.0.2/.pi/harnesses/coms/package.json +7 -0
  109. package/.versions/1.0.2/.pi/harnesses/coms/version.ts +42 -0
  110. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/README.md +124 -0
  111. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/index.ts +536 -0
  112. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/package.json +7 -0
  113. package/.versions/1.0.2/.pi/harnesses/damage-control-continue/version.ts +42 -0
  114. package/.versions/1.0.2/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  115. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  116. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  117. package/.versions/1.0.2/.pi/harnesses/lib/context-budget-view.ts +107 -0
  118. package/.versions/1.0.2/.pi/harnesses/lib/context-budget.ts +114 -0
  119. package/.versions/1.0.2/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  120. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  121. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  122. package/.versions/1.0.2/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  123. package/.versions/1.0.2/.pi/harnesses/lib/fleet-dashboard-ops.ts +155 -0
  124. package/.versions/1.0.2/.pi/harnesses/lib/fleet-dashboard-view.ts +140 -0
  125. package/.versions/1.0.2/.pi/harnesses/lib/fleet-detail-view.ts +133 -0
  126. package/.versions/1.0.2/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  127. package/.versions/1.0.2/.pi/harnesses/lib/fleet-panel.ts +34 -0
  128. package/.versions/1.0.2/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  129. package/.versions/1.0.2/.pi/harnesses/lib/fleet-selection.ts +24 -0
  130. package/.versions/1.0.2/.pi/harnesses/lib/herdr-client.ts +472 -0
  131. package/.versions/1.0.2/.pi/harnesses/lib/herdr-presence.ts +399 -0
  132. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  133. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  134. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  135. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  136. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  137. package/.versions/1.0.2/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  138. package/.versions/1.0.2/.pi/harnesses/lib/spawned-peers.js +190 -0
  139. package/.versions/1.0.2/.pi/harnesses/package-lock.json +2039 -0
  140. package/.versions/1.0.2/.pi/harnesses/package.json +10 -0
  141. package/.versions/1.0.2/.pi/prompts/af-build.md +24 -0
  142. package/.versions/1.0.2/.pi/prompts/af-code-simplify.md +22 -0
  143. package/.versions/1.0.2/.pi/prompts/af-plan.md +16 -0
  144. package/.versions/1.0.2/.pi/prompts/af-review.md +16 -0
  145. package/.versions/1.0.2/.pi/prompts/af-set-hermes-telegram.md +15 -0
  146. package/.versions/1.0.2/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  147. package/.versions/1.0.2/.pi/prompts/af-ship.md +17 -0
  148. package/.versions/1.0.2/.pi/prompts/af-spec.md +15 -0
  149. package/.versions/1.0.2/.pi/prompts/af-test.md +19 -0
  150. package/.versions/1.0.2/.pi/skills/bowser/SKILL.md +145 -0
  151. package/.versions/1.0.2/.version +1 -0
  152. package/.versions/1.0.2/agents/architect.md +24 -0
  153. package/.versions/1.0.2/agents/bowser.md +27 -0
  154. package/.versions/1.0.2/agents/builder.md +54 -0
  155. package/.versions/1.0.2/agents/code-reviewer.md +208 -0
  156. package/.versions/1.0.2/agents/deep-researcher.md +32 -0
  157. package/.versions/1.0.2/agents/documenter.md +18 -0
  158. package/.versions/1.0.2/agents/orchestrator.md +20 -0
  159. package/.versions/1.0.2/agents/plan-reviewer.md +83 -0
  160. package/.versions/1.0.2/agents/planner.md +70 -0
  161. package/.versions/1.0.2/agents/releaser.md +24 -0
  162. package/.versions/1.0.2/agents/researcher.md +28 -0
  163. package/.versions/1.0.2/agents/security-auditor.md +167 -0
  164. package/.versions/1.0.2/agents/test-engineer.md +153 -0
  165. package/.versions/1.0.2/agents/web-debugger.md +43 -0
  166. package/.versions/1.0.2/agents/web-performance-auditor.md +193 -0
  167. package/.versions/1.0.2/bin/catalog/harness-runtime-closure.json +38 -0
  168. package/.versions/1.0.2/codex/CONDUCTOR.md +148 -0
  169. package/.versions/1.0.2/docs/ARCHITECTURE.md +369 -0
  170. package/.versions/1.0.2/docs/agent-fleet-setup.md +468 -0
  171. package/.versions/1.0.2/docs/claude-code-coms-bridge.md +128 -0
  172. package/.versions/1.0.2/docs/codex-remote-conductor.md +170 -0
  173. package/.versions/1.0.2/docs/coms-hermes-bridge.md +189 -0
  174. package/.versions/1.0.2/docs/getting-started.md +98 -0
  175. package/.versions/1.0.2/docs/npm-install.md +292 -0
  176. package/.versions/1.0.2/docs/pi-extensions.md +439 -0
  177. package/.versions/1.0.2/docs/pi-setup.md +74 -0
  178. package/.versions/1.0.2/docs/skill-anatomy.md +150 -0
  179. package/.versions/1.0.2/hermes/README.md +347 -0
  180. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  181. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  182. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  183. package/.versions/1.0.2/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  184. package/.versions/1.0.2/hermes/gates/gate-o-capability.md +8 -0
  185. package/.versions/1.0.2/hermes/gates/gate-o-validator-fixtures.json +1 -0
  186. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  187. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  188. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  189. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  190. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  191. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  192. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  193. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  194. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  195. package/.versions/1.0.2/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  196. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  197. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  198. package/.versions/1.0.2/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  199. package/.versions/1.0.2/hermes/skills/hub-conductor/SKILL.md +84 -0
  200. package/.versions/1.0.2/hermes/skills/hub-liaison/SKILL.md +84 -0
  201. package/.versions/1.0.2/hermes/skills/hub-watchdog/SKILL.md +76 -0
  202. package/.versions/1.0.2/hermes/skills/hub-watchdog/manifest.json +1 -0
  203. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  204. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  205. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  206. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  207. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  208. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  209. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  210. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  211. package/.versions/1.0.2/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  212. package/.versions/1.0.2/hermes/watchdog-tests/__init__.py +0 -0
  213. package/.versions/1.0.2/hooks/coms-stop-hook.mjs +84 -0
  214. package/.versions/1.0.2/install-manifest.json +2745 -0
  215. package/.versions/1.0.2/justfile +272 -0
  216. package/.versions/1.0.2/manifest-meta.json +882 -0
  217. package/.versions/1.0.2/references/accessibility-checklist.md +160 -0
  218. package/.versions/1.0.2/references/definition-of-done.md +67 -0
  219. package/.versions/1.0.2/references/fleet-coordination-patterns.md +151 -0
  220. package/.versions/1.0.2/references/observability-checklist.md +91 -0
  221. package/.versions/1.0.2/references/orchestration-patterns.md +370 -0
  222. package/.versions/1.0.2/references/performance-checklist.md +153 -0
  223. package/.versions/1.0.2/references/prompting-patterns.md +380 -0
  224. package/.versions/1.0.2/references/security-checklist.md +179 -0
  225. package/.versions/1.0.2/references/testing-patterns.md +236 -0
  226. package/.versions/1.0.2/scripts/codex-conductor.ts +41 -0
  227. package/.versions/1.0.2/scripts/codex-remote-control.ts +167 -0
  228. package/.versions/1.0.2/scripts/coms-claude-bridge.ts +411 -0
  229. package/.versions/1.0.2/scripts/coms-cli.ts +484 -0
  230. package/.versions/1.0.2/scripts/coms-hermes-bridge.ts +413 -0
  231. package/.versions/1.0.2/scripts/fleet.ts +185 -0
  232. package/.versions/1.0.2/scripts/hermes-monitor-capability-runner.ts +25 -0
  233. package/.versions/1.0.2/scripts/hermes-monitor-scenario.ts +474 -0
  234. package/.versions/1.0.2/scripts/hermes-watchdog-capability-probe.ts +45 -0
  235. package/.versions/1.0.2/scripts/install-hermes-plugin.sh +180 -0
  236. package/.versions/1.0.2/scripts/lib/claude-bridge-core.ts +210 -0
  237. package/.versions/1.0.2/scripts/lib/codex-conductor.ts +88 -0
  238. package/.versions/1.0.2/scripts/lib/codex-remote-control.ts +480 -0
  239. package/.versions/1.0.2/scripts/lib/coms-envelope.ts +582 -0
  240. package/.versions/1.0.2/scripts/lib/fake-herdr-server.ts +88 -0
  241. package/.versions/1.0.2/scripts/lib/fleet-command.ts +266 -0
  242. package/.versions/1.0.2/scripts/lib/herdr-layout.ts +281 -0
  243. package/.versions/1.0.2/scripts/lib/hermes-bridge-core.ts +241 -0
  244. package/.versions/1.0.2/scripts/lib/hermes-monitor-events.ts +1 -0
  245. package/.versions/1.0.2/scripts/lib/hermes-monitor-herdr.ts +2 -0
  246. package/.versions/1.0.2/scripts/lib/hermes-monitor-model.ts +3 -0
  247. package/.versions/1.0.2/scripts/lib/hermes-monitor-registry.ts +2 -0
  248. package/.versions/1.0.2/scripts/lib/hermes-monitor-socket.ts +2 -0
  249. package/.versions/1.0.2/scripts/lib/hermes-monitor-store.ts +2 -0
  250. package/.versions/1.0.2/scripts/lib/monitor-env.ts +146 -0
  251. package/.versions/1.0.2/scripts/lib/peer-launch.ts +318 -0
  252. package/.versions/1.0.2/scripts/lib/persona-banner.ts +62 -0
  253. package/.versions/1.0.2/scripts/lib/spawn-stagger.ts +101 -0
  254. package/.versions/1.0.2/scripts/lib/team-project.ts +213 -0
  255. package/.versions/1.0.2/scripts/lib/team-snapshot.ts +147 -0
  256. package/.versions/1.0.2/scripts/peer-banner.ts +40 -0
  257. package/.versions/1.0.2/scripts/peer-launch.ts +259 -0
  258. package/.versions/1.0.2/scripts/team-snapshot.ts +237 -0
  259. package/.versions/1.0.2/scripts/team-up.ts +406 -0
  260. package/.versions/1.0.2/skills/_internal/grilling.md +11 -0
  261. package/.versions/1.0.2/skills/browser-testing-with-devtools/SKILL.md +351 -0
  262. package/.versions/1.0.2/skills/code-review-and-quality/SKILL.md +381 -0
  263. package/.versions/1.0.2/skills/compound-learning/SKILL.md +137 -0
  264. package/.versions/1.0.2/skills/context-engineering/SKILL.md +291 -0
  265. package/.versions/1.0.2/skills/deprecation-and-migration/SKILL.md +206 -0
  266. package/.versions/1.0.2/skills/designing-agents/SKILL.md +394 -0
  267. package/.versions/1.0.2/skills/designing-agents/pi-harness-authoring.md +222 -0
  268. package/.versions/1.0.2/skills/frontend-ui-engineering/SKILL.md +328 -0
  269. package/.versions/1.0.2/skills/git-workflow-and-versioning/SKILL.md +316 -0
  270. package/.versions/1.0.2/skills/idea-refine/SKILL.md +182 -0
  271. package/.versions/1.0.2/skills/idea-refine/examples.md +238 -0
  272. package/.versions/1.0.2/skills/idea-refine/frameworks.md +99 -0
  273. package/.versions/1.0.2/skills/idea-refine/refinement-criteria.md +113 -0
  274. package/.versions/1.0.2/skills/idea-refine/scripts/idea-refine.sh +15 -0
  275. package/.versions/1.0.2/skills/incremental-implementation/SKILL.md +287 -0
  276. package/.versions/1.0.2/skills/interview-me/SKILL.md +226 -0
  277. package/.versions/1.0.2/skills/orchestration-verification/SKILL.md +181 -0
  278. package/.versions/1.0.2/skills/peer-coms/SKILL.md +90 -0
  279. package/.versions/1.0.2/skills/performance-optimization/SKILL.md +350 -0
  280. package/.versions/1.0.2/skills/planning-and-task-breakdown/SKILL.md +254 -0
  281. package/.versions/1.0.2/skills/security-and-hardening/SKILL.md +461 -0
  282. package/.versions/1.0.2/skills/spec-driven-development/SKILL.md +257 -0
  283. package/.versions/1.0.2/skills/using-agent-skills/SKILL.md +199 -0
  284. package/.versions/1.0.2/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  285. package/.versions/1.0.2/vendor/agent-skills-upstream/LICENSE +21 -0
  286. package/.versions/1.0.2/vendor/agent-skills-upstream/README.md +11 -0
  287. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  288. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  289. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  290. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  291. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  292. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  293. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  294. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  295. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  296. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  297. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  298. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  299. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  300. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  301. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  302. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  303. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  304. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  305. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  306. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  307. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  308. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  309. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  310. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  311. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  312. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  313. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  314. package/.versions/1.0.2/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  315. package/.versions/1.0.3/.pi/agents/dispatch-policy.yaml +32 -0
  316. package/.versions/1.0.3/.pi/agents/model-profiles.yaml +27 -0
  317. package/.versions/1.0.3/.pi/agents/peers.yaml +142 -0
  318. package/.versions/1.0.3/.pi/agents/teams.yaml +41 -0
  319. package/.versions/1.0.3/.pi/damage-control-rules.yaml +297 -0
  320. package/.versions/1.0.3/.pi/extensions/agent-fleet-update-check/README.md +57 -0
  321. package/.versions/1.0.3/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  322. package/.versions/1.0.3/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  323. package/.versions/1.0.3/.pi/extensions/btw/README.md +120 -0
  324. package/.versions/1.0.3/.pi/extensions/btw/index.ts +914 -0
  325. package/.versions/1.0.3/.pi/extensions/btw/package.json +6 -0
  326. package/.versions/1.0.3/.pi/extensions/btw/state.js +179 -0
  327. package/.versions/1.0.3/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  328. package/.versions/1.0.3/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  329. package/.versions/1.0.3/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  330. package/.versions/1.0.3/.pi/extensions/compact-and-continue/README.md +42 -0
  331. package/.versions/1.0.3/.pi/extensions/compact-and-continue/index.ts +120 -0
  332. package/.versions/1.0.3/.pi/extensions/compact-and-continue/package.json +6 -0
  333. package/.versions/1.0.3/.pi/extensions/mcp-bridge/README.md +46 -0
  334. package/.versions/1.0.3/.pi/extensions/mcp-bridge/index.ts +206 -0
  335. package/.versions/1.0.3/.pi/extensions/mcp-bridge/package.json +6 -0
  336. package/.versions/1.0.3/.pi/extensions/package-lock.json +1175 -0
  337. package/.versions/1.0.3/.pi/extensions/package.json +9 -0
  338. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/README.md +205 -0
  339. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/config.ts +198 -0
  340. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  341. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/index.ts +248 -0
  342. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/package.json +6 -0
  343. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  344. package/.versions/1.0.3/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  345. package/.versions/1.0.3/.pi/harnesses/agent-hub/README.md +1156 -0
  346. package/.versions/1.0.3/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  347. package/.versions/1.0.3/.pi/harnesses/agent-hub/artifacts.js +146 -0
  348. package/.versions/1.0.3/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  349. package/.versions/1.0.3/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  350. package/.versions/1.0.3/.pi/harnesses/agent-hub/budget-continuation.ts +73 -0
  351. package/.versions/1.0.3/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  352. package/.versions/1.0.3/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  353. package/.versions/1.0.3/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  354. package/.versions/1.0.3/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  355. package/.versions/1.0.3/.pi/harnesses/agent-hub/context-window.js +106 -0
  356. package/.versions/1.0.3/.pi/harnesses/agent-hub/delegate.ts +435 -0
  357. package/.versions/1.0.3/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  358. package/.versions/1.0.3/.pi/harnesses/agent-hub/drift-watchdog.js +218 -0
  359. package/.versions/1.0.3/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  360. package/.versions/1.0.3/.pi/harnesses/agent-hub/execution-profile.ts +69 -0
  361. package/.versions/1.0.3/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  362. package/.versions/1.0.3/.pi/harnesses/agent-hub/footer.ts +36 -0
  363. package/.versions/1.0.3/.pi/harnesses/agent-hub/helpers.ts +266 -0
  364. package/.versions/1.0.3/.pi/harnesses/agent-hub/hub-state-audit.js +59 -0
  365. package/.versions/1.0.3/.pi/harnesses/agent-hub/index.ts +9999 -0
  366. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  367. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  368. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  369. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  370. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  371. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  372. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  373. package/.versions/1.0.3/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  374. package/.versions/1.0.3/.pi/harnesses/agent-hub/package.json +7 -0
  375. package/.versions/1.0.3/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  376. package/.versions/1.0.3/.pi/harnesses/agent-hub/posture.ts +158 -0
  377. package/.versions/1.0.3/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  378. package/.versions/1.0.3/.pi/harnesses/agent-hub/research-retention.js +34 -0
  379. package/.versions/1.0.3/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  380. package/.versions/1.0.3/.pi/harnesses/agent-hub/return-contract.js +293 -0
  381. package/.versions/1.0.3/.pi/harnesses/agent-hub/return-extract.js +75 -0
  382. package/.versions/1.0.3/.pi/harnesses/agent-hub/review-findings.js +102 -0
  383. package/.versions/1.0.3/.pi/harnesses/agent-hub/run-budget.js +537 -0
  384. package/.versions/1.0.3/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  385. package/.versions/1.0.3/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  386. package/.versions/1.0.3/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  387. package/.versions/1.0.3/.pi/harnesses/agent-hub/session-health.js +110 -0
  388. package/.versions/1.0.3/.pi/harnesses/agent-hub/spawn.ts +366 -0
  389. package/.versions/1.0.3/.pi/harnesses/agent-hub/version.ts +42 -0
  390. package/.versions/1.0.3/.pi/harnesses/ask-user-remote/README.md +53 -0
  391. package/.versions/1.0.3/.pi/harnesses/ask-user-remote/index.ts +532 -0
  392. package/.versions/1.0.3/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  393. package/.versions/1.0.3/.pi/harnesses/coms/README.md +100 -0
  394. package/.versions/1.0.3/.pi/harnesses/coms/index.ts +1767 -0
  395. package/.versions/1.0.3/.pi/harnesses/coms/package.json +7 -0
  396. package/.versions/1.0.3/.pi/harnesses/coms/version.ts +42 -0
  397. package/.versions/1.0.3/.pi/harnesses/damage-control-continue/README.md +124 -0
  398. package/.versions/1.0.3/.pi/harnesses/damage-control-continue/index.ts +536 -0
  399. package/.versions/1.0.3/.pi/harnesses/damage-control-continue/package.json +7 -0
  400. package/.versions/1.0.3/.pi/harnesses/damage-control-continue/version.ts +42 -0
  401. package/.versions/1.0.3/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  402. package/.versions/1.0.3/.pi/harnesses/lib/context-budget-child-prompt.ts +179 -0
  403. package/.versions/1.0.3/.pi/harnesses/lib/context-budget-hub-prompt.ts +116 -0
  404. package/.versions/1.0.3/.pi/harnesses/lib/context-budget-view.ts +107 -0
  405. package/.versions/1.0.3/.pi/harnesses/lib/context-budget.ts +114 -0
  406. package/.versions/1.0.3/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  407. package/.versions/1.0.3/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  408. package/.versions/1.0.3/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  409. package/.versions/1.0.3/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  410. package/.versions/1.0.3/.pi/harnesses/lib/fleet-dashboard-ops.ts +155 -0
  411. package/.versions/1.0.3/.pi/harnesses/lib/fleet-dashboard-view.ts +142 -0
  412. package/.versions/1.0.3/.pi/harnesses/lib/fleet-detail-view.ts +168 -0
  413. package/.versions/1.0.3/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  414. package/.versions/1.0.3/.pi/harnesses/lib/fleet-panel.ts +34 -0
  415. package/.versions/1.0.3/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  416. package/.versions/1.0.3/.pi/harnesses/lib/fleet-selection.ts +24 -0
  417. package/.versions/1.0.3/.pi/harnesses/lib/herdr-client.ts +472 -0
  418. package/.versions/1.0.3/.pi/harnesses/lib/herdr-presence.ts +399 -0
  419. package/.versions/1.0.3/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  420. package/.versions/1.0.3/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  421. package/.versions/1.0.3/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  422. package/.versions/1.0.3/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  423. package/.versions/1.0.3/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  424. package/.versions/1.0.3/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  425. package/.versions/1.0.3/.pi/harnesses/lib/spawned-peers.js +190 -0
  426. package/.versions/1.0.3/.pi/harnesses/package-lock.json +2039 -0
  427. package/.versions/1.0.3/.pi/harnesses/package.json +10 -0
  428. package/.versions/1.0.3/.pi/prompts/af-build.md +24 -0
  429. package/.versions/1.0.3/.pi/prompts/af-code-simplify.md +22 -0
  430. package/.versions/1.0.3/.pi/prompts/af-plan.md +16 -0
  431. package/.versions/1.0.3/.pi/prompts/af-review.md +16 -0
  432. package/.versions/1.0.3/.pi/prompts/af-set-hermes-telegram.md +15 -0
  433. package/.versions/1.0.3/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  434. package/.versions/1.0.3/.pi/prompts/af-ship.md +17 -0
  435. package/.versions/1.0.3/.pi/prompts/af-spec.md +15 -0
  436. package/.versions/1.0.3/.pi/prompts/af-test.md +19 -0
  437. package/.versions/1.0.3/.pi/skills/bowser/SKILL.md +145 -0
  438. package/.versions/1.0.3/.version +1 -0
  439. package/.versions/1.0.3/agents/architect.md +25 -0
  440. package/.versions/1.0.3/agents/bowser.md +28 -0
  441. package/.versions/1.0.3/agents/builder.md +55 -0
  442. package/.versions/1.0.3/agents/code-reviewer.md +209 -0
  443. package/.versions/1.0.3/agents/deep-researcher.md +33 -0
  444. package/.versions/1.0.3/agents/documenter.md +19 -0
  445. package/.versions/1.0.3/agents/orchestrator.md +21 -0
  446. package/.versions/1.0.3/agents/plan-reviewer.md +84 -0
  447. package/.versions/1.0.3/agents/planner.md +71 -0
  448. package/.versions/1.0.3/agents/releaser.md +25 -0
  449. package/.versions/1.0.3/agents/researcher.md +29 -0
  450. package/.versions/1.0.3/agents/security-auditor.md +168 -0
  451. package/.versions/1.0.3/agents/test-engineer.md +154 -0
  452. package/.versions/1.0.3/agents/web-debugger.md +44 -0
  453. package/.versions/1.0.3/agents/web-performance-auditor.md +194 -0
  454. package/.versions/1.0.3/bin/catalog/harness-runtime-closure.json +38 -0
  455. package/.versions/1.0.3/codex/CONDUCTOR.md +148 -0
  456. package/.versions/1.0.3/docs/ARCHITECTURE.md +375 -0
  457. package/.versions/1.0.3/docs/agent-fleet-setup.md +468 -0
  458. package/.versions/1.0.3/docs/claude-code-coms-bridge.md +128 -0
  459. package/.versions/1.0.3/docs/codex-remote-conductor.md +170 -0
  460. package/.versions/1.0.3/docs/coms-hermes-bridge.md +189 -0
  461. package/.versions/1.0.3/docs/getting-started.md +98 -0
  462. package/.versions/1.0.3/docs/npm-install.md +292 -0
  463. package/.versions/1.0.3/docs/pi-extensions.md +441 -0
  464. package/.versions/1.0.3/docs/pi-setup.md +74 -0
  465. package/.versions/1.0.3/docs/skill-anatomy.md +150 -0
  466. package/.versions/1.0.3/hermes/README.md +347 -0
  467. package/.versions/1.0.3/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  468. package/.versions/1.0.3/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  469. package/.versions/1.0.3/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  470. package/.versions/1.0.3/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  471. package/.versions/1.0.3/hermes/gates/gate-o-capability.md +8 -0
  472. package/.versions/1.0.3/hermes/gates/gate-o-validator-fixtures.json +1 -0
  473. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  474. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  475. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  476. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  477. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  478. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  479. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  480. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  481. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  482. package/.versions/1.0.3/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  483. package/.versions/1.0.3/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  484. package/.versions/1.0.3/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  485. package/.versions/1.0.3/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  486. package/.versions/1.0.3/hermes/skills/hub-conductor/SKILL.md +84 -0
  487. package/.versions/1.0.3/hermes/skills/hub-liaison/SKILL.md +84 -0
  488. package/.versions/1.0.3/hermes/skills/hub-watchdog/SKILL.md +76 -0
  489. package/.versions/1.0.3/hermes/skills/hub-watchdog/manifest.json +1 -0
  490. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  491. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  492. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  493. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  494. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  495. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  496. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  497. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  498. package/.versions/1.0.3/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  499. package/.versions/1.0.3/hermes/watchdog-tests/__init__.py +0 -0
  500. package/.versions/1.0.3/hooks/coms-stop-hook.mjs +84 -0
  501. package/.versions/1.0.3/install-manifest.json +2745 -0
  502. package/.versions/1.0.3/justfile +272 -0
  503. package/.versions/1.0.3/manifest-meta.json +882 -0
  504. package/.versions/1.0.3/references/accessibility-checklist.md +160 -0
  505. package/.versions/1.0.3/references/definition-of-done.md +67 -0
  506. package/.versions/1.0.3/references/fleet-coordination-patterns.md +151 -0
  507. package/.versions/1.0.3/references/observability-checklist.md +91 -0
  508. package/.versions/1.0.3/references/orchestration-patterns.md +370 -0
  509. package/.versions/1.0.3/references/performance-checklist.md +153 -0
  510. package/.versions/1.0.3/references/prompting-patterns.md +380 -0
  511. package/.versions/1.0.3/references/security-checklist.md +179 -0
  512. package/.versions/1.0.3/references/testing-patterns.md +236 -0
  513. package/.versions/1.0.3/scripts/codex-conductor.ts +41 -0
  514. package/.versions/1.0.3/scripts/codex-remote-control.ts +167 -0
  515. package/.versions/1.0.3/scripts/coms-claude-bridge.ts +411 -0
  516. package/.versions/1.0.3/scripts/coms-cli.ts +484 -0
  517. package/.versions/1.0.3/scripts/coms-hermes-bridge.ts +413 -0
  518. package/.versions/1.0.3/scripts/fleet.ts +185 -0
  519. package/.versions/1.0.3/scripts/hermes-monitor-capability-runner.ts +25 -0
  520. package/.versions/1.0.3/scripts/hermes-monitor-scenario.ts +474 -0
  521. package/.versions/1.0.3/scripts/hermes-watchdog-capability-probe.ts +45 -0
  522. package/.versions/1.0.3/scripts/install-hermes-plugin.sh +180 -0
  523. package/.versions/1.0.3/scripts/lib/claude-bridge-core.ts +210 -0
  524. package/.versions/1.0.3/scripts/lib/codex-conductor.ts +88 -0
  525. package/.versions/1.0.3/scripts/lib/codex-remote-control.ts +480 -0
  526. package/.versions/1.0.3/scripts/lib/coms-envelope.ts +582 -0
  527. package/.versions/1.0.3/scripts/lib/fake-herdr-server.ts +88 -0
  528. package/.versions/1.0.3/scripts/lib/fleet-command.ts +266 -0
  529. package/.versions/1.0.3/scripts/lib/herdr-layout.ts +281 -0
  530. package/.versions/1.0.3/scripts/lib/hermes-bridge-core.ts +241 -0
  531. package/.versions/1.0.3/scripts/lib/hermes-monitor-events.ts +1 -0
  532. package/.versions/1.0.3/scripts/lib/hermes-monitor-herdr.ts +2 -0
  533. package/.versions/1.0.3/scripts/lib/hermes-monitor-model.ts +3 -0
  534. package/.versions/1.0.3/scripts/lib/hermes-monitor-registry.ts +2 -0
  535. package/.versions/1.0.3/scripts/lib/hermes-monitor-socket.ts +2 -0
  536. package/.versions/1.0.3/scripts/lib/hermes-monitor-store.ts +2 -0
  537. package/.versions/1.0.3/scripts/lib/monitor-env.ts +146 -0
  538. package/.versions/1.0.3/scripts/lib/peer-launch.ts +318 -0
  539. package/.versions/1.0.3/scripts/lib/persona-banner.ts +62 -0
  540. package/.versions/1.0.3/scripts/lib/spawn-stagger.ts +101 -0
  541. package/.versions/1.0.3/scripts/lib/team-project.ts +213 -0
  542. package/.versions/1.0.3/scripts/lib/team-snapshot.ts +147 -0
  543. package/.versions/1.0.3/scripts/peer-banner.ts +40 -0
  544. package/.versions/1.0.3/scripts/peer-launch.ts +259 -0
  545. package/.versions/1.0.3/scripts/team-snapshot.ts +237 -0
  546. package/.versions/1.0.3/scripts/team-up.ts +406 -0
  547. package/.versions/1.0.3/skills/_internal/grilling.md +11 -0
  548. package/.versions/1.0.3/skills/browser-testing-with-devtools/SKILL.md +351 -0
  549. package/.versions/1.0.3/skills/code-review-and-quality/SKILL.md +381 -0
  550. package/.versions/1.0.3/skills/compound-learning/SKILL.md +137 -0
  551. package/.versions/1.0.3/skills/context-engineering/SKILL.md +291 -0
  552. package/.versions/1.0.3/skills/deprecation-and-migration/SKILL.md +206 -0
  553. package/.versions/1.0.3/skills/designing-agents/SKILL.md +394 -0
  554. package/.versions/1.0.3/skills/designing-agents/pi-harness-authoring.md +222 -0
  555. package/.versions/1.0.3/skills/frontend-ui-engineering/SKILL.md +328 -0
  556. package/.versions/1.0.3/skills/git-workflow-and-versioning/SKILL.md +316 -0
  557. package/.versions/1.0.3/skills/idea-refine/SKILL.md +182 -0
  558. package/.versions/1.0.3/skills/idea-refine/examples.md +238 -0
  559. package/.versions/1.0.3/skills/idea-refine/frameworks.md +99 -0
  560. package/.versions/1.0.3/skills/idea-refine/refinement-criteria.md +113 -0
  561. package/.versions/1.0.3/skills/idea-refine/scripts/idea-refine.sh +15 -0
  562. package/.versions/1.0.3/skills/incremental-implementation/SKILL.md +287 -0
  563. package/.versions/1.0.3/skills/interview-me/SKILL.md +226 -0
  564. package/.versions/1.0.3/skills/orchestration-verification/SKILL.md +181 -0
  565. package/.versions/1.0.3/skills/peer-coms/SKILL.md +90 -0
  566. package/.versions/1.0.3/skills/performance-optimization/SKILL.md +350 -0
  567. package/.versions/1.0.3/skills/planning-and-task-breakdown/SKILL.md +254 -0
  568. package/.versions/1.0.3/skills/security-and-hardening/SKILL.md +461 -0
  569. package/.versions/1.0.3/skills/spec-driven-development/SKILL.md +257 -0
  570. package/.versions/1.0.3/skills/using-agent-skills/SKILL.md +199 -0
  571. package/.versions/1.0.3/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  572. package/.versions/1.0.3/vendor/agent-skills-upstream/LICENSE +21 -0
  573. package/.versions/1.0.3/vendor/agent-skills-upstream/README.md +11 -0
  574. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  575. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  576. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  577. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  578. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  579. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  580. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  581. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  582. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  583. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  584. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  585. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  586. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  587. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  588. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  589. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  590. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  591. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  592. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  593. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  594. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  595. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  596. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  597. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  598. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  599. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  600. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  601. package/.versions/1.0.3/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  602. package/CHANGELOG.md +15 -0
  603. package/README.md +8 -5
  604. package/agents/architect.md +1 -0
  605. package/agents/bowser.md +1 -0
  606. package/agents/builder.md +1 -0
  607. package/agents/code-reviewer.md +1 -0
  608. package/agents/deep-researcher.md +1 -0
  609. package/agents/documenter.md +1 -0
  610. package/agents/orchestrator.md +5 -56
  611. package/agents/plan-reviewer.md +1 -0
  612. package/agents/planner.md +1 -0
  613. package/agents/releaser.md +1 -0
  614. package/agents/researcher.md +1 -0
  615. package/agents/security-auditor.md +1 -0
  616. package/agents/test-engineer.md +1 -0
  617. package/agents/web-debugger.md +1 -0
  618. package/agents/web-performance-auditor.md +1 -0
  619. package/bin/lib/validate-overrides.js +1 -1
  620. package/docs/ARCHITECTURE.md +72 -34
  621. package/docs/agent-fleet-setup.md +39 -8
  622. package/docs/pi-extensions.md +33 -4
  623. package/install-manifest.json +2 -2
  624. package/package.json +2 -2
  625. package/scripts/fleet.ts +1 -1
@@ -17,12 +17,13 @@
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
23
24
  * level (off|minimal|low|medium|high|xhigh)
24
25
  * /af-models [profile] — apply a named model profile (.pi/agents/model-profiles.yaml)
25
- * /af-agent-models-substitute <source> <target> — swap one model across all personas
26
+ * /af-agent-models-substitute [<source> <target>] — visually pick/save a session-wide model substitution
26
27
  * /af-dispatch-policy — show which members route to coms peers (.pi/agents/dispatch-policy.yaml)
27
28
  * /af-agents-kill <name|rN|all> — SIGTERM a frozen specialist (and its delegation
28
29
  * tree); on a research helper it kills AND removes the
@@ -34,6 +35,9 @@
34
35
  * (team member, research helper rN, or delegate child id)
35
36
  * /af-research <task> — spawn a read-only research helper (@persona, --model)
36
37
  * /af-agents-cont rN ... — resume a finished research helper (alias: /af-research-cont)
38
+ * /af-work-mode [operator|orchestrator]
39
+ * — posture picker (alias of /af-posture; Alt+M)
40
+ * /af-posture [operator|orchestrator] — show/switch direct vs delegate-only
37
41
  *
38
42
  * Finished research helpers are auto-pruned: auto-research pipe helpers as soon
39
43
  * as they finish (findings persist as files under findings/), manual/persona
@@ -46,9 +50,9 @@
46
50
  * documenter to land them in the project's rules/docs
47
51
  *
48
52
  * Shortcuts:
49
- * Alt+A — toggle agent view: dashboard grid (above editor) ↔
50
- * compact running-agents list (below editor: one line
51
- * per *running* agent — name · context · state)
53
+ * Alt+A — open the Fleet Dashboard
54
+ * Alt+M — open the posture picker (operator | orchestrator)
55
+ * Alt+Shift+A — toggle the compact running-agents widget
52
56
  * Alt+] / Alt+[ — compact view: mark next/previous running subagent
53
57
  * Alt+\ — compact view: zoom the marked subagent (Q/Esc closes)
54
58
  *
@@ -62,7 +66,7 @@
62
66
  * Direct guarded launch: pi -e .pi/harnesses/damage-control-continue/index.ts -e .pi/harnesses/agent-hub/index.ts
63
67
  */
64
68
 
65
- import type { ExtensionAPI, ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
69
+ import type { ExtensionAPI, ExtensionContext, ImageContent, Theme } from "@mariozechner/pi-coding-agent";
66
70
  import { DynamicBorder, getMarkdownTheme as getPiMdTheme, copyToClipboard } from "@mariozechner/pi-coding-agent";
67
71
  import { Type } from "@sinclair/typebox";
68
72
  import {
@@ -88,9 +92,9 @@ import {
88
92
  AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
89
93
  exemptionsFilePath, type AccessRequest,
90
94
  } from "../lib/damage-control-shared.ts";
91
- import { applyModelOverride, clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, resolveStartupRoster, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
92
- import { DEFAULT_HUB_MODE, DEFAULT_TASK_TIER, HUB_MODES, TASK_BUDGET_MULTIPLIER, 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";
95
+ import { applyModelOverride, clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
96
+ import { DEFAULT_TASK_TIER, addTaskClockWait, applyTierChange, blockingFindingCap, budgetStatusLine, checkReviewRoundCap, checkTaskBudget, checkTierPersonaGate, checkTurnBudget, closeTaskClock, contextOverflowDiagnostic, createTaskClock, isReviewPersona, openTaskClock, remainingTaskResearch, resetTaskClock, resolveTaskBudget, resolveTurnBudget, reviewBudgetClause, reviewRoundCap, shouldRecycleSession, taskClockElapsedMs } from "./run-budget.js";
97
+ import { buildBudgetContinuationAudit, buildHubAuditIdentity, buildTaskResetAudit } from "./hub-state-audit.js";
94
98
  import { countReviewFindings, findingBudgetNotice } from "./review-findings.js";
95
99
  import { checkDocsLane, docsLaneNotice } from "./docs-lane.js";
96
100
  import { checkExternalBlockerGate, externalBlockedProtocol, extractExternalBlockers } from "./external-blocker.js";
@@ -115,7 +119,19 @@ import { crossCheck, deliveryDisposition, extractAssertionIds, parseDeliveredRet
115
119
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
116
120
  import { validateEvidence } from "./evidence-rules.js";
117
121
  import { comsRequiredRefusal, explicitComsRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
118
- import { parsePosture, posturePrompt, resolvePostureTools, resolveSessionPosture, type Posture } from "./posture.ts";
122
+ import { NATIVE_ROSTER_ENTRY_TYPE, parsePosture, persistedNativeRosterState, posturePrompt, resolvePostureTools, resolveSessionPosture, resolveSessionRoster, type Posture } from "./posture.ts";
123
+ import {
124
+ compactPosture,
125
+ executionPairBlockedByRoster,
126
+ parseWorkModeArgs,
127
+ posturePickerOptions,
128
+ selectedPickerValue,
129
+ } from "./execution-profile.ts";
130
+ import { CAPABILITY_PACKS, latestPersistedCapabilityState, persistedCapabilityState, resolveCapabilityPacks, type CapabilityPack, type CapabilityResolution, type ContextState, type PendingOperation } from "./capability-packs.ts";
131
+ import { contextPressureDiagnostic, createContextPressureState, transitionContextPressure, type ContextPressureState } from "./context-pressure.ts";
132
+ import { confirmationGate, confirmationOutcome, capabilityConfirmationPack, capabilityConfirmationQuestion, type CapabilityConfirmationState, type ConfirmableCapabilityPack } from "./capability-confirmation.ts";
133
+ import { budgetContinuationInstruction, budgetContinuationKind, budgetContinuationOutcome, turnBudgetActiveMs, type BudgetContinuationKind } from "./budget-continuation.ts";
134
+ import { observeAskUserResults } from "../ask-user-remote/index.ts";
119
135
  import { buildHubPeerSpawnPlan, launchHubPeerInPane } from "./peer-spawn-plan.ts";
120
136
  import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
121
137
  import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
@@ -136,8 +152,21 @@ import { createPanelResources } from "../lib/fleet-panel.ts";
136
152
  import { buildFleetRows, fleetTiming, summarise, unionMs, type DelegateInput, type FleetRow, type FleetSource, type PeerInput, type ResearchInput, type SpecialistInput } from "../lib/fleet-read-model.ts";
137
153
  import { attachFleetDashboardTicker, compactWidgetsEnabled, gridColumnsForItems, gridColumnsForSize, liveTimeline, renderCardGrid, resolveFleetKill, resolveFleetRestart } from "../lib/fleet-dashboard-ops.ts";
138
154
  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";
155
+ import { detailContent, detailTransition, fleetModelChoices, modelPickerTransition, normalizeFleetDetailInput, renderFleetDetail, renderFleetModelPicker, renderFleetSubstitutionPicker, DETAIL_CHROME_ROWS, type FleetDetailKey, type FleetModelChoice } from "../lib/fleet-detail-view.ts";
140
156
  import { reconcileSelection, type Selection } from "../lib/fleet-selection.ts";
157
+ import { collectContextBudgetSnapshot, type LivePlane } from "./context-budget-snapshot.ts";
158
+ import { CONTEXT_BUDGET_CHROME_ROWS, contextBudgetTransition, renderContextBudget, type ContextBudgetViewState } from "../lib/context-budget-view.ts";
159
+ import { component, safeSchemaChars, type ContextBudgetComponent } from "../lib/context-budget.ts";
160
+ import { assembleHubSystemPrompt, HUB_HERDR_SECTION, namedHubLedgerParts, recordHubLedger } from "../lib/context-budget-hub-prompt.ts";
161
+ import {
162
+ delegateStandingParts,
163
+ buildSpecialistContextManifest,
164
+ nativeResearchSystemPrompt,
165
+ nativeSpecialistSystemPrompt,
166
+ researchStandingParts,
167
+ type SpecialistContextManifest,
168
+ specialistStandingParts,
169
+ } from "../lib/context-budget-child-prompt.ts";
141
170
  import { parseEnvFile, resolveEnvFilePath } from "../../../scripts/lib/herdr-layout.ts";
142
171
  import { worktreeTag } from "../../../scripts/lib/team-project.ts";
143
172
  import { STAGGER_ENV_VAR, WARMUP_SECONDS, oauthNeedsWarmup } from "../../../scripts/lib/spawn-stagger.ts";
@@ -238,6 +267,8 @@ interface AgentState {
238
267
  // a percentage cannot be compared against a window it was not divided by.
239
268
  contextTokens: number;
240
269
  sessionFile: string | null;
270
+ /** Metadata-only child context retained across research-pause resume. */
271
+ specialistManifest?: SpecialistContextManifest;
241
272
  runCount: number;
242
273
  // Runs served by the CURRENT accumulated session (-c resume chain). Reset on
243
274
  // recycle; drives shouldRecycleSession together with the measured contextPct.
@@ -298,6 +329,7 @@ interface ResearchState {
298
329
  elapsed: number;
299
330
  lastWork: string;
300
331
  contextPct: number;
332
+ contextTokens: number;
301
333
  sessionFile: string | null; // set after a successful run → enables `-c` resume
302
334
  turnCount: number;
303
335
  finishedAt?: number; // last time a run ended (any status) — LRU key for retention
@@ -422,14 +454,12 @@ function extractNeedsResearch(output: string): string[] {
422
454
  // recon-search-timeout-s: <1..3600>|off — parent-side deadline for each
423
455
  // read/grep/find/ls call made by research helpers
424
456
  // and read-only delegate children (default 120).
425
- // mode: fast|standard|strict — default execution mode (see run-budget.js).
426
- // fast = single-specialist path, standard = batched
427
- // work with turn budgets (default), strict = full
428
- // Verification Contract with wide budgets.
429
- // max-dispatches-per-turn: <n>|off — dispatch_agent calls allowed per user turn
430
- // (replaces the mode default; "off" = unlimited).
457
+ // mode: — REMOVED. Ignored with a warning; budgets follow
458
+ // task tier (see run-budget.js).
459
+ // max-dispatches-per-turn: <n>|off — ceiling on dispatch_agent calls per user turn
460
+ // (min with the task-tier envelope; "off" stays at the tier).
431
461
  // 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.
462
+ // turn-wall-time-s: <n>|off — active-time budget per user turn (ask_user waits excluded).
433
463
  // agent-turn-timeout-s: <n>|off — whole-run deadline for each spawned
434
464
  // specialist/research/delegate run (not per tool).
435
465
  // session-recycle-runs: <n>|off — recycle a specialist's accumulated session
@@ -458,10 +488,8 @@ interface AgentTeamOverrides {
458
488
  docsPaths: string[];
459
489
  researchKeep: number;
460
490
  reconSearchTimeoutMs: number | null;
461
- hubMode: string;
462
- hubModeSource: "default" | "project-override";
463
- // Per-axis turn-budget overrides for run-budget.js resolveTurnBudget():
464
- // number replaces the mode default, null = "off", undefined = keep default.
491
+ // Per-axis turn-budget ceilings for run-budget.js resolveTurnBudget():
492
+ // number is min()'d with the task tier; null/"off" stays at the tier.
465
493
  budgetOverrides: {
466
494
  maxDispatches?: number | null;
467
495
  maxResearch?: number | null;
@@ -489,8 +517,6 @@ const DEFAULT_OVERRIDES: AgentTeamOverrides = {
489
517
  docsPaths: [],
490
518
  researchKeep: DEFAULT_RESEARCH_KEEP,
491
519
  reconSearchTimeoutMs: 120_000,
492
- hubMode: DEFAULT_HUB_MODE,
493
- hubModeSource: "default",
494
520
  budgetOverrides: {},
495
521
  watchdogSetting: DEFAULT_WATCHDOG_SETTING,
496
522
  watchdogJudgeModel: null,
@@ -573,13 +599,7 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
573
599
  }
574
600
  }
575
601
  if (key === "mode" && value) {
576
- const mode = normalizeHubMode(value);
577
- if (mode) {
578
- result.hubMode = mode;
579
- result.hubModeSource = "project-override";
580
- } else {
581
- result.warnings.push(`mode "${value}" is not one of ${HUB_MODES.join("|")} — using the default (${DEFAULT_HUB_MODE})`);
582
- }
602
+ result.warnings.push(`mode "${value}" is ignored — execution modes were removed; budgets follow task tier. Remove this key.`);
583
603
  }
584
604
  if (key === "watchdog" && value) {
585
605
  const setting = normalizeWatchdogSetting(value);
@@ -590,8 +610,8 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
590
610
  }
591
611
  }
592
612
  if (key === "watchdog-judge-model" && value) result.watchdogJudgeModel = value;
593
- // Turn-budget keys: a positive integer replaces the mode default, "off"
594
- // disables the axis. Counts are unitless; *-s keys are seconds → ms.
613
+ // Turn-budget keys: a positive integer is a ceiling (min with the tier);
614
+ // "off" stays at the tier. Counts are unitless; *-s keys are seconds → ms.
595
615
  const budgetKeys: Record<string, { field: keyof AgentTeamOverrides["budgetOverrides"]; scaleMs: boolean }> = {
596
616
  "max-dispatches-per-turn": { field: "maxDispatches", scaleMs: false },
597
617
  "max-research-per-turn": { field: "maxResearch", scaleMs: false },
@@ -606,7 +626,7 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
606
626
  } else if (/^\d+$/.test(value) && Number(value) >= 1) {
607
627
  result.budgetOverrides[field] = Number(value) * (scaleMs ? 1000 : 1);
608
628
  } else {
609
- result.warnings.push(`${key} "${value}" is not a positive integer or "off" — using the ${result.hubMode} mode default`);
629
+ result.warnings.push(`${key} "${value}" is not a positive integer or "off" — using the task-tier default`);
610
630
  }
611
631
  }
612
632
  const slug = "[a-z0-9]+(?:-[a-z0-9]+)*";
@@ -873,18 +893,6 @@ const CONTEXT_WARN_THRESHOLD = 70;
873
893
  // child spawns reserved tree-wide for a dispatch.
874
894
  const DELEGATE_CALL_BUDGET = DELEGATE_TREE_SPAWN_BUDGET;
875
895
 
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
896
  // System prompt for an ad-hoc (anonymous) research helper — one with no persona file.
889
897
  const ANON_RESEARCH_PROMPT = `# Research Helper
890
898
 
@@ -1854,6 +1862,8 @@ export default function (pi: ExtensionAPI) {
1854
1862
  // Read-only research helpers (Phase 4), keyed by numeric id (handle `rN`). Lives
1855
1863
  // alongside the standing team but renders in its own widget row.
1856
1864
  const researchStates: Map<number, ResearchState> = new Map();
1865
+ // Metadata only: prompt text is never retained by this ledger.
1866
+ let lastHubLedger: ContextBudgetComponent[] = [];
1857
1867
  let nextResearchId = 1;
1858
1868
  // Retention cap for finished durable (manual/persona) helpers — set from the
1859
1869
  // overrides file's `research-keep:` key at session start (default 4, Infinity
@@ -1958,6 +1968,10 @@ export default function (pi: ExtensionAPI) {
1958
1968
  // One "coms peer missing → native" notice per member per team activation.
1959
1969
  const comsMissNotified = new Set<string>();
1960
1970
  const modelOverrides = new Map<string, string>();
1971
+ // Session-wide source → target substitutions. Unlike the eager per-persona map,
1972
+ // these are resolved at spawn time, so personas and delegate roles activated or
1973
+ // created later in the same session inherit the substitution automatically.
1974
+ const modelSubstitutions = new Map<string, string>();
1961
1975
  // Session-lifetime per-persona thinking-level overrides set by
1962
1976
  // /af-agent-model-thinking (lowercase persona name → pi --thinking level). Wins
1963
1977
  // over the persona's frontmatter `thinking:`; resets on session_start; takes
@@ -1966,7 +1980,8 @@ export default function (pi: ExtensionAPI) {
1966
1980
  // Session-lifetime model overrides for delegate sub-roles, set by
1967
1981
  // /af-agent-model <persona>.<role>. Keyed "<persona>.<role>" (lowercase); applied
1968
1982
  // when the dispatch serializes AGENT_HUB_DELEGATE_CONFIG, so nested children
1969
- // inherit them. Resets on session_start. /af-models profiles never touch these.
1983
+ // inherit them. Session-wide source substitutions are resolved after this map.
1984
+ // Resets on session_start. /af-models profiles never touch these.
1970
1985
  const subagentModelOverrides = new Map<string, string>();
1971
1986
  let activeTeamName = "";
1972
1987
  let gridCols = 2;
@@ -2063,6 +2078,12 @@ than bulk-reading doc trees; when an entry point is a folder, start from its REA
2063
2078
  or index file. If your work changes something the docs describe (architecture, public
2064
2079
  APIs, commands, structure), say so in your final response so the docs can be updated.`;
2065
2080
  }
2081
+
2082
+ /** One canonical repository context file plus explicitly configured rule roots. */
2083
+ function specialistProjectPolicyPaths(cwd: string): string[] {
2084
+ const canonical = ["AGENTS.md", "CLAUDE.md"].find(candidate => existsSync(path.join(cwd, candidate)));
2085
+ return [...new Set([...(canonical ? [canonical] : []), ...projectRulesDirs])];
2086
+ }
2066
2087
  // The one supported safety harness. Every native specialist, researcher, and
2067
2088
  // nested delegate receives it; a missing harness refuses child dispatch.
2068
2089
  let safetyHarnessPath: string | null = null;
@@ -2072,28 +2093,36 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2072
2093
  // Per-tool deadline for read/grep/find/ls in research helpers/delegates. The
2073
2094
  // whole-run bound is separate: the turn budget's agentTurnMs (run-budget.js).
2074
2095
  let reconSearchTimeoutMs: number | null = 120_000;
2075
- // ── Execution mode & per-turn budgets (run-budget.js) ──
2076
- // hubMode: overrides-file default, switchable live via /af-hub-mode (session-
2077
- // 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.
2080
- let hubMode: string = DEFAULT_HUB_MODE;
2096
+ // ── Per-turn budgets (run-budget.js) ──
2097
+ // Envelopes follow task tier. Override keys are a ceiling (min with the tier).
2098
+ // Counters reset in before_agent_start, or after an explicit one-click
2099
+ // continuation. currentTurnStartedAt (above) is the active-time base; ask_user
2100
+ // waits are subtracted.
2081
2101
  let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
2082
2102
  let turnDispatchCount = 0;
2083
2103
  let turnResearchCount = 0;
2104
+ // Human wait time is not fleet work. Track it separately from history UI
2105
+ // intervals so a continuation can rebase the budget without erasing history.
2106
+ let turnBudgetAskUserWaitMs = 0;
2107
+ type PendingBudgetContinuation = { kind: BudgetContinuationKind; reason: string };
2108
+ let pendingBudgetContinuation: PendingBudgetContinuation | null = null;
2109
+ const budgetContinuationAsks = new Map<string, { kind: BudgetContinuationKind; reason: string; params: { context?: unknown; options?: unknown } }>();
2110
+ let taskContinuationCount = 0;
2111
+ let turnContinuationCount = 0;
2084
2112
  // ── Task-scoped budget & tier (run-budget.js) ──
2085
2113
  // A per-message allowance cannot bound a task: every steering message opened a
2086
2114
  // fresh turn window, so a run could spend 8 dispatches and 60 minutes again and
2087
2115
  // 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.
2116
+ // and are cleared only by an explicit new task (`set_task_tier` with
2117
+ // `new_task: true`) or an approved task-budget continuation — never by an
2118
+ // ordinary user message.
2090
2119
  let taskDispatchCount = 0;
2091
2120
  let taskResearchCount = 0;
2092
2121
  let taskLabel: string | null = null;
2093
2122
  // The task clock charges ACTIVE time only — turns that ran, minus the time the
2094
2123
  // dispatcher spent blocked on ask_user. Raw wall clock would bill the human's
2095
2124
  // lunch break, an overnight pause, and every long answer against the task, and
2096
- // at fast mode's 45-minute envelope that hard-stops a task with two dispatches
2125
+ // at small tier's 45-minute envelope that hard-stops a task with two dispatches
2097
2126
  // spent. A false stop is worse than no stop: it teaches people to reset the
2098
2127
  // task window reflexively, which is the one thing that must stay deliberate.
2099
2128
  // The explicit clock state makes `active` authoritative: a stale timestamp can
@@ -2104,7 +2133,7 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2104
2133
  // Task tier (complexity triage): declared by the dispatcher via set_task_tier.
2105
2134
  // TASK-scoped, not turn-scoped, and it moves by ratchet — down freely, up only
2106
2135
  // with a stated reason (applyTierChange). Null until declared; the first
2107
- // dispatch assumes DEFAULT_TASK_TIER outside strict mode. Caps = min(mode, tier).
2136
+ // dispatch assumes DEFAULT_TASK_TIER. Caps come from the tier envelope.
2108
2137
  let taskTier: string | null = null;
2109
2138
  // Was the tier ASSUMED by the hub rather than declared by the dispatcher? The
2110
2139
  // distinction matters to the ratchet: an assumed tier must not turn the
@@ -2125,13 +2154,15 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2125
2154
  let runHistoryKeep: number | null = DEFAULT_RUN_HISTORY_KEEP;
2126
2155
  // ── Drift watchdog (drift-watchdog.js) ──
2127
2156
  // Hub-wide setting from the overrides file, live-switchable via /af-watchdog;
2128
- // per-agent overrides ("on"/"off") win over it; a dispatch_agent `watchdog`
2129
- // param wins over both.
2157
+ // per-agent overrides ("on"/"off") win over it. In operator posture a
2158
+ // dispatch_agent `watchdog` param wins over both. In orchestrator posture the
2159
+ // watchdog auto-arms unless hub or per-agent is explicitly off; dispatch
2160
+ // `watchdog: false` cannot disarm it.
2130
2161
  let watchdogSetting: string = DEFAULT_WATCHDOG_SETTING;
2131
2162
  let watchdogJudgeModel: string | null = null;
2132
2163
  const watchdogAgentOverrides = new Map<string, "on" | "off">();
2133
2164
  function currentBudget() {
2134
- return resolveTurnBudget(hubMode, budgetOverrides, taskTier);
2165
+ return resolveTurnBudget(taskTier ?? DEFAULT_TASK_TIER, budgetOverrides);
2135
2166
  }
2136
2167
  function currentTaskBudget() {
2137
2168
  return resolveTaskBudget(currentBudget());
@@ -2149,6 +2180,33 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2149
2180
  for (const startedAt of askUserStarts.values()) openWait += Math.max(0, now - startedAt);
2150
2181
  return taskClockElapsedMs(taskClock, now, openWait);
2151
2182
  }
2183
+ function turnBudgetActiveElapsedMs(now = Date.now()): number {
2184
+ let openWait = 0;
2185
+ for (const startedAt of askUserStarts.values()) openWait += Math.max(0, now - startedAt);
2186
+ return turnBudgetActiveMs(currentTurnStartedAt, now, turnBudgetAskUserWaitMs, openWait);
2187
+ }
2188
+ function armBudgetContinuation(kind: BudgetContinuationKind, reason: string): void {
2189
+ pendingBudgetContinuation = { kind, reason };
2190
+ }
2191
+ /** Renew only the per-turn envelope; the task identity and outer counters stay intact. */
2192
+ function renewTurnBudgetWindow(now = Date.now()): void {
2193
+ turnDispatchCount = 0;
2194
+ turnResearchCount = 0;
2195
+ currentTurnStartedAt = now;
2196
+ turnBudgetAskUserWaitMs = 0;
2197
+ turnDispatchFingerprints.clear();
2198
+ turnContinuationCount++;
2199
+ updateModeStatus();
2200
+ }
2201
+ /** Add one task tranche while preserving tier, assertions, packs, blockers, and label. */
2202
+ function continueTaskBudgetWindow(now = Date.now()): void {
2203
+ taskDispatchCount = 0;
2204
+ taskResearchCount = 0;
2205
+ taskClock = resetTaskClock(taskClock, now);
2206
+ taskReviewRounds = 0;
2207
+ taskContinuationCount++;
2208
+ renewTurnBudgetWindow(now);
2209
+ }
2152
2210
  /** Fold the turn that is ending into the task's active-time accumulator. */
2153
2211
  function closeTurnActiveTime(now = Date.now()) {
2154
2212
  taskClock = closeTaskClock(taskClock, now);
@@ -2159,13 +2217,21 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2159
2217
  taskResearchCount = 0;
2160
2218
  taskClock = resetTaskClock(taskClock, now);
2161
2219
  taskReviewRounds = 0;
2220
+ taskContinuationCount = 0;
2221
+ pendingBudgetContinuation = null;
2222
+ budgetContinuationAsks.clear();
2162
2223
  taskLabel = label;
2163
2224
  taskTier = null;
2164
2225
  taskTierAssumed = false;
2226
+ taskCapabilityPacks = [];
2227
+ taskProvisionalPacks = [];
2228
+ capabilityConfirmation = {};
2165
2229
  externalBlockers = [];
2166
2230
  externalBlockerAcknowledged = false;
2167
2231
  externalBlockerRefusedOnce = false;
2168
2232
  turnDispatchFingerprints.clear();
2233
+ resolveIncomingCapabilities("", true);
2234
+ applyPostureTools();
2169
2235
  updateModeStatus();
2170
2236
  }
2171
2237
  function hubAuditIdentity(ctx?: ExtensionContext) {
@@ -2182,23 +2248,6 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2182
2248
  const where = hubAuditIdentity(ctx);
2183
2249
  return `\nRepository: ${where.cwd ?? "unknown"}${where.herdr_pane_id ? ` · pane ${where.herdr_pane_id}` : ""}`;
2184
2250
  }
2185
- function appendHubModeEntry(input: {
2186
- previousMode: string;
2187
- mode: string;
2188
- source: "slash-command" | "project-override" | "default";
2189
- overrideFile?: string | null;
2190
- ctx?: ExtensionContext;
2191
- }) {
2192
- try {
2193
- pi.appendEntry("agent-hub-mode", buildHubModeAudit({
2194
- ...input,
2195
- taskTier,
2196
- turnDispatches: turnDispatchCount,
2197
- turnResearch: turnResearchCount,
2198
- identity: hubAuditIdentity(input.ctx),
2199
- }));
2200
- } catch { /* diagnostics are best-effort; state changes still succeed */ }
2201
- }
2202
2251
  function taskResetSnapshot(now = Date.now()) {
2203
2252
  return {
2204
2253
  tier: taskTier,
@@ -2208,7 +2257,16 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2208
2257
  activeMs: taskActiveElapsedMs(now),
2209
2258
  };
2210
2259
  }
2211
- function appendTaskResetEntry(source: "slash-command" | "tool:set_task_tier", label: string | null, prior: ReturnType<typeof taskResetSnapshot>, ctx?: ExtensionContext) {
2260
+ function budgetContinuationSnapshot(kind: BudgetContinuationKind, now = Date.now()) {
2261
+ return kind === "task" ? taskResetSnapshot(now) : {
2262
+ tier: taskTier,
2263
+ dispatches: turnDispatchCount,
2264
+ research: turnResearchCount,
2265
+ reviewRounds: 0,
2266
+ activeMs: turnBudgetActiveElapsedMs(now),
2267
+ };
2268
+ }
2269
+ function appendTaskResetEntry(source: "tool:set_task_tier", label: string | null, prior: ReturnType<typeof taskResetSnapshot>, ctx?: ExtensionContext) {
2212
2270
  try {
2213
2271
  pi.appendEntry("agent-hub-task-reset", buildTaskResetAudit({
2214
2272
  source,
@@ -2218,17 +2276,27 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2218
2276
  }));
2219
2277
  } catch { /* diagnostics are best-effort; state changes still succeed */ }
2220
2278
  }
2279
+ function appendBudgetContinuationEntry(kind: BudgetContinuationKind, reason: string, prior: ReturnType<typeof taskResetSnapshot>, ctx?: ExtensionContext) {
2280
+ try {
2281
+ pi.appendEntry("agent-hub-budget-continuation", buildBudgetContinuationAudit({
2282
+ kind,
2283
+ continuation: kind === "task" ? taskContinuationCount : turnContinuationCount,
2284
+ reason,
2285
+ prior,
2286
+ identity: hubAuditIdentity(ctx),
2287
+ }));
2288
+ } catch { /* diagnostics are best-effort; state changes still succeed */ }
2289
+ }
2221
2290
  function updateModeStatus() {
2222
2291
  try {
2223
2292
  widgetCtx?.ui?.setStatus(
2224
- "hub-mode",
2293
+ "hub-tier",
2225
2294
  budgetStatusLine(
2226
- hubMode,
2227
2295
  { dispatches: turnDispatchCount, research: turnResearchCount },
2228
2296
  currentBudget(),
2229
2297
  // A trailing "?" marks a tier the hub assumed rather than one the
2230
2298
  // dispatcher declared — the human can see that triage was skipped.
2231
- taskTier && taskTierAssumed ? `${taskTier}?` : taskTier,
2299
+ taskTier && taskTierAssumed ? `${taskTier}?` : (taskTier ?? DEFAULT_TASK_TIER),
2232
2300
  { counters: taskCounters(), budget: currentTaskBudget() },
2233
2301
  ),
2234
2302
  );
@@ -2239,6 +2307,14 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2239
2307
  * order: an unacknowledged external blocker, then the tier's persona gate.
2240
2308
  * Returns the refusal text, or null when the call may proceed.
2241
2309
  */
2310
+ /** Latch the conservative tier before any fleet action can pass a persona gate. */
2311
+ function ensureTaskTier(): void {
2312
+ if (taskTier !== null) return;
2313
+ taskTier = DEFAULT_TASK_TIER;
2314
+ taskTierAssumed = true;
2315
+ turnReport.tier = taskTier;
2316
+ updateModeStatus();
2317
+ }
2242
2318
  function preflightGate(persona: string): { reason: string; message: string } | null {
2243
2319
  const blocked = checkExternalBlockerGate({
2244
2320
  blockers: externalBlockers,
@@ -2351,10 +2427,20 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2351
2427
  return out;
2352
2428
  }
2353
2429
 
2354
- // The model a persona would dispatch on right now: session override →
2355
- // frontmatter default → undefined (dispatcher's model).
2430
+ function substitutedModel(model: string | undefined): string | undefined {
2431
+ return model ? (modelSubstitutions.get(model) ?? model) : undefined;
2432
+ }
2433
+
2434
+ // The model a persona would dispatch on right now: explicit per-persona
2435
+ // override → frontmatter default, then the session-wide source substitution.
2436
+ // Resolving here (rather than eagerly rewriting every loaded def) makes the
2437
+ // mapping apply to agents activated or spawned later in the same session.
2356
2438
  function resolvedModel(def: AgentDef): string | undefined {
2357
- return modelOverrides.get(def.name.toLowerCase()) ?? def.model;
2439
+ return substitutedModel(modelOverrides.get(def.name.toLowerCase()) ?? def.model);
2440
+ }
2441
+
2442
+ function resolvedSubagentModel(persona: string, role: string, declared: string): string {
2443
+ return substitutedModel(subagentModelOverrides.get(`${persona.toLowerCase()}.${role.toLowerCase()}`) ?? declared) ?? declared;
2358
2444
  }
2359
2445
 
2360
2446
  // The raw thinking value a persona would dispatch with right now: session
@@ -2733,6 +2819,11 @@ APIs, commands, structure), say so in your final response so the docs can be upd
2733
2819
  recomputeGrid();
2734
2820
  }
2735
2821
 
2822
+ function persistActiveRoster(): void {
2823
+ if (!activeTeamName || agentStates.size === 0) return;
2824
+ pi.appendEntry(NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState(activeTeamName));
2825
+ }
2826
+
2736
2827
  // ── Dynamic roster (add/drop/save; /af-agents-add, /af-agents-drop, team_adjust) ──
2737
2828
  // The system prompt is rebuilt every turn from agentStates, so a roster
2738
2829
  // change takes effect on the dispatcher's next turn with no restart.
@@ -3478,6 +3569,7 @@ ${externalBlockedProtocol()}
3478
3569
  scopeGlobs: string[] = [],
3479
3570
  watchdogParam?: boolean,
3480
3571
  requestedBackend: "auto" | "native" | "coms" = "auto",
3572
+ preserveManifest = false,
3481
3573
  ): Promise<{
3482
3574
  output: string;
3483
3575
  exitCode: number;
@@ -3626,7 +3718,8 @@ ${externalBlockedProtocol()}
3626
3718
  ?? (ctx.model
3627
3719
  ? `${ctx.model.provider}/${ctx.model.id}`
3628
3720
  : "openrouter/google/gemini-3-flash-preview");
3629
- const originalModelFallback = fallbackModelFor(state.def, model);
3721
+ const fallbackCandidate = substitutedModel(fallbackModelFor(state.def, model));
3722
+ const originalModelFallback = fallbackCandidate === model ? undefined : fallbackCandidate;
3630
3723
 
3631
3724
  // THIS specialist's window, not the dispatcher's. Measuring a 49k local
3632
3725
  // model against a hosted model's window is what produced readings like
@@ -3686,44 +3779,6 @@ ${externalBlockedProtocol()}
3686
3779
  }
3687
3780
  }
3688
3781
 
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
3782
  // Mid-turn delegation: a persona that declares `subagents:` gets the
3728
3783
  // delegate extension injected (`-e delegate.ts`), the `delegate` tool
3729
3784
  // added to its allowlist (pi filters extension tools too), and its
@@ -3735,18 +3790,19 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3735
3790
  // delegate config, so nested children inherit the switch for free.
3736
3791
  const subagentRoles = state.def.subagents && Object.keys(state.def.subagents).length > 0
3737
3792
  ? Object.fromEntries(Object.entries(state.def.subagents).map(([role, r]) => {
3738
- const override = subagentModelOverrides.get(`${personaKey}.${role.toLowerCase()}`);
3739
- return [role, override ? applyModelOverride(r, override) : r];
3793
+ const effective = resolvedSubagentModel(personaKey, role, r.model);
3794
+ const configured = effective !== r.model ? applyModelOverride(r, effective) : r;
3795
+ const fallback = substitutedModel(configured.fallbackModel);
3796
+ return [role, fallback === configured.model ? { ...configured, fallbackModel: undefined } : { ...configured, fallbackModel: fallback }];
3740
3797
  }))
3741
3798
  : null;
3742
- // Fast mode is a single-specialist path: no nested delegation trees.
3799
+ // Nested delegation follows the task-tier envelope (off at trivial/small).
3743
3800
  const delegationActive = turnBudget.delegation && !!subagentRoles && !!delegateExtPath;
3744
3801
  const safety = requireSafetyHarness(safetyHarnessPath);
3745
3802
  if (!safety.ok) return finishRun(safety.error, 1);
3746
3803
  const extensions = [...safety.extensions];
3747
3804
  let effectiveTools = state.def.tools;
3748
3805
  let delegateEnv: Record<string, string> | undefined;
3749
- let delegationProtocol = "";
3750
3806
  if (delegationActive) {
3751
3807
  const delegationDir = safePathWithin(sessionDir, "delegations", agentKey);
3752
3808
  try { rmSync(delegationDir, { recursive: true, force: true }); } catch {}
@@ -3771,25 +3827,25 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
3771
3827
  cwd: ctx.cwd || process.cwd(),
3772
3828
  }),
3773
3829
  };
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
3830
  startDelegationWatch(state, delegationDir);
3784
3831
  }
3785
3832
 
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;
3833
+ const manifest = preserveManifest && state.specialistManifest
3834
+ ? state.specialistManifest
3835
+ : buildSpecialistContextManifest({
3836
+ personaName: state.def.name,
3837
+ personaPath: state.def.file,
3838
+ personaPrompt: state.def.systemPrompt,
3839
+ task,
3840
+ rulesPaths: specialistProjectPolicyPaths(ctx.cwd || process.cwd()),
3841
+ docsPaths: projectDocsPaths,
3842
+ hasAssertions: extractAssertionIds(task).length > 0,
3843
+ hasScope: scopeGlobs.length > 0,
3844
+ hasArtifacts: inputArtifacts.length > 0,
3845
+ delegateRoles: delegationActive ? Object.keys(subagentRoles!) : [],
3846
+ });
3847
+ state.specialistManifest = manifest;
3848
+ const replacementSystemPrompt = nativeSpecialistSystemPrompt({ manifest, userLanguage, agentKey, runNumber });
3793
3849
 
3794
3850
  // Per-agent thinking: the persona's `thinking:` frontmatter (or a
3795
3851
  // /af-agent-model-thinking session override) sets the pi --thinking reasoning
@@ -3800,7 +3856,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3800
3856
 
3801
3857
  // ── Drift watchdog: layer-1 rules on the live stream, judge on escalation ──
3802
3858
  // Precedence: dispatch param > per-agent /af-watchdog override > hub setting.
3803
- const watchdogArmed = resolveWatchdogActive(watchdogParam, watchdogAgentOverrides.get(key), watchdogSetting);
3859
+ const watchdogArmed = resolveWatchdogActive(watchdogParam, watchdogAgentOverrides.get(key), watchdogSetting, posture);
3804
3860
  // The hub ORDERS every specialist to write its deliverable under the session
3805
3861
  // artifacts tree, which no dispatcher `scope:` ever lists — so those paths are
3806
3862
  // implicitly in scope. Both path forms: the specialist may use either.
@@ -3850,7 +3906,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3850
3906
  if (state.sessionFile && !sessionRecycled) {
3851
3907
  const overflow = shouldRecycleBeforeSpawn({
3852
3908
  priorTokens: state.contextTokens,
3853
- promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(appendedSystemPrompt),
3909
+ promptTokens: estimatePromptTokens(runPrompt) + estimatePromptTokens(replacementSystemPrompt),
3854
3910
  window: agentWindow.window,
3855
3911
  });
3856
3912
  if (overflow) {
@@ -3874,10 +3930,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3874
3930
  model,
3875
3931
  tools: effectiveTools,
3876
3932
  thinking: thinkingLevel,
3877
- appendSystemPrompt: appendedSystemPrompt,
3933
+ systemPrompt: replacementSystemPrompt,
3934
+ noSkills: true,
3935
+ noContextFiles: true,
3878
3936
  sessionFile: agentSessionFile,
3879
3937
  resume: !!state.sessionFile,
3880
3938
  prompt: runPrompt,
3939
+ cwd: ctx.cwd || process.cwd(),
3881
3940
  extensions,
3882
3941
  env: { ...guardrailEnv(agentKey), ...(delegateEnv || {}) },
3883
3942
  detached: true,
@@ -4209,6 +4268,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4209
4268
  elapsed: 0,
4210
4269
  lastWork: "",
4211
4270
  contextPct: 0,
4271
+ contextTokens: 0,
4212
4272
  sessionFile: null,
4213
4273
  turnCount: 1,
4214
4274
  timeline: [],
@@ -4283,18 +4343,25 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4283
4343
  // READ-ONLY by construction: RESEARCH_TOOLS only, regardless of persona frontmatter.
4284
4344
  let fullText = "";
4285
4345
  const researchWindow = resolveContextWindow(state.model, { lookup: modelWindowLookup(ctx), fallbackWindow: contextWindow });
4346
+ const researchFallbackCandidate = substitutedModel(fallbackModelFor(state.def, state.model));
4347
+ const researchFallback = researchFallbackCandidate === state.model ? undefined : researchFallbackCandidate;
4286
4348
  notifyProviderQueue(state.model, `Research r${state.id}`, ctx);
4287
4349
  const res = await providerSemaphore.run(state.model, () => spawnPiAgentWithModelFallback({
4288
4350
  model: state.model,
4289
4351
  tools: RESEARCH_TOOLS,
4290
4352
  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(),
4353
+ // Replacement policy avoids inherited skills and project context files.
4354
+ // The selected persona remains available by its explicit source path.
4355
+ systemPrompt: nativeResearchSystemPrompt({
4356
+ ...(state.persona ? { personaName: state.def.name, personaPath: state.def.file } : {}),
4357
+ cwd: ctx.cwd || process.cwd(),
4358
+ }),
4359
+ noSkills: true,
4360
+ noContextFiles: true,
4295
4361
  sessionFile: sessionPath,
4296
4362
  resume: !!state.sessionFile,
4297
4363
  prompt: appendInputArtifacts(prompt, inputArtifacts),
4364
+ cwd: ctx.cwd || process.cwd(),
4298
4365
  // A blocked read feeds back so the helper can adapt without aborting.
4299
4366
  extensions: safety.extensions,
4300
4367
  env: guardrailEnv(`research-r${state.id}`),
@@ -4303,7 +4370,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4303
4370
  ...researchWatchdogSpawnOptions(reconSearchTimeoutMs, signal),
4304
4371
  // Whole-run deadline from the active mode's budget (null in strict mode).
4305
4372
  turnDeadlineMs: currentBudget().agentTurnMs,
4306
- }, fallbackModelFor(state.def, state.model), {
4373
+ }, researchFallback, {
4307
4374
  onProcess: (p) => { state.proc = p; },
4308
4375
  onModelFallback: ({ from, to, reason }) => {
4309
4376
  state.lastWork = `model fallback: ${shortModel(from)} → ${shortModel(to)}`;
@@ -4334,7 +4401,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4334
4401
  state.zoomRender?.();
4335
4402
  },
4336
4403
  onUsage: (usage) => {
4337
- if (researchWindow.window > 0) {
4404
+ state.contextTokens = (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
4405
+ if (researchWindow.window > 0) {
4338
4406
  // Same context truth as dispatchAgent: include cache reads/writes,
4339
4407
  // measured against THIS helper's window rather than the dispatcher's.
4340
4408
  state.contextPct = contextPct(usage, researchWindow.window);
@@ -4473,6 +4541,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4473
4541
  }
4474
4542
 
4475
4543
  function handlePrompt(socket: net.Socket, env: PromptEnvelope): void {
4544
+ if (currentCtx && modelWorkBlockedByRosterRecovery(currentCtx)) {
4545
+ nack(socket, env.msg_id, "orchestrator roster recovery required");
4546
+ return;
4547
+ }
4476
4548
  // 1. Hop limit check
4477
4549
  if (typeof env.hops !== "number" || env.hops >= MAX_HOPS) {
4478
4550
  nack(socket, env.msg_id, "hops exceeded");
@@ -4977,35 +5049,31 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4977
5049
  pi.registerTool({
4978
5050
  name: "dispatch_agent",
4979
5051
  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.",
5052
+ description: "Dispatch one focused task to a listed specialist; it returns evidence.",
4981
5053
  parameters: Type.Object({
4982
5054
  agent: Type.String({ description: "Agent name (case-insensitive)" }),
4983
5055
  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`." })),
5056
+ artifacts: Type.Optional(Type.Array(Type.String({ description: "Input artifact path; the specialist reads it." }))),
5057
+ scope: Type.Optional(Type.Array(Type.String({ description: "Advisory writable-file globs; violations are reported, never reverted." }))),
5058
+ watchdog: Type.Optional(Type.Boolean({ description: "Override this dispatch's drift watchdog." })),
5059
+ review_reason: Type.Optional(Type.String({ description: "Why a docs-only review is needed." })),
4988
5060
  backend: Type.Optional(Type.Union([
4989
5061
  Type.Literal("auto"),
4990
5062
  Type.Literal("native"),
4991
5063
  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." })),
5064
+ ], { description: "auto policy; native local; coms requires its live peer (no fallback)." })),
4993
5065
  }),
4994
5066
 
4995
5067
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
5068
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5069
+ if (confirmationRefusal) return confirmationRefusal;
4996
5070
  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
5071
  // Display names / underscores resolve to the persona slug key space, so
4998
5072
  // `agent: "Test Engineer"` never burns a dispatch on a lookup error.
4999
5073
  const agent = normalizeAgentInput((params as { agent: string }).agent);
5000
- // Unclassified task: assume the default tier (outside strict, whose full
5001
- // contract runs uncapped by tiers). The prompt asks for set_task_tier
5002
- // FIRST; this is the fail-safe, not the intended path.
5003
- if (taskTier === null && hubMode !== "strict") {
5004
- taskTier = DEFAULT_TASK_TIER;
5005
- taskTierAssumed = true;
5006
- turnReport.tier = taskTier;
5007
- updateModeStatus();
5008
- }
5074
+ // Unclassified task: assume the default tier. The prompt asks for
5075
+ // set_task_tier FIRST; this is the fail-safe, not the intended path.
5076
+ ensureTaskTier();
5009
5077
  // Pre-flight refusals, in severity order, BEFORE anything is charged: an
5010
5078
  // unacknowledged external blocker, the tier's persona gate, the review-round
5011
5079
  // cap, then the docs-only lane. None of these reached a specialist, so none
@@ -5034,8 +5102,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5034
5102
  if (taskRefusal) {
5035
5103
  turnReport.refusals++;
5036
5104
  sessionTotals.refusals++;
5105
+ armBudgetContinuation("task", taskRefusal.reason);
5037
5106
  return {
5038
- content: [{ type: "text", text: taskRefusal.message }],
5107
+ content: [{ type: "text", text: budgetContinuationInstruction(taskRefusal.message, "task", userLanguage) }],
5039
5108
  details: { agent, task, status: "task_budget_refused", reason: taskRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
5040
5109
  };
5041
5110
  }
@@ -5045,14 +5114,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5045
5114
  "dispatch",
5046
5115
  { dispatches: turnDispatchCount, research: turnResearchCount },
5047
5116
  currentBudget(),
5048
- Date.now() - (currentTurnStartedAt || Date.now()),
5049
- hubMode,
5117
+ turnBudgetActiveElapsedMs(),
5118
+ taskTier,
5050
5119
  );
5051
5120
  if (budgetRefusal) {
5052
5121
  turnReport.refusals++;
5053
5122
  sessionTotals.refusals++;
5123
+ armBudgetContinuation("turn", budgetRefusal.reason);
5054
5124
  return {
5055
- content: [{ type: "text", text: budgetRefusal.message }],
5125
+ content: [{ type: "text", text: budgetContinuationInstruction(budgetRefusal.message, "turn", userLanguage) }],
5056
5126
  details: { agent, task, status: "budget_refused", reason: budgetRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
5057
5127
  };
5058
5128
  }
@@ -5185,7 +5255,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5185
5255
  const resumePrompt = "Research findings for your NEEDS_RESEARCH questions are ready. " +
5186
5256
  "Read each file with your read tool, then continue from where you paused:\n" +
5187
5257
  answered.map((a, i) => `${i + 1}. ${a.question}\n → ${a.file}`).join("\n");
5188
- result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog, backend);
5258
+ result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog, backend, true);
5189
5259
  dispatchBilled += result.billed ?? 0;
5190
5260
  dispatchOut += result.out ?? 0;
5191
5261
  }
@@ -5281,7 +5351,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5281
5351
  ? `\n\n⚠ ${agent} paused for research, but the TASK research envelope is spent ` +
5282
5352
  `(${taskResearchCount}/${currentTaskBudget().maxResearch}) — no helper was spawned and the specialist ` +
5283
5353
  `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.`
5354
+ `or call set_task_tier with new_task: true if this is genuinely different work.`
5285
5355
  : "";
5286
5356
 
5287
5357
  const returnPathNotice = returnPath ? `\n\nFull specialist output: ${returnPath}` : "";
@@ -5450,17 +5520,22 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5450
5520
  pi.registerTool({
5451
5521
  name: "spawn_research",
5452
5522
  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.",
5523
+ description: "Run a read-only (read/grep/find/ls) helper and return findings.",
5454
5524
  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." }))),
5525
+ task: Type.String({ description: "Investigation and expected findings." }),
5526
+ persona: Type.Optional(Type.String({ description: "Research persona; omit for ad-hoc." })),
5527
+ model: Type.Optional(Type.String({ description: "Anonymous-helper model; ignored with persona." })),
5528
+ artifacts: Type.Optional(Type.Array(Type.String({ description: "Input artifact path." }))),
5459
5529
  }),
5460
5530
 
5461
5531
  async execute(_toolCallId, params, _signal, onUpdate, ctx) {
5532
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5533
+ if (confirmationRefusal) return confirmationRefusal;
5462
5534
  const { task, persona, model, artifacts } = params as { task: string; persona?: string; model?: string; artifacts?: string[] };
5463
5535
 
5536
+ // Research is also a fleet action: latch the conservative tier before
5537
+ // its persona gate, so research-first cannot bypass assumed-small.
5538
+ ensureTaskTier();
5464
5539
  // Pre-flight refusals before anything is charged: an unacknowledged
5465
5540
  // external blocker, then the tier's persona gate (deep-researcher is the
5466
5541
  // most expensive helper in the system and is not a trivial-tier tool).
@@ -5484,8 +5559,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5484
5559
  if (taskRefusal) {
5485
5560
  turnReport.refusals++;
5486
5561
  sessionTotals.refusals++;
5562
+ armBudgetContinuation("task", taskRefusal.reason);
5487
5563
  return {
5488
- content: [{ type: "text", text: taskRefusal.message }],
5564
+ content: [{ type: "text", text: budgetContinuationInstruction(taskRefusal.message, "task", userLanguage) }],
5489
5565
  details: { status: "task_budget_refused", reason: taskRefusal.reason },
5490
5566
  };
5491
5567
  }
@@ -5495,14 +5571,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5495
5571
  "research",
5496
5572
  { dispatches: turnDispatchCount, research: turnResearchCount },
5497
5573
  currentBudget(),
5498
- Date.now() - (currentTurnStartedAt || Date.now()),
5499
- hubMode,
5574
+ turnBudgetActiveElapsedMs(),
5575
+ taskTier,
5500
5576
  );
5501
5577
  if (budgetRefusal) {
5502
5578
  turnReport.refusals++;
5503
5579
  sessionTotals.refusals++;
5580
+ armBudgetContinuation("turn", budgetRefusal.reason);
5504
5581
  return {
5505
- content: [{ type: "text", text: budgetRefusal.message }],
5582
+ content: [{ type: "text", text: budgetContinuationInstruction(budgetRefusal.message, "turn", userLanguage) }],
5506
5583
  details: { status: "budget_refused", reason: budgetRefusal.reason },
5507
5584
  };
5508
5585
  }
@@ -5631,15 +5708,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5631
5708
  });
5632
5709
 
5633
5710
  // ── set_task_tier Tool (complexity triage) ──
5634
- // The dispatcher classifies each user turn BEFORE its first dispatch; the
5635
- // declared tier lowers the dispatch/research caps to min(mode, tier) in code.
5636
- // Skipping it makes the first dispatch assume the default tier (run-budget.js).
5711
+ // The dispatcher classifies each TASK before its first dispatch; the declared
5712
+ // tier *is* the budget envelope (run-budget.js). Skipping it makes the first
5713
+ // dispatch assume DEFAULT_TASK_TIER.
5637
5714
 
5638
5715
  pi.registerTool({
5639
5716
  name: "set_task_tier",
5640
5717
  label: "Set Task Tier",
5641
5718
  description:
5642
- "Classify the CURRENT TASK before your first dispatch: trivial (one obvious, low-risk change — 1 dispatch), small (a contained change, no planning pipeline — 2 dispatches), feature (a normal multi-step feature — 6 dispatches), project (a large effort — mode budget applies). The tier persists across user messages and moves by ratchet: LOWERING it is always free, RAISING it requires `reason` naming what the ask turned out to contain. Pass `new_task: true` only when the human has moved on to a genuinely different piece of work — it also resets the task budget.",
5719
+ "Classify the CURRENT TASK before your first dispatch: trivial (one obvious, low-risk change — 1 dispatch), small (a contained change, no planning pipeline — 2 dispatches), feature (a normal multi-step feature — 8 dispatches), project (a large effort — 12 dispatches). Nested delegation is off at trivial/small. The tier persists across user messages and moves by ratchet: LOWERING it is always free, RAISING it requires `reason` naming what the ask turned out to contain. Pass `new_task: true` only when the human has moved on to a genuinely different piece of work — it also resets the task budget.",
5643
5720
  parameters: Type.Object({
5644
5721
  tier: Type.String({ description: "One of: trivial | small | feature | project" }),
5645
5722
  reason: Type.Optional(Type.String({ description: "One line on why this tier fits the ask. REQUIRED when raising the tier above the current one." })),
@@ -5647,6 +5724,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5647
5724
  }),
5648
5725
  async execute(_callId, params, _signal, _onUpdate, _ctx) {
5649
5726
  const { tier, reason, new_task } = params as { tier: string; reason?: string; new_task?: boolean };
5727
+ // An explicit new-task reset is the lifecycle escape hatch and clears
5728
+ // provisional decisions; it must not itself require the old task's consent.
5729
+ if (!new_task) {
5730
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5731
+ if (confirmationRefusal) return confirmationRefusal;
5732
+ }
5733
+
5650
5734
  // A new task classifies from an empty ratchet. Validate the requested tier
5651
5735
  // before mutating/resetting anything so invalid input cannot erase a task.
5652
5736
  const currentTier = new_task ? null : (taskTierAssumed ? null : taskTier);
@@ -5693,26 +5777,30 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5693
5777
  });
5694
5778
 
5695
5779
  // ── team_adjust Tool (dispatcher-driven roster changes, gated) ──
5696
- // The dispatcher may restructure its own team mid-session — but never in fast
5697
- // mode, never past the roster cap, and the human is notified of every change.
5780
+ // The dispatcher may restructure its own team mid-session — but never when the
5781
+ // current tier has nested delegation off, never past the roster cap, and the
5782
+ // human is notified of every change.
5698
5783
  const TEAM_ADJUST_ROSTER_CAP = 8;
5699
5784
 
5700
5785
  pi.registerTool({
5701
5786
  name: "team_adjust",
5702
5787
  label: "Team Adjust",
5703
5788
  description:
5704
- "Add or drop a specialist persona in the ACTIVE team (the roster you can dispatch to). Use sparingly, when the current roster genuinely cannot serve the task (e.g. add security-auditor for a security-sensitive change, drop an unused specialist). Not available in fast mode. The human sees every change and can revert with /af-agents-add /af-agents-drop.",
5789
+ "Add or drop a specialist persona in the ACTIVE team (the roster you can dispatch to). Use sparingly, when the current roster genuinely cannot serve the task (e.g. add security-auditor for a security-sensitive change, drop an unused specialist). Not available at trivial/small tiers. The human sees every change and can revert with /af-agents-add /af-agents-drop.",
5705
5790
  parameters: Type.Object({
5706
5791
  action: Type.String({ description: "add | drop" }),
5707
5792
  agent: Type.String({ description: "Persona name (case-insensitive), e.g. security-auditor" }),
5708
5793
  reason: Type.String({ description: "One line on why the roster must change for this task." }),
5709
5794
  }),
5710
5795
  async execute(_callId, params, _signal, _onUpdate, ctx) {
5796
+ const confirmationRefusal = provisionalCapabilityRefusal("fleet");
5797
+ if (confirmationRefusal) return confirmationRefusal;
5711
5798
  const { action, agent, reason } = params as { action: string; agent: string; reason: string };
5712
5799
  const act = String(action || "").trim().toLowerCase();
5713
- if (hubMode === "fast") {
5800
+ if (!currentBudget().delegation) {
5801
+ const tier = taskTier ?? DEFAULT_TASK_TIER;
5714
5802
  return {
5715
- content: [{ type: "text" as const, text: "team_adjust is disabled in fast mode — a single-specialist path never needs roster changes. Ask the user to /af-hub-mode standard if the task outgrew fast mode." }],
5803
+ content: [{ type: "text" as const, text: `team_adjust is disabled at tier "${tier}" — a single-specialist path never needs roster changes. Raise the task tier with set_task_tier if the work outgrew "${tier}".` }],
5716
5804
  details: { status: "refused" },
5717
5805
  };
5718
5806
  }
@@ -5753,17 +5841,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5753
5841
  pi.registerTool({
5754
5842
  name: "set_assertions",
5755
5843
  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.`,
5844
+ description: `Replace this task's checkable assertion ledger (max ${MAX_OPEN_ASSERTIONS}); dispatch only evidence-gated work.`,
5758
5845
  parameters: Type.Object({
5759
5846
  assertions: Type.Array(
5760
5847
  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." }),
5848
+ id: Type.String({ description: "Stable id (A1, A2)." }),
5849
+ tag: Type.String({ description: "test | runtime-ui | code-grep | manual." }),
5850
+ text: Type.String({ description: "One pass condition." }),
5851
+ source: Type.String({ description: "Requirement origin." }),
5765
5852
  }),
5766
- { description: `The full assertion list — replaces any existing ledger. Soft cap ${MAX_OPEN_ASSERTIONS} per batch.` },
5853
+ { description: `Replacement list; soft cap ${MAX_OPEN_ASSERTIONS}.` },
5767
5854
  ),
5768
5855
  }),
5769
5856
  async execute(_callId, params, _signal, _onUpdate, ctx) {
@@ -5799,8 +5886,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5799
5886
  pi.registerTool({
5800
5887
  name: "update_assertion",
5801
5888
  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.",
5889
+ description: "Record a verification result. proven requires named evidence; unproven/failed are not done.",
5804
5890
  parameters: Type.Object({
5805
5891
  id: Type.String({ description: "Assertion id to update, e.g. A2." }),
5806
5892
  status: Type.String({ description: "One of: proven | unproven | failed." }),
@@ -5864,8 +5950,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5864
5950
  pi.registerTool({
5865
5951
  name: "get_assertions",
5866
5952
  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.",
5953
+ description: "Read the full assertion ledger, especially after compaction. Read-only.",
5869
5954
  parameters: Type.Object({}),
5870
5955
  async execute(_callId, _params, _signal, _onUpdate, _ctx) {
5871
5956
  if (assertions.length === 0) {
@@ -5893,11 +5978,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5893
5978
  pi.registerTool({
5894
5979
  name: "coms_list",
5895
5980
  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.",
5981
+ description: "List peers in the human-scoped pool; this tool cannot widen discovery.",
5901
5982
  parameters: Type.Object({
5902
5983
  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
5984
  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 +6090,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6009
6090
  pi.registerTool({
6010
6091
  name: "coms_send",
6011
6092
  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.",
6093
+ description: "Send to an in-pool peer; use its msg_id with coms_get or coms_await.",
6016
6094
  parameters: Type.Object({
6017
6095
  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
6096
  prompt: Type.String({ description: "The prompt to send." }),
@@ -6022,6 +6100,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6022
6100
  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
6101
  }),
6024
6102
  async execute(_callId, params) {
6103
+ const confirmationRefusal = provisionalCapabilityRefusal("peer");
6104
+ if (confirmationRefusal) return confirmationRefusal;
6025
6105
  if (!identity) {
6026
6106
  throw new Error("coms not initialised");
6027
6107
  }
@@ -6185,8 +6265,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6185
6265
  pi.registerTool({
6186
6266
  name: "coms_await",
6187
6267
  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).",
6268
+ description: "Wait for a pending coms_send reply; timeout leaves it pending.",
6190
6269
  parameters: Type.Object({
6191
6270
  msg_id: Type.String({ description: "msg_id returned by coms_send." }),
6192
6271
  timeout_ms: Type.Optional(Type.Number({ description: "Override the default timeout (ms)." })),
@@ -6327,20 +6406,21 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6327
6406
  pi.registerTool({
6328
6407
  name: "herdr_spawn_peer",
6329
6408
  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.",
6409
+ description: "Spawn a reusable sibling coms peer from its declared or compatible override settings; wait for peer_ready.",
6332
6410
  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)." })),
6411
+ name: Type.String({ description: "Peer and pane name." }),
6412
+ runner: Type.Optional(Type.Union([Type.Literal("pi"), Type.Literal("claude-code")], { description: "Runner override." })),
6413
+ persona: Type.Optional(Type.String({ description: "Pi persona override." })),
6414
+ no_persona: Type.Optional(Type.Boolean({ description: "Use persona-less Fleet Core." })),
6415
+ model: Type.Optional(Type.String({ description: "Model override." })),
6416
+ extensions: Type.Optional(Type.String({ description: "Pi extensions." })),
6417
+ browser: Type.Optional(Type.Boolean({ description: "Enable browser." })),
6418
+ all_extensions: Type.Optional(Type.Boolean({ description: "All extensions (Fleet Core only)." })),
6419
+ direction: Type.Optional(Type.Union([Type.Literal("right"), Type.Literal("down")], { description: "Split direction." })),
6342
6420
  }),
6343
6421
  async execute(_callId, params) {
6422
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6423
+ if (confirmationRefusal) return confirmationRefusal;
6344
6424
  if (!herdrFleetReady) {
6345
6425
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6346
6426
  }
@@ -6424,14 +6504,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6424
6504
  pi.registerTool({
6425
6505
  name: "herdr_spawn_pane",
6426
6506
  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.",
6507
+ description: "Spawn a raw auxiliary command in a sibling pane, not a coms peer.",
6429
6508
  parameters: Type.Object({
6430
6509
  name: Type.String({ description: "Human-visible pane label." }),
6431
6510
  command: Type.String({ description: "Raw shell command executed with bash -lc." }),
6432
6511
  direction: Type.Optional(Type.Union([Type.Literal("right"), Type.Literal("down")], { description: "Split direction (default right)." })),
6433
6512
  }),
6434
6513
  async execute(_callId, params) {
6514
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6515
+ if (confirmationRefusal) return confirmationRefusal;
6435
6516
  if (!herdrFleetReady) {
6436
6517
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6437
6518
  }
@@ -6475,8 +6556,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6475
6556
  pi.registerTool({
6476
6557
  name: "herdr_read_pane",
6477
6558
  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.",
6559
+ description: "Read up to 200 recent pane lines; use coms for bridged peers.",
6480
6560
  parameters: Type.Object({
6481
6561
  pane_id: Type.String({ description: "Pane id, e.g. w3:p2 (see herdr_spawn_peer result or the sidebar)." }),
6482
6562
  lines: Type.Optional(Type.Number({ description: "Line cap, default 60, max 200." })),
@@ -6507,13 +6587,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6507
6587
  pi.registerTool({
6508
6588
  name: "herdr_close_pane",
6509
6589
  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.",
6590
+ description: "Close a Hub-spawned pane. Destructive: always asks the human.",
6512
6591
  parameters: Type.Object({
6513
6592
  pane_id: Type.String({ description: "Pane id to close." }),
6514
6593
  reason: Type.String({ description: "One line shown to the human: why this pane can die." }),
6515
6594
  }),
6516
6595
  async execute(_callId, params) {
6596
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6597
+ if (confirmationRefusal) return confirmationRefusal;
6517
6598
  if (!herdrFleetReady) {
6518
6599
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6519
6600
  }
@@ -6550,13 +6631,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6550
6631
  pi.registerTool({
6551
6632
  name: "herdr_notify",
6552
6633
  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.",
6634
+ description: "Notify an away human; never replaces ask_user.",
6555
6635
  parameters: Type.Object({
6556
6636
  title: Type.String({ description: "Notification title." }),
6557
6637
  body: Type.Optional(Type.String({ description: "Notification body." })),
6558
6638
  }),
6559
6639
  async execute(_callId, params) {
6640
+ const confirmationRefusal = provisionalCapabilityRefusal("workspace");
6641
+ if (confirmationRefusal) return confirmationRefusal;
6560
6642
  if (!herdrFleetReady) {
6561
6643
  return { content: [{ type: "text" as const, text: "herdr is not available in this session." }], details: { error: "no herdr" } };
6562
6644
  }
@@ -6594,7 +6676,69 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6594
6676
 
6595
6677
  let askUserAvailable = false;
6596
6678
  let posture: Posture = "operator";
6679
+ let rosterRecoveryRequired = false;
6680
+ let rosterRecoveryDiagnostic = "";
6597
6681
  let baselineTools: string[] = [];
6682
+ let taskCapabilityPacks: CapabilityPack[] = [];
6683
+ let taskProvisionalPacks: CapabilityPack[] = [];
6684
+ let capabilityConfirmation: CapabilityConfirmationState = {};
6685
+ let contextPressureState: ContextPressureState = createContextPressureState();
6686
+ let capabilityResolution: CapabilityResolution = resolveCapabilityPacks({
6687
+ posture, userText: "", taskPacks: [], comsReady: false, herdrReady: false,
6688
+ pendingOperations: [], contextState: "normal",
6689
+ });
6690
+
6691
+ function pendingCapabilityOperations(): PendingOperation[] {
6692
+ const pending: PendingOperation[] = [];
6693
+ 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" });
6694
+ if (pendingReplies.size > 0 || pendingHandoff) pending.push({ pack: "peer", kind: "message" });
6695
+ if (hubSpawnedPeers.size > 0) pending.push({ pack: "workspace", kind: "pane" });
6696
+ return pending;
6697
+ }
6698
+
6699
+ function capabilityContextState(): ContextState {
6700
+ if (contextPressureState.phase === "warning") return "approaching-compaction";
6701
+ if (contextPressureState.phase !== "normal") return "imminent-compaction";
6702
+ if (contextPressureState.pressure === "imminent") return "imminent-compaction";
6703
+ if (contextPressureState.pressure === "approaching") return "approaching-compaction";
6704
+ // Before the first turn_end sample, preserve startup/input protection from
6705
+ // the live Pi measurement without mutating the single-flight state machine.
6706
+ const percent = currentCtx?.getContextUsage?.()?.percent;
6707
+ if (typeof percent === "number" && percent >= 90) return "imminent-compaction";
6708
+ if (typeof percent === "number" && percent >= 80) return "approaching-compaction";
6709
+ return "normal";
6710
+ }
6711
+
6712
+ function resolveIncomingCapabilities(userText: string, newTask = false): void {
6713
+ capabilityResolution = resolveCapabilityPacks({
6714
+ posture,
6715
+ userText,
6716
+ taskTier: taskTier === "trivial" || taskTier === "small" || taskTier === "feature" || taskTier === "project" ? taskTier : undefined,
6717
+ taskPacks: taskCapabilityPacks,
6718
+ provisionalPacks: taskProvisionalPacks,
6719
+ comsReady,
6720
+ herdrReady: herdrFleetReady,
6721
+ pendingOperations: pendingCapabilityOperations(),
6722
+ contextState: capabilityContextState(),
6723
+ newTask,
6724
+ });
6725
+ for (const pack of ["fleet", "peer", "workspace"] as const) {
6726
+ if (capabilityConfirmation[pack] === "promoted" || capabilityConfirmation[pack] === "declined") {
6727
+ capabilityResolution.provisional = capabilityResolution.provisional.filter(candidate => candidate !== pack);
6728
+ capabilityResolution.confirmationRequired = capabilityResolution.confirmationRequired.filter(candidate => candidate !== pack);
6729
+ if (capabilityConfirmation[pack] === "promoted" && !capabilityResolution.active.includes(pack)) capabilityResolution.active.push(pack);
6730
+ }
6731
+ }
6732
+ taskCapabilityPacks = capabilityResolution.nextTaskPacks = CAPABILITY_PACKS.filter(pack => pack !== "core" && pack !== "compaction" && capabilityResolution.active.includes(pack));
6733
+ taskProvisionalPacks = capabilityResolution.provisional.filter(pack => capabilityConfirmation[pack as ConfirmableCapabilityPack] !== "declined");
6734
+ try { pi.appendEntry("agent-hub-capability-packs", persistedCapabilityState(capabilityResolution, capabilityConfirmation)); } catch { /* state persistence is best-effort */ }
6735
+ }
6736
+
6737
+ function provisionalCapabilityRefusal(pack: ConfirmableCapabilityPack) {
6738
+ const gate = confirmationGate(capabilityConfirmation, pack, capabilityResolution.provisional.includes(pack));
6739
+ if (gate.allowed) return null;
6740
+ return { content: [{ type: "text" as const, text: gate.message }], details: { status: "provisional_confirmation_required", confirmation: gate.status, pack } };
6741
+ }
6598
6742
 
6599
6743
  function applyPostureTools(): void {
6600
6744
  pi.setActiveTools(resolvePostureTools({
@@ -6603,6 +6747,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6603
6747
  comsReady,
6604
6748
  herdrReady: herdrFleetReady,
6605
6749
  askUserAvailable,
6750
+ capabilityPacks: [...capabilityResolution.active, ...capabilityResolution.provisional],
6606
6751
  }));
6607
6752
  }
6608
6753
 
@@ -6610,6 +6755,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6610
6755
  ctx.ui.setStatus("hub-posture", `Posture: ${posture}`);
6611
6756
  }
6612
6757
 
6758
+ function modelWorkBlockedByRosterRecovery(ctx: ExtensionContext): boolean {
6759
+ if (posture !== "orchestrator" || !rosterRecoveryRequired) return false;
6760
+ 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.`;
6761
+ ctx.ui.notify(message, "error");
6762
+ // Print/JSON modes do not render extension notifications. Never include the
6763
+ // blocked prompt or command arguments in this metadata-only diagnostic.
6764
+ if (!ctx.hasUI) console.error(`[agent-hub] ${message}`);
6765
+ return true;
6766
+ }
6767
+
6613
6768
  function postureStatusText(): string {
6614
6769
  return [
6615
6770
  `Posture: ${posture}`,
@@ -6670,7 +6825,26 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6670
6825
 
6671
6826
  const idx = options.indexOf(choice);
6672
6827
  const name = teamNames[idx];
6673
- activateTeam(name);
6828
+ const selected = resolveSessionRoster({
6829
+ teams,
6830
+ entries: [],
6831
+ explicitRoster: name,
6832
+ availablePersonas: allAgentDefs.map(def => def.name),
6833
+ });
6834
+ if (!selected.roster) {
6835
+ ctx.ui.notify(`${selected.diagnostic} Fix .pi/agents/teams.yaml or select another team.`, "error");
6836
+ return;
6837
+ }
6838
+ activateTeam(selected.roster.name);
6839
+ rosterRecoveryRequired = false;
6840
+ rosterRecoveryDiagnostic = "";
6841
+ persistActiveRoster();
6842
+ resolveIncomingCapabilities("");
6843
+ applyPostureTools();
6844
+ if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
6845
+ await pickDispatcherPersona(ctx);
6846
+ }
6847
+ setTimeout(replayDeferredRecoveryInputs, 0);
6674
6848
  updateWidget();
6675
6849
  ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
6676
6850
  ctx.ui.notify(`Team: ${name} — ${Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ")}`, "info");
@@ -6693,17 +6867,204 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6693
6867
  const peers = fleetPeerInputs(model => `⇄ ${abbreviateModel(model)}`);
6694
6868
  return buildFleetRows({ specialists, research, peers }, unfiltered ? { showFinished: true } : { showFinished: fleetShowFinished, query: fleetFilter });
6695
6869
  }
6870
+ type FleetDetailModelTarget =
6871
+ | { kind: "specialist"; current: string; state: AgentState }
6872
+ | { kind: "research"; current: string; state: ResearchState }
6873
+ | { kind: "delegate"; current: string; delegation: NonNullable<ReturnType<typeof findDelegationChild>>; role: [string, SubagentRole]; overrideKey: string };
6874
+
6875
+ function resolveFleetDetailModelTarget(row: FleetRow, ctx: any): FleetDetailModelTarget | null {
6876
+ if (row.kind === "peer") {
6877
+ ctx.ui.notify("External coms peers control their own model; switch it in that peer's Pi session.", "info");
6878
+ return null;
6879
+ }
6880
+ if (row.kind === "specialist") {
6881
+ const state = agentStates.get(row.key);
6882
+ if (!state) { ctx.ui.notify("This specialist is no longer available.", "warning"); return null; }
6883
+ return { kind: "specialist", current: resolvedModel(state.def) ?? "", state };
6884
+ }
6885
+ if (row.kind === "research") {
6886
+ const state = researchStates.get(parseResearchHandle(row.key)!);
6887
+ if (!state) { ctx.ui.notify("This research helper is no longer available.", "warning"); return null; }
6888
+ return { kind: "research", current: state.model, state };
6889
+ }
6890
+ const delegation = findDelegationChild(row.key);
6891
+ if (!delegation) { ctx.ui.notify("This nested delegate is no longer available.", "warning"); return null; }
6892
+ const role = Object.entries(delegation.owner.def.subagents ?? {})
6893
+ .find(([name]) => name.toLowerCase() === delegation.child.role.toLowerCase());
6894
+ if (!role) {
6895
+ ctx.ui.notify(`The role for ${row.name} is no longer declared by ${displayName(delegation.owner.def.name)}.`, "warning");
6896
+ return null;
6897
+ }
6898
+ const overrideKey = `${delegation.owner.def.name.toLowerCase()}.${role[0].toLowerCase()}`;
6899
+ return { kind: "delegate", current: resolvedSubagentModel(delegation.owner.def.name, role[0], role[1].model), delegation, role, overrideKey };
6900
+ }
6901
+
6902
+ async function loadAvailableModelChoices(ctx: any, current?: string): Promise<FleetModelChoice[] | null> {
6903
+ try { await ctx.modelRegistry?.refresh?.(); } catch { /* retain the registry's last-known available list */ }
6904
+ const choices = fleetModelChoices(ctx.modelRegistry?.getAvailable?.() ?? [], current);
6905
+ if (choices.length === 0) {
6906
+ const diagnostic = ctx.modelRegistry?.getError?.();
6907
+ ctx.ui.notify(`Pi reports no available models${diagnostic ? `: ${diagnostic}` : "."}`, "warning");
6908
+ return null;
6909
+ }
6910
+ return choices;
6911
+ }
6912
+
6913
+ /** Load every model Pi currently reports as available for the inline picker. */
6914
+ async function loadFleetDetailModelChoices(row: FleetRow, ctx: any): Promise<{ choices: FleetModelChoice[]; current: string } | null> {
6915
+ const target = resolveFleetDetailModelTarget(row, ctx);
6916
+ if (!target) return null;
6917
+ const choices = await loadAvailableModelChoices(ctx, target.current);
6918
+ return choices ? { choices, current: target.current } : null;
6919
+ }
6920
+
6921
+ function substitutionSourceChoices(): FleetModelChoice[] {
6922
+ return allKnownModels().map(spec => {
6923
+ const target = modelSubstitutions.get(spec);
6924
+ return { spec, label: target ? `${spec} → ${target} (active this session)` : spec };
6925
+ });
6926
+ }
6927
+
6928
+ async function applySessionModelSubstitution(source: string, target: string, ctx: any): Promise<boolean> {
6929
+ const known = allKnownModels();
6930
+ if (!known.includes(source)) {
6931
+ ctx.ui.notify(`Unknown configured source model "${source}". Choose one of: ${known.join(", ") || "none"}.`, "error");
6932
+ return false;
6933
+ }
6934
+ const available = await loadAvailableModelChoices(ctx, modelSubstitutions.get(source));
6935
+ if (!available) return false;
6936
+ if (!available.some(choice => choice.spec === target)) {
6937
+ ctx.ui.notify(`Target model "${target}" is not currently available in Pi.`, "error");
6938
+ return false;
6939
+ }
6940
+ if (source === target) {
6941
+ ctx.ui.notify(`Source and target are the same (${source}); the session substitution was not changed.`, "info");
6942
+ return false;
6943
+ }
6944
+ const previous = modelSubstitutions.get(source);
6945
+ if (previous === target) {
6946
+ ctx.ui.notify(`Substitution ${source} → ${target} is already active for this session.`, "info");
6947
+ return false;
6948
+ }
6949
+ modelSubstitutions.set(source, target);
6950
+ const personas = allAgentDefs.filter(def => (modelOverrides.get(def.name.toLowerCase()) ?? def.model) === source);
6951
+ const roles = allAgentDefs.flatMap(def => Object.entries(def.subagents ?? {})
6952
+ .filter(([role, config]) => (subagentModelOverrides.get(`${def.name.toLowerCase()}.${role.toLowerCase()}`) ?? config.model) === source)
6953
+ .map(([role]) => `${def.name}.${role}`));
6954
+ updateWidget();
6955
+ ctx.ui.notify(
6956
+ `${previous ? "Updated" : "Saved"} session substitution ${source} → ${target}. ` +
6957
+ `${personas.length} persona${personas.length === 1 ? "" : "s"} and ${roles.length} sub-role${roles.length === 1 ? "" : "s"} currently resolve through it; ` +
6958
+ `future agents spawned from the same configured source inherit it automatically. Current runs are not interrupted.`,
6959
+ "success",
6960
+ );
6961
+ return true;
6962
+ }
6963
+
6964
+ /** Apply an inline-picker choice to the next run; never interrupt a live child. */
6965
+ function applyFleetDetailModel(row: FleetRow, picked: string, ctx: any): boolean {
6966
+ const target = resolveFleetDetailModelTarget(row, ctx);
6967
+ if (!target) return false;
6968
+ const effectivePicked = substitutedModel(picked) ?? picked;
6969
+ if (effectivePicked === target.current) {
6970
+ ctx.ui.notify(`${row.name} is already on ${effectivePicked}`, "info");
6971
+ return false;
6972
+ }
6973
+ let applyHint = "applies on the next run";
6974
+ if (target.kind === "specialist") {
6975
+ const key = target.state.def.name.toLowerCase();
6976
+ if (picked === target.state.def.model) modelOverrides.delete(key);
6977
+ else modelOverrides.set(key, picked);
6978
+ applyHint = "applies on the next dispatch";
6979
+ } else if (target.kind === "research") {
6980
+ target.state.model = picked;
6981
+ applyHint = `applies when r${target.state.id} next continues or restarts`;
6982
+ } else {
6983
+ if (picked === target.role[1].model) subagentModelOverrides.delete(target.overrideKey);
6984
+ else subagentModelOverrides.set(target.overrideKey, picked);
6985
+ applyHint = `applies on the next ${displayName(target.delegation.owner.def.name)} dispatch`;
6986
+ }
6987
+ updateWidget();
6988
+ ctx.ui.notify(`${row.name} → ${effectivePicked} (${applyHint}; current runs are not interrupted)`, "success");
6989
+ if (target.kind === "specialist" && (dispatchPolicy.substitutions[target.state.def.name.toLowerCase()]?.prefer ?? dispatchPolicy.default) === "coms") {
6990
+ ctx.ui.notify("This specialist prefers a coms peer; the choice applies to native fallback runs, while the peer keeps its own model.", "info");
6991
+ }
6992
+ return true;
6993
+ }
6994
+
6995
+ function matchedFleetDetailInput(data: string): string {
6996
+ const key: FleetDetailKey | undefined =
6997
+ matchesKey(data, Key.up) ? "up"
6998
+ : matchesKey(data, Key.down) ? "down"
6999
+ : matchesKey(data, Key.pageUp) ? "pageUp"
7000
+ : matchesKey(data, Key.pageDown) ? "pageDown"
7001
+ : matchesKey(data, Key.home) ? "home"
7002
+ : matchesKey(data, Key.end) ? "end"
7003
+ : matchesKey(data, Key.enter) ? "enter"
7004
+ : matchesKey(data, Key.escape) ? "escape"
7005
+ : matchesKey(data, Key.ctrl("c")) ? "copy"
7006
+ : undefined;
7007
+ return normalizeFleetDetailInput(data, key);
7008
+ }
7009
+
6696
7010
  async function openFleetDetail(row: FleetRow, ctx: any): Promise<void> {
6697
7011
  const target = row.kind === "research" ? researchStates.get(parseResearchHandle(row.key)!) : row.kind === "delegate" ? findDelegationChild(row.key)?.child : agentStates.get(row.key);
6698
7012
  const resources = createPanelResources();
7013
+ let detailRow = row;
7014
+ let modelPicker: { choices: FleetModelChoice[]; index: number; scrollOffset: number } | null = null;
6699
7015
  let scrollOffset = 0, selectedIndex = 0, expandedIndex: number | null = null, followTail = true, lastRender = 0;
6700
7016
  const timeline = () => liveTimeline(target);
6701
7017
  try { await ctx.ui.custom((tui: any, theme: any, _kb: any, done: () => void) => {
6702
7018
  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() };
7019
+ return {
7020
+ render: (w: number) => {
7021
+ const body = bodyRows(tui.terminal?.rows, DETAIL_CHROME_ROWS);
7022
+ if (modelPicker) return renderFleetModelPicker(detailRow.name, modelPicker.choices, modelPicker, w, body, theme);
7023
+ const entries = timeline();
7024
+ if (followTail) scrollOffset = Math.max(0, detailContent(entries, w, expandedIndex).length - body);
7025
+ return renderFleetDetail(detailRow, entries, scrollOffset, w, body, theme, expandedIndex);
7026
+ },
7027
+ handleInput: async (data: string) => {
7028
+ const input = matchedFleetDetailInput(data);
7029
+ const body = bodyRows(tui.terminal?.rows, DETAIL_CHROME_ROWS);
7030
+ if (modelPicker) {
7031
+ const action = modelPickerTransition(input, modelPicker, modelPicker.choices.length, body);
7032
+ if (action === "cancel") modelPicker = null;
7033
+ else if (action === "select") {
7034
+ const picked = modelPicker.choices[modelPicker.index]?.spec;
7035
+ modelPicker = null;
7036
+ if (picked && applyFleetDetailModel(detailRow, picked, ctx)) {
7037
+ const effectivePicked = substitutedModel(picked) ?? picked;
7038
+ detailRow = { ...detailRow, model: detailRow.status === "running" ? `${detailRow.model} → ${shortModel(effectivePicked)} next` : `${shortModel(effectivePicked)} (next)` };
7039
+ }
7040
+ }
7041
+ tui.requestRender();
7042
+ return;
7043
+ }
7044
+ const entries = timeline();
7045
+ const state = { scrollOffset, selectedIndex, expandedIndex, followTail };
7046
+ const action = detailTransition(input, state, entries, body, detailContent(entries, tui.terminal?.columns ?? 80, expandedIndex).length);
7047
+ ({ scrollOffset, selectedIndex, expandedIndex, followTail } = state);
7048
+ if (action === "close") done();
7049
+ else if (action === "copy") {
7050
+ const item = entries[selectedIndex];
7051
+ 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"); } }
7052
+ } else if (action === "model") {
7053
+ const loaded = await loadFleetDetailModelChoices(detailRow, ctx);
7054
+ if (loaded) {
7055
+ const currentIndex = loaded.choices.findIndex(choice => choice.spec === loaded.current);
7056
+ modelPicker = { choices: loaded.choices, index: Math.max(0, currentIndex), scrollOffset: Math.max(0, currentIndex) };
7057
+ }
7058
+ }
7059
+ tui.requestRender();
7060
+ },
7061
+ invalidate() {},
7062
+ dispose: () => resources.dispose(),
7063
+ };
6704
7064
  }, FULLSCREEN_OVERLAY); } finally { resources.dispose(); if (target) target.zoomRender = undefined; }
6705
7065
  }
6706
7066
  async function restartFleetRow(selected: FleetRow, ctx: any): Promise<void> {
7067
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
6707
7068
  const decision = resolveFleetRestart(selected, {
6708
7069
  researchRestartable: (key) => {
6709
7070
  const state = researchStates.get(parseResearchHandle(key)!);
@@ -6738,12 +7099,23 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6738
7099
  const result = await dispatchAgent(state.def.name, state.task, ctx);
6739
7100
  pi.sendMessage({ customType: "agent-restart-result", content: `[${displayName(state.def.name)}] restarted by operator and ${result.exitCode === 0 ? "completed" : "failed"} in ${Math.round(result.elapsed / 1000)}s.`, display: true }, { deliverAs: "followUp", triggerTurn: true });
6740
7101
  }
6741
- async function openFleetDashboard(ctx: any): Promise<void> {
7102
+ type FleetSubstitutionPickerState = {
7103
+ stage: "source" | "target";
7104
+ source?: string;
7105
+ choices: FleetModelChoice[];
7106
+ index: number;
7107
+ scrollOffset: number;
7108
+ };
7109
+
7110
+ async function openFleetDashboard(ctx: any, startSubstitution = false): Promise<void> {
6742
7111
  const resources = createPanelResources();
6743
7112
  const selection: Selection = { index: 0 };
6744
7113
  let scrollOffset = 0;
6745
7114
  let filtering = false;
6746
7115
  let confirm: DashboardConfirm = null;
7116
+ let substitutionPicker: FleetSubstitutionPickerState | null = startSubstitution
7117
+ ? { stage: "source", choices: substitutionSourceChoices(), index: 0, scrollOffset: 0 }
7118
+ : null;
6747
7119
  const toInput = (data: string): string => {
6748
7120
  if (matchesKey(data, Key.up)) return "\u001b[A";
6749
7121
  if (matchesKey(data, Key.down)) return "\u001b[B";
@@ -6761,6 +7133,12 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6761
7133
  const rows = fleetRows();
6762
7134
  reconcileSelection(selection, rows);
6763
7135
  const body = bodyRows(tui.terminal?.rows, FLEET_CHROME_ROWS);
7136
+ if (substitutionPicker) {
7137
+ return renderFleetSubstitutionPicker(
7138
+ substitutionPicker.stage, substitutionPicker.source, substitutionPicker.choices,
7139
+ substitutionPicker, w, body, theme,
7140
+ );
7141
+ }
6764
7142
  scrollOffset = clampScroll(scrollOffset, rows.length, body);
6765
7143
  const summary = summarise(rows);
6766
7144
  return renderFleetDashboard({
@@ -6775,13 +7153,44 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6775
7153
  const rows = fleetRows();
6776
7154
  reconcileSelection(selection, rows);
6777
7155
  const body = bodyRows(tui.terminal?.rows, FLEET_CHROME_ROWS);
7156
+ const input = toInput(data);
7157
+ if (substitutionPicker) {
7158
+ const action = modelPickerTransition(input, substitutionPicker, substitutionPicker.choices.length, body);
7159
+ if (action === "cancel") {
7160
+ if (substitutionPicker.stage === "target") {
7161
+ const source = substitutionPicker.source;
7162
+ const choices = substitutionSourceChoices();
7163
+ const index = Math.max(0, choices.findIndex(choice => choice.spec === source));
7164
+ substitutionPicker = { stage: "source", choices, index, scrollOffset: index };
7165
+ } else substitutionPicker = null;
7166
+ } else if (action === "select") {
7167
+ const picked = substitutionPicker.choices[substitutionPicker.index]?.spec;
7168
+ if (picked && substitutionPicker.stage === "source") {
7169
+ const targets = await loadAvailableModelChoices(ctx, modelSubstitutions.get(picked));
7170
+ if (targets) {
7171
+ const current = modelSubstitutions.get(picked);
7172
+ const index = Math.max(0, targets.findIndex(choice => choice.spec === current));
7173
+ substitutionPicker = { stage: "target", source: picked, choices: targets, index, scrollOffset: index };
7174
+ }
7175
+ } else if (picked && substitutionPicker.source) {
7176
+ await applySessionModelSubstitution(substitutionPicker.source, picked, ctx);
7177
+ substitutionPicker = null;
7178
+ }
7179
+ }
7180
+ tui.requestRender();
7181
+ return;
7182
+ }
6778
7183
  const state = { selection, scrollOffset, filtering, filterQuery: fleetFilter, showFinished: fleetShowFinished, confirm };
6779
- const intent = dashboardTransition(toInput(data), state, rows, body);
7184
+ const intent = dashboardTransition(input, state, rows, body);
6780
7185
  ({ scrollOffset, filtering, confirm } = state);
6781
7186
  fleetFilter = state.filterQuery;
6782
7187
  fleetShowFinished = state.showFinished;
6783
7188
  if (intent === "close") done();
6784
- else if (intent && typeof intent === "object" && "open" in intent) {
7189
+ else if (intent === "substitute") {
7190
+ const choices = substitutionSourceChoices();
7191
+ if (choices.length === 0) ctx.ui.notify("No configured persona or sub-role models are available as substitution sources.", "warning");
7192
+ else substitutionPicker = { stage: "source", choices, index: 0, scrollOffset: 0 };
7193
+ } else if (intent && typeof intent === "object" && "open" in intent) {
6785
7194
  const selected = rows.find(r => r.key === intent.open) ?? rows[selection.index];
6786
7195
  if (selected) await openFleetDetail(selected, ctx);
6787
7196
  } else if (intent && typeof intent === "object" && "kill" in intent) {
@@ -6867,6 +7276,178 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6867
7276
  },
6868
7277
  });
6869
7278
 
7279
+ function toolSchemaChars(toolList: string): number {
7280
+ const names = toolList.split(",").map(name => name.trim()).filter(Boolean);
7281
+ const all = typeof pi.getAllTools === "function" ? pi.getAllTools() : [];
7282
+ const byName = new Map(all.map((tool: any) => [tool.name, tool]));
7283
+ return names.reduce((sum, name) => {
7284
+ const tool = byName.get(name);
7285
+ return sum + (tool ? safeSchemaChars({ name: tool.name, description: tool.description, parameters: tool.parameters, promptGuidelines: tool.promptGuidelines }) : name.length);
7286
+ }, 0);
7287
+ }
7288
+ function contextPlanes(ctx: any): LivePlane[] {
7289
+ // Keep the projection decomposed along the same standing components native
7290
+ // spawn appends. It intentionally counts no task/history: this is cold-start.
7291
+ const baseChars = safeSchemaChars(ctx?.getSystemPromptOptions?.() ?? {});
7292
+ const projection = (def: AgentDef, research = false) => research
7293
+ ? researchStandingParts({
7294
+ replacementPrompt: nativeResearchSystemPrompt({
7295
+ personaName: def.name,
7296
+ personaPath: def.file,
7297
+ cwd: ctx?.cwd || process.cwd(),
7298
+ }),
7299
+ toolChars: toolSchemaChars(RESEARCH_TOOLS),
7300
+ // --system-prompt plus --no-skills/--no-context-files replaces
7301
+ // inherited child prompt inputs; only the explicit prompt/tools remain.
7302
+ basePromptChars: 0,
7303
+ })
7304
+ : specialistStandingParts({
7305
+ replacementPrompt: nativeSpecialistSystemPrompt({
7306
+ // An active child projects the exact metadata retained for its
7307
+ // spawn/resume; an inactive card is a task-free cold-start estimate.
7308
+ manifest: agentStates.get(def.name.toLowerCase())?.specialistManifest
7309
+ ?? buildSpecialistContextManifest({
7310
+ personaName: def.name, personaPath: def.file, personaPrompt: def.systemPrompt,
7311
+ task: "", rulesPaths: specialistProjectPolicyPaths(ctx?.cwd || process.cwd()), docsPaths: projectDocsPaths,
7312
+ hasAssertions: false, hasScope: false, hasArtifacts: false,
7313
+ delegateRoles: def.subagents && delegateExtPath ? Object.keys(def.subagents) : [],
7314
+ }),
7315
+ userLanguage, agentKey: safeAgentKey(def.name), runNumber: agentStates.get(def.name.toLowerCase())?.runCount ?? 0,
7316
+ }),
7317
+ toolChars: toolSchemaChars(def.tools),
7318
+ });
7319
+ const delegateProjection = (owner: AgentState, child: DelegationChild) => {
7320
+ const roleEntry = Object.entries(owner.def.subagents ?? {}).find(([name]) => name.toLowerCase() === child.role.toLowerCase());
7321
+ if (!roleEntry) return undefined;
7322
+ return delegateStandingParts({
7323
+ toolChars: toolSchemaChars(child.tools || roleEntry[1].tools || owner.def.tools),
7324
+ basePromptChars: baseChars,
7325
+ roleNames: [roleEntry[0]],
7326
+ });
7327
+ };
7328
+ const windowFor = (model: string) => model ? resolveContextWindow(model, { lookup: modelWindowLookup(ctx), fallbackWindow: 0 }).window || undefined : undefined;
7329
+ const local = allAgentDefs.filter(def => def.kind !== "research").map(def => {
7330
+ const state = agentStates.get(def.name.toLowerCase());
7331
+ const model = state ? (resolvedModel(state.def) ?? "") : (resolvedModel(def) ?? "");
7332
+ return { id: `specialist/${def.name}`, label: displayName(def.name), plane: "specialist" as const, model, window: windowFor(model), tokens: state?.contextTokens, projectionParts: projection(def) };
7333
+ });
7334
+ const research = researchPersonas.map(def => {
7335
+ const active = Array.from(researchStates.values()).find(state => state.def.name === def.name);
7336
+ const model = active?.model ?? resolvedModel(def) ?? "";
7337
+ 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 };
7338
+ });
7339
+ const delegates = Array.from(agentStates.values()).flatMap(state => Array.from(state.delegations?.values() ?? []).map(child => {
7340
+ const projectionParts = delegateProjection(state, child);
7341
+ return projectionParts
7342
+ ? { 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 }
7343
+ : { 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 };
7344
+ }));
7345
+ 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 }));
7346
+ return [...local, ...research, ...delegates, ...peers];
7347
+ }
7348
+
7349
+ async function openContextBudget(ctx: any): Promise<void> {
7350
+ const resources = createPanelResources();
7351
+ const toInput = (data: string): string => {
7352
+ if (matchesKey(data, Key.up)) return "\u001b[A";
7353
+ if (matchesKey(data, Key.down)) return "\u001b[B";
7354
+ if (matchesKey(data, Key.pageUp)) return "\u001b[5~";
7355
+ if (matchesKey(data, Key.pageDown)) return "\u001b[6~";
7356
+ if (matchesKey(data, Key.enter)) return "\r";
7357
+ if (matchesKey(data, Key.escape)) return "\u001b";
7358
+ return data;
7359
+ };
7360
+ const state: ContextBudgetViewState = { selection: { index: 0 }, expanded: new Set(), scrollOffset: 0 };
7361
+ const collect = () => {
7362
+ // Build the replacement prompt ledger now rather than waiting for the first
7363
+ // before_agent_start hook; this is pure prompt construction, not a turn.
7364
+ buildHubSystemPrompt(false);
7365
+ return collectContextBudgetSnapshot(ctx, {
7366
+ ledger: lastHubLedger,
7367
+ pressure: contextPressureDiagnostic(contextPressureState),
7368
+ planes: contextPlanes(ctx),
7369
+ tools: typeof pi.getAllTools === "function" ? pi.getAllTools() : [],
7370
+ activeToolNames: typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [],
7371
+ commands: typeof pi.getCommands === "function" ? pi.getCommands() : [],
7372
+ });
7373
+ };
7374
+ let snapshot = collect();
7375
+ const refresh = () => { snapshot = collect(); };
7376
+ try {
7377
+ await ctx.ui.custom((tui: any, _theme: any, _kb: any, done: () => void) => {
7378
+ resources.every(1000, () => { refresh(); tui.requestRender(); });
7379
+ return {
7380
+ render: (w: number) => renderContextBudget(snapshot, state, w, bodyRows(tui.terminal?.rows, CONTEXT_BUDGET_CHROME_ROWS)),
7381
+ 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(); },
7382
+ invalidate() {}, dispose: () => resources.dispose(),
7383
+ };
7384
+ }, FULLSCREEN_OVERLAY);
7385
+ } finally { resources.dispose(); }
7386
+ }
7387
+
7388
+ pi.registerCommand("af-context", {
7389
+ description: "Open a read-only full-screen context budget diagnostic",
7390
+ handler: async (_args, ctx) => { widgetCtx = ctx; await openContextBudget(ctx); },
7391
+ });
7392
+
7393
+ function rosterRefusalMessage(): string {
7394
+ return "Orchestrator posture requires at least one native specialist. Add one with /af-agents-add or select /af-agents-team first.";
7395
+ }
7396
+
7397
+ function watchdogArmedNote(next: Posture): string {
7398
+ if (next !== "orchestrator") return "";
7399
+ const armed = resolveWatchdogActive(undefined, undefined, watchdogSetting, next);
7400
+ return armed
7401
+ ? "\nDrift watchdog: armed (orchestrator auto). /af-watchdog off to disarm."
7402
+ : "\nDrift watchdog: off (explicit hub setting).";
7403
+ }
7404
+
7405
+ async function commitPosture(next: Posture, ctx: ExtensionContext): Promise<"ok" | "unchanged" | "roster"> {
7406
+ if (orchestratorNeedsRoster(next, agentStates.size)) return "roster";
7407
+ if (next === posture) return "unchanged";
7408
+ posture = next;
7409
+ if (posture === "operator") {
7410
+ rosterRecoveryRequired = false;
7411
+ rosterRecoveryDiagnostic = "";
7412
+ setTimeout(replayDeferredRecoveryInputs, 0);
7413
+ }
7414
+ if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
7415
+ await pickDispatcherPersona(ctx);
7416
+ }
7417
+ resolveIncomingCapabilities("");
7418
+ applyPostureTools();
7419
+ updatePostureStatus(ctx);
7420
+ pi.appendEntry("agent-hub-posture", { posture });
7421
+ return "ok";
7422
+ }
7423
+
7424
+ async function applyPostureSelection(next: Posture, ctx: ExtensionContext, deprecatedFrom?: string): Promise<void> {
7425
+ if (executionPairBlockedByRoster(posture, next, agentStates.size)) {
7426
+ ctx.ui.notify(rosterRefusalMessage(), "warning");
7427
+ return;
7428
+ }
7429
+ const result = await commitPosture(next, ctx);
7430
+ if (result === "roster") {
7431
+ ctx.ui.notify(rosterRefusalMessage(), "warning");
7432
+ return;
7433
+ }
7434
+ const deprecation = deprecatedFrom
7435
+ ? `"${deprecatedFrom}" is no longer an execution mode; mapped to ${next} posture.\n`
7436
+ : "";
7437
+ ctx.ui.notify(
7438
+ `${deprecation}${postureStatusText()}\nPrompt and tools update on the next model call.${watchdogArmedNote(next)}`,
7439
+ result === "ok" ? "success" : "info",
7440
+ );
7441
+ }
7442
+
7443
+ async function openPosturePicker(ctx: ExtensionContext): Promise<void> {
7444
+ const picker = posturePickerOptions(posture);
7445
+ const choice = await ctx.ui.select(picker.title, picker.options);
7446
+ const next = selectedPickerValue(picker.options, choice, picker.postures);
7447
+ if (!next) return;
7448
+ await applyPostureSelection(next, ctx);
7449
+ }
7450
+
6870
7451
  // ── /af-posture: direct operator ↔ restricted orchestrator ──
6871
7452
  pi.registerCommand("af-posture", {
6872
7453
  description: "Show or set the Fleet posture: operator (direct tools) | orchestrator (delegate-only)",
@@ -6874,6 +7455,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6874
7455
  widgetCtx = ctx;
6875
7456
  const requested = (args || "").trim();
6876
7457
  if (!requested) {
7458
+ if (ctx.hasUI && typeof ctx.ui.select === "function") {
7459
+ await openPosturePicker(ctx);
7460
+ return;
7461
+ }
6877
7462
  ctx.ui.notify(`${postureStatusText()}\nSwitch with /af-posture operator|orchestrator`, "info");
6878
7463
  return;
6879
7464
  }
@@ -6882,77 +7467,31 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6882
7467
  ctx.ui.notify(`Unknown posture "${requested}" — expected operator|orchestrator.`, "error");
6883
7468
  return;
6884
7469
  }
6885
- if (orchestratorNeedsRoster(next, agentStates.size)) {
6886
- ctx.ui.notify("Orchestrator posture requires at least one native specialist. Add one with /af-agents-add or select /af-agents-team first.", "warning");
6887
- return;
6888
- }
6889
- posture = next;
6890
- if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
6891
- await pickDispatcherPersona(ctx);
6892
- }
6893
- applyPostureTools();
6894
- updatePostureStatus(ctx);
6895
- pi.appendEntry("agent-hub-posture", { posture });
6896
- ctx.ui.notify(`${postureStatusText()}\nPrompt and tools update on the next model call.`, "success");
7470
+ await applyPostureSelection(next, ctx);
6897
7471
  },
6898
7472
  });
6899
7473
 
6900
- // ── /af-hub-mode: execution mode (fast|standard|strict) ──
6901
- // Session-lifetime switch over the overrides-file default. Budgets bind on
6902
- // the NEXT tool call (counters are per user turn and keep running); the
6903
- // dispatcher prompt rebuilds with the new mode on the next turn.
6904
- pi.registerCommand("af-hub-mode", {
6905
- description: "Show or set the execution mode: fast (single specialist) | standard (batched, default) | strict (full Verification Contract)",
7474
+ pi.registerCommand("af-work-mode", {
7475
+ description: "Show or set Fleet posture (operator | orchestrator). Alt+M opens the picker.",
6906
7476
  handler: async (args, ctx) => {
6907
7477
  widgetCtx = ctx;
6908
- const requested = (args || "").trim();
6909
- if (!requested) {
6910
- const b = currentBudget();
6911
- const cap = (n: number | null) => (n == null ? "∞" : String(n));
7478
+ const parsed = parseWorkModeArgs(args);
7479
+ if (!parsed.ok) {
7480
+ ctx.ui.notify(parsed.error, "error");
7481
+ return;
7482
+ }
7483
+ if (parsed.action === "apply") {
7484
+ await applyPostureSelection(parsed.posture, ctx, parsed.deprecatedFrom);
7485
+ return;
7486
+ }
7487
+ if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
6912
7488
  ctx.ui.notify(
6913
- `Execution mode: ${hubMode}\nThis turn: ${turnDispatchCount}/${cap(b.maxDispatches)} dispatches, ` +
6914
- `${turnResearchCount}/${cap(b.maxResearch)} research\nSwitch with /af-hub-mode ${HUB_MODES.join("|")}`,
7489
+ `${postureStatusText()}\nSwitch with /af-work-mode operator|orchestrator`,
6915
7490
  "info",
6916
7491
  );
6917
7492
  return;
6918
7493
  }
6919
- const mode = normalizeHubMode(requested);
6920
- if (!mode) {
6921
- ctx.ui.notify(`Unknown mode "${requested}" — expected one of: ${HUB_MODES.join(", ")}`, "error");
6922
- return;
6923
- }
6924
- const previousMode = hubMode;
6925
- hubMode = mode;
6926
- updateModeStatus();
6927
- appendHubModeEntry({ previousMode, mode, source: "slash-command", ctx });
6928
- ctx.ui.notify(
6929
- `Execution mode → ${mode} (budgets apply from the next dispatch; prompt updates next turn)` + hubLocationSuffix(ctx),
6930
- "success",
6931
- );
6932
- },
6933
- });
6934
-
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
- );
7494
+ await openPosturePicker(ctx);
6956
7495
  },
6957
7496
  });
6958
7497
 
@@ -7064,6 +7603,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7064
7603
  }
7065
7604
  teams[name] = members;
7066
7605
  activeTeamName = name;
7606
+ persistActiveRoster();
7067
7607
  ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
7068
7608
  ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "success");
7069
7609
  },
@@ -7114,6 +7654,20 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7114
7654
  void openFleetDashboard(ctx);
7115
7655
  },
7116
7656
  });
7657
+ pi.registerShortcut("alt+m", {
7658
+ description: "Open posture picker",
7659
+ handler: (ctx) => {
7660
+ widgetCtx = ctx;
7661
+ if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
7662
+ ctx.ui.notify(
7663
+ `${postureStatusText()}\nSwitch with /af-work-mode operator|orchestrator`,
7664
+ "info",
7665
+ );
7666
+ return;
7667
+ }
7668
+ void openPosturePicker(ctx);
7669
+ },
7670
+ });
7117
7671
  pi.registerShortcut("alt+shift+a", {
7118
7672
  description: "Toggle compact agent widget",
7119
7673
  handler: (ctx) => { widgetCtx = ctx; viewMode = viewMode === "compact" ? "off" : "compact"; updateWidget(); updateResearchWidget(); ctx.ui.notify(`Compact agent widget: ${viewMode}`, "info"); },
@@ -7301,9 +7855,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7301
7855
  const roleItems = Array.from(agentStates.values()).flatMap(s =>
7302
7856
  Object.entries(s.def.subagents || {}).map(([role, r]) => {
7303
7857
  const override = subagentModelOverrides.get(`${s.def.name.toLowerCase()}.${role.toLowerCase()}`);
7858
+ const effective = resolvedSubagentModel(s.def.name, role, r.model);
7304
7859
  return {
7305
7860
  value: `${s.def.name}.${role}`,
7306
- label: `${s.def.name}.${role} — ${shortModel(override ?? r.model)}${override ? " (switched)" : ""}`,
7861
+ label: `${s.def.name}.${role} — ${shortModel(effective)}${override || effective !== r.model ? " (switched)" : ""}`,
7307
7862
  };
7308
7863
  }),
7309
7864
  );
@@ -7350,7 +7905,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7350
7905
  for (const m of [role.model, ...allowedModels(parent.def)]) {
7351
7906
  if (m && !candidates.includes(m)) candidates.push(m);
7352
7907
  }
7353
- const current = subagentModelOverrides.get(overrideKey) ?? role.model;
7908
+ const current = resolvedSubagentModel(parent.def.name, roleKey, role.model);
7354
7909
  const options = candidates.map(m => {
7355
7910
  const tags = [m === role.model ? "default" : "", m === current ? "current" : ""].filter(Boolean);
7356
7911
  return tags.length ? `${m} (${tags.join(", ")})` : m;
@@ -7359,8 +7914,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7359
7914
  const choice = await ctx.ui.select(`Model for ${label}`, options);
7360
7915
  if (choice === undefined) return;
7361
7916
  const picked = candidates[options.indexOf(choice)];
7362
- if (picked === current) {
7363
- ctx.ui.notify(`${label} is already on ${picked}`, "info");
7917
+ const effectivePicked = substitutedModel(picked) ?? picked;
7918
+ if (effectivePicked === current) {
7919
+ ctx.ui.notify(`${label} is already on ${effectivePicked}`, "info");
7364
7920
  return;
7365
7921
  }
7366
7922
  if (picked === role.model) {
@@ -7370,7 +7926,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7370
7926
  }
7371
7927
  updateWidget();
7372
7928
  ctx.ui.notify(
7373
- `${label} → ${picked} (applies on next dispatch of ${parent.def.name})`,
7929
+ `${label} → ${effectivePicked} (applies on next dispatch of ${parent.def.name})`,
7374
7930
  "success",
7375
7931
  );
7376
7932
  return;
@@ -7409,9 +7965,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7409
7965
  const choice = await ctx.ui.select(`Model for ${displayName(def.name)}`, options);
7410
7966
  if (choice === undefined) return;
7411
7967
  const picked = candidates[options.indexOf(choice)];
7412
- const pickedIsCurrent = current ? picked === current : picked === DISPATCHER_DEFAULT;
7968
+ const effectivePicked = picked === DISPATCHER_DEFAULT ? picked : (substitutedModel(picked) ?? picked);
7969
+ const pickedIsCurrent = current ? effectivePicked === current : picked === DISPATCHER_DEFAULT;
7413
7970
  if (pickedIsCurrent) {
7414
- ctx.ui.notify(`${displayName(def.name)} is already on ${picked}`, "info");
7971
+ ctx.ui.notify(`${displayName(def.name)} is already on ${effectivePicked}`, "info");
7415
7972
  return;
7416
7973
  }
7417
7974
  if (picked === def.model || picked === DISPATCHER_DEFAULT) {
@@ -7425,7 +7982,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7425
7982
  const applyHint = (def.kind || "").toLowerCase() === "research"
7426
7983
  ? "applies on next /af-research or spawn_research"
7427
7984
  : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
7428
- ctx.ui.notify(`${displayName(def.name)} → ${picked} (${applyHint})`, "success");
7985
+ ctx.ui.notify(`${displayName(def.name)} → ${effectivePicked} (${applyHint})`, "success");
7429
7986
  if ((dispatchPolicy.substitutions[name]?.prefer ?? dispatchPolicy.default) === "coms") {
7430
7987
  ctx.ui.notify(
7431
7988
  `Note: ${displayName(def.name)} prefers a coms peer (dispatch-policy.yaml) — this model override only applies to native(-fallback) runs; the peer keeps its own model.`,
@@ -7553,113 +8110,59 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7553
8110
  },
7554
8111
  });
7555
8112
 
7556
- // All known model strings across every persona (allowedModels union), deduped
7557
- // preserving first-seen order. Used for /af-agent-models-substitute autocomplete.
8113
+ // Every configured model source across persona defaults/candidates, retained
8114
+ // fallbacks, and delegate sub-roles. Active mapping keys remain visible so the
8115
+ // operator can replace a session substitution even if the roster changes.
7558
8116
  function allKnownModels(): string[] {
7559
8117
  const seen = new Set<string>();
7560
8118
  const out: string[] = [];
8119
+ const add = (model: string | undefined) => {
8120
+ if (model && !seen.has(model)) { seen.add(model); out.push(model); }
8121
+ };
7561
8122
  for (const def of allAgentDefs) {
7562
- for (const m of allowedModels(def)) {
7563
- if (m && !seen.has(m)) { seen.add(m); out.push(m); }
8123
+ add(def.model);
8124
+ add(def.fallbackModel);
8125
+ for (const model of def.models ?? []) add(model);
8126
+ for (const role of Object.values(def.subagents ?? {})) {
8127
+ add(role.model);
8128
+ add(role.fallbackModel);
7564
8129
  }
7565
8130
  }
8131
+ for (const model of modelOverrides.values()) add(model);
8132
+ for (const model of subagentModelOverrides.values()) add(model);
8133
+ for (const source of modelSubstitutions.keys()) add(source);
7566
8134
  return out;
7567
8135
  }
7568
8136
 
7569
- // Completions for /af-agent-models-substitute: a flat list of known models.
7570
- // Free text allowed too — we just suggest, never restrict, so ad-hoc targets
7571
- // (e.g. a model a persona does not declare) still produce a clean "skipped"
7572
- // report at apply time.
7573
8137
  const substituteCompletions = (prefix: string): AutocompleteItem[] | null => {
7574
- const items = allKnownModels().map(m => ({ value: m, label: m }));
8138
+ const items = substitutionSourceChoices().map(choice => ({ value: choice.spec, label: choice.label }));
7575
8139
  if (items.length === 0) return null;
7576
8140
  const p = prefix.toLowerCase();
7577
8141
  const filtered = items.filter(i => i.value.toLowerCase().startsWith(p));
7578
8142
  return filtered.length > 0 ? filtered : items;
7579
8143
  };
7580
8144
 
7581
- // /af-agent-models-substitute <source> <target> — replace one model across all
7582
- // personas (team members + research + orchestrator; never the dispatcher).
7583
- // Per-persona validity: target must be in that persona's allowedModels.
7584
- // Applies session-lifetime (same lifetime as /af-agent-model); takes effect on
7585
- // the persona's NEXT dispatch (/af-agents-restart applies it immediately).
7586
- // One-step flow: dry-run summary is shown up front, then the swap is
7587
- // applied unconditionally — the operator runs the command to commit.
8145
+ // Bare command opens the exact same source → available-target picker as `m` in
8146
+ // Fleet Dashboard. The two-argument form remains available for scripting.
7588
8147
  pi.registerCommand("af-agent-models-substitute", {
7589
- description: "Replace one model across all personas: /af-agent-models-substitute <source> <target>",
8148
+ description: "Save a session-wide model substitution: /af-agent-models-substitute [<source> <target>]",
7590
8149
  getArgumentCompletions: substituteCompletions,
7591
8150
  handler: async (args, ctx) => {
7592
8151
  widgetCtx = ctx;
7593
8152
  const tokens = (args || "").trim().split(/\s+/).filter(Boolean);
7594
- if (tokens.length !== 2) {
7595
- ctx.ui.notify(
7596
- `Usage: /af-agent-models-substitute <source> <target>. ` +
7597
- `Both must be model specs (e.g. openai-codex/gpt-5.3-codex-spark).`,
7598
- "error",
7599
- );
7600
- return;
7601
- }
7602
- const [source, target] = tokens;
7603
-
7604
- // Build the dry-run. Walk every loaded persona (team + research +
7605
- // orchestrator all live in allAgentDefs) and decide per-persona:
7606
- // - "match" : current effective model === source AND target is a
7607
- // declared candidate → will be switched.
7608
- // - "skip" : any other case, with a reason.
7609
- const matches: { def: AgentDef; current: string }[] = [];
7610
- const skipped: { def: AgentDef; reason: string }[] = [];
7611
- for (const def of allAgentDefs) {
7612
- const current = resolvedModel(def);
7613
- if (!current) {
7614
- skipped.push({ def, reason: "no default model (runs on dispatcher's model)" });
7615
- continue;
7616
- }
7617
- if (current !== source) {
7618
- skipped.push({ def, reason: `current is ${current} (not ${source})` });
7619
- continue;
7620
- }
7621
- if (!allowedModels(def).includes(target)) {
7622
- skipped.push({ def, reason: `target ${target} not in declared candidates (model:/af-models: in ${def.file})` });
7623
- continue;
8153
+ if (tokens.length === 0) {
8154
+ if (allKnownModels().length === 0) {
8155
+ ctx.ui.notify("No configured persona or sub-role models are available as substitution sources.", "warning");
8156
+ return;
7624
8157
  }
7625
- matches.push({ def, current });
7626
- }
7627
-
7628
- // If target === source, the substitution is a no-op. We still report
7629
- // it so the operator sees that the request was understood.
7630
- if (source === target) {
7631
- ctx.ui.notify(
7632
- `Source and target are the same (${source}); nothing to do. ` +
7633
- `Affected: ${matches.length}, skipped: ${skipped.length}.`,
7634
- "info",
7635
- );
8158
+ await openFleetDashboard(ctx, true);
7636
8159
  return;
7637
8160
  }
7638
-
7639
- // Apply: for every match, if the persona's frontmatter default IS the
7640
- // target, clear any existing override (so it tracks frontmatter
7641
- // updates); otherwise record target in modelOverrides. Mirrors
7642
- // /af-agent-model and /af-models.
7643
- const applied: string[] = [];
7644
- for (const { def } of matches) {
7645
- const key = def.name.toLowerCase();
7646
- if (def.model === target) {
7647
- modelOverrides.delete(key);
7648
- } else {
7649
- modelOverrides.set(key, target);
7650
- }
7651
- applied.push(`${displayName(def.name)}: ${source} → ${target}`);
8161
+ if (tokens.length !== 2) {
8162
+ ctx.ui.notify("Usage: /af-agent-models-substitute [<source> <target>]", "error");
8163
+ return;
7652
8164
  }
7653
-
7654
- const skipDetails = skipped.map(s => `${displayName(s.def.name)}: ${s.reason}`);
7655
- const summary = [
7656
- `Substitution ${source} → ${target}:`,
7657
- ` Affected: ${applied.length}${applied.length ? ` (${applied.join(", ")})` : ""}`,
7658
- ` Skipped: ${skipped.length}${skipped.length ? ` (${skipDetails.join("; ")})` : ""}`,
7659
- ` Applies on next dispatch (/af-agents-restart to apply now).`,
7660
- ].join("\n");
7661
- updateWidget();
7662
- ctx.ui.notify(summary, applied.length > 0 ? "success" : "info");
8165
+ await applySessionModelSubstitution(tokens[0], tokens[1], ctx);
7663
8166
  },
7664
8167
  });
7665
8168
 
@@ -7682,6 +8185,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7682
8185
  getArgumentCompletions: researchPersonaCompletions,
7683
8186
  handler: async (args, ctx) => {
7684
8187
  widgetCtx = ctx;
8188
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7685
8189
  let rest = (args ?? "").trim();
7686
8190
  let personaName: string | undefined;
7687
8191
  let modelArg: string | undefined;
@@ -7757,6 +8261,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7757
8261
  // its /af-research-cont alias.
7758
8262
  const researchContHandler = async (args: string | undefined, ctx: any) => {
7759
8263
  widgetCtx = ctx;
8264
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7760
8265
  const trimmed = (args ?? "").trim();
7761
8266
  const sp = trimmed.indexOf(" ");
7762
8267
  if (sp === -1) {
@@ -7961,6 +8466,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
7961
8466
  getArgumentCompletions: subagentTargetCompletions,
7962
8467
  handler: async (args, ctx) => {
7963
8468
  widgetCtx = ctx;
8469
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
7964
8470
  const name = args?.trim();
7965
8471
  // An rN handle re-runs a finished helper's last task on a fresh session
7966
8472
  // (unlike /af-agents-cont, which resumes the existing one). A running helper
@@ -8141,6 +8647,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8141
8647
  description: "Hand the session off to a coms peer (the dispatcher composes a self-contained brief): /af-handoff <peer>",
8142
8648
  getArgumentCompletions: comsPeerCompletions,
8143
8649
  handler: async (args, ctx) => {
8650
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
8144
8651
  if (!comsReady) { ctx.ui.notify("coms is not active in this session — /af-handoff unavailable.", "warning"); return; }
8145
8652
  const target = (args ?? "").trim();
8146
8653
  if (!target) {
@@ -8178,6 +8685,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8178
8685
  pi.registerCommand("af-compound", {
8179
8686
  description: "Capture this session's lessons into the project's rules/docs via the documenter: /af-compound [focus]",
8180
8687
  handler: async (args, ctx) => {
8688
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
8181
8689
  if (!agentStates.has("documenter")) {
8182
8690
  ctx.ui.notify(
8183
8691
  "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 +8730,32 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8222
8730
  pi.on("tool_execution_start", async (event) => {
8223
8731
  if (event.toolName !== "ask_user") return;
8224
8732
  askUserStarts.set(event.toolCallId, Date.now());
8733
+ const kind = budgetContinuationKind(event.args?.context);
8734
+ if (kind && pendingBudgetContinuation?.kind === kind) {
8735
+ budgetContinuationAsks.set(event.toolCallId, {
8736
+ kind,
8737
+ reason: pendingBudgetContinuation.reason,
8738
+ params: event.args,
8739
+ });
8740
+ }
8225
8741
  // Asking the human IS the escalation the external-blocker breaker demands:
8226
8742
  // once it is under way, the gate opens.
8227
8743
  externalBlockerAcknowledged = true;
8228
8744
  externalBlockerRefusedOnce = false;
8229
8745
  });
8746
+ observeAskUserResults(({ params, result, phase }) => {
8747
+ const pack = capabilityConfirmationPack(params.context);
8748
+ if (!pack) return;
8749
+ if (phase === "start") capabilityConfirmation[pack] = "pending";
8750
+ else {
8751
+ const outcome = confirmationOutcome(result);
8752
+ if (!outcome) return;
8753
+ capabilityConfirmation[pack] = outcome;
8754
+ resolveIncomingCapabilities("");
8755
+ applyPostureTools();
8756
+ }
8757
+ });
8758
+
8230
8759
  pi.on("tool_execution_end", async (event) => {
8231
8760
  if (event.toolName !== "ask_user") return;
8232
8761
  const startedAt = askUserStarts.get(event.toolCallId);
@@ -8234,18 +8763,46 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8234
8763
  // The task clock bills active time only — the human's answer is not the
8235
8764
  // fleet's work, and billing it is what would false-stop a steered session.
8236
8765
  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?.();
8766
+ const waitMs = startedAt == null ? 0 : Math.max(0, endedAt - startedAt);
8767
+ if (startedAt) taskClock = addTaskClockWait(taskClock, waitMs);
8768
+ turnBudgetAskUserWaitMs += waitMs;
8769
+ if (startedAt != null) {
8770
+ const interval: [number, number] = [startedAt, endedAt];
8771
+ // Attach to the live dispatcher entry, or buffer until one is created this turn.
8772
+ if (currentOrchestratorEntry) (currentOrchestratorEntry.awaitIntervals ??= []).push(interval);
8773
+ else turnAskUserIntervals.push(interval);
8774
+ historyRender?.();
8775
+ }
8776
+
8777
+ // Renew only when this exact marked ask selected its first option. This uses
8778
+ // Pi's tool events rather than wrapper internals, so it also works when the
8779
+ // stock ask_user package owns the tool under extension discovery.
8780
+ const confirmation = budgetContinuationAsks.get(event.toolCallId);
8781
+ budgetContinuationAsks.delete(event.toolCallId);
8782
+ if (confirmation) {
8783
+ const outcome = budgetContinuationOutcome(confirmation.params, event.result);
8784
+ if (outcome) pendingBudgetContinuation = null;
8785
+ if (outcome === "continue") {
8786
+ const prior = budgetContinuationSnapshot(confirmation.kind, endedAt);
8787
+ if (confirmation.kind === "task") continueTaskBudgetWindow(endedAt);
8788
+ else renewTurnBudgetWindow(endedAt);
8789
+ appendBudgetContinuationEntry(confirmation.kind, confirmation.reason, prior, currentCtx ?? undefined);
8790
+ widgetCtx?.ui?.notify(
8791
+ confirmation.kind === "task"
8792
+ ? "Task budget continued; task tier, assertions, capabilities, and progress were preserved."
8793
+ : "Turn budget continued; continuing without another message.",
8794
+ "success",
8795
+ );
8796
+ }
8797
+ }
8244
8798
  });
8245
8799
 
8246
8800
  // ── System Prompt Override ───────────────────
8247
8801
 
8248
- pi.on("before_agent_start", async (_event, _ctx) => {
8802
+ // This is also called by /af-context before the first turn. Keep prompt assembly
8803
+ // in this one production path so its ledger describes the exact next replacement.
8804
+ function buildHubSystemPrompt(forTurn: boolean): { systemPrompt: string } {
8805
+ if (forTurn) {
8249
8806
  // Re-assert the selected posture for every turn so prompt and tool policy stay
8250
8807
  // synchronized after commands or runtime capability changes.
8251
8808
  applyPostureTools();
@@ -8268,12 +8825,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8268
8825
  currentOrchestratorEntry = null;
8269
8826
  askUserStarts.clear();
8270
8827
  turnAskUserIntervals.length = 0;
8828
+ turnBudgetAskUserWaitMs = 0;
8829
+ budgetContinuationAsks.clear();
8830
+ if (pendingBudgetContinuation?.kind === "turn") pendingBudgetContinuation = null;
8271
8831
  // Fresh turn → fresh TURN budget window (mode persists across turns). The
8272
8832
  // TASK budget, the tier, and the external-blocker breaker deliberately do
8273
8833
  // NOT reset here: a steering message is a correction to the same work, not
8274
8834
  // 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.
8835
+ // dispatches per correction and never hit a bound. A task continuation is
8836
+ // instead an explicit Yes/No confirmation; genuinely different work uses
8837
+ // set_task_tier with new_task: true.
8277
8838
  turnDispatchCount = 0;
8278
8839
  turnResearchCount = 0;
8279
8840
  turnDispatchFingerprints.clear();
@@ -8288,20 +8849,26 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
8288
8849
  }
8289
8850
  turnReport = freshTurnReport();
8290
8851
  updateModeStatus();
8852
+ }
8291
8853
 
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");
8854
+ const modelPacks = new Set<CapabilityPack>([...capabilityResolution.active, ...capabilityResolution.provisional]);
8855
+ const fleetActive = modelPacks.has("fleet");
8856
+ const verificationActive = modelPacks.has("verification");
8857
+ const peerActive = modelPacks.has("peer");
8858
+ const workspaceActive = modelPacks.has("workspace");
8859
+ const compactionActive = modelPacks.has("compaction");
8860
+ // Fleet roster and research policy are absent unless the fleet pack is model-visible.
8861
+ const agentCards = fleetActive ? Array.from(agentStates.values())
8862
+ .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}` })) : [];
8863
+ const agentCatalog = agentCards.map(card => card.text).join("\n\n");
8296
8864
 
8297
- const teamMembers = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
8865
+ const teamMembers = fleetActive ? Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ") : "";
8298
8866
 
8299
8867
  // Research personas (kind: research) the dispatcher can spawn read-only via
8300
8868
  // 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")
8869
+ 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}` })) : [];
8870
+ const researchCatalog = !fleetActive ? "" : researchCards.length > 0
8871
+ ? researchCards.map(card => card.text).join("\n\n")
8305
8872
  : "(No research personas defined. Call `spawn_research` without `persona` for an ad-hoc read-only helper.)";
8306
8873
 
8307
8874
  // Two flavors of the system prompt depending on whether ask_user is
@@ -8336,11 +8903,9 @@ ask the human. You MUST instead:
8336
8903
  - For \`ASK_USER:\` markers raised by specialists, relay the question verbatim to
8337
8904
  the user in ${userLanguage} and wait for their reply in the next turn.`;
8338
8905
 
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";
8906
+ const toolList = `these active packs: ${[...modelPacks].join(", ")}. Tools: ${pi.getActiveTools().map(name => `\`${name}\``).join(", ") || "(none)"}`;
8342
8907
 
8343
- const dispatchSection = askUserAvailable
8908
+ const dispatchSection = !fleetActive ? "" : askUserAvailable
8344
8909
  ? `- BEFORE dispatching: if anything is ambiguous, missing, or could go several valid
8345
8910
  ways, call \`ask_user\` first. Never invent constraints or "reasonable defaults"
8346
8911
  the user did not state.
@@ -8380,253 +8945,302 @@ ask the human. You MUST instead:
8380
8945
  - When a specialist emits an \`ASK_USER:\` line in English, translate it to
8381
8946
  ${userLanguage} before relaying to the user.${userLanguage.toLowerCase() === "english" ? " (If user-language is English this is a no-op.)" : ""}`;
8382
8947
 
8383
- // ── Execution mode section + mode-conditional Verification Contract ──
8384
- // The mode is the dispatcher's operating envelope: the hub ENFORCES the
8385
- // budgets in code (dispatch_agent/spawn_research refuse past them); the
8386
- // prompt teaches the dispatcher to plan within them instead of hitting them.
8948
+ // ── Task triage + Verification Contract ──
8949
+ // The hub ENFORCES budgets in code (dispatch_agent/spawn_research refuse
8950
+ // past the task-tier envelope); the prompt teaches the dispatcher to plan
8951
+ // within them instead of hitting them.
8387
8952
  const budget = currentBudget();
8388
8953
  const taskBudget = currentTaskBudget();
8389
8954
  const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
8390
8955
  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"
8499
- ? `## Verification (fast mode)
8500
- The assertion ledger is OPTIONAL in fast mode. State what was asked, dispatch the one
8501
- specialist, and verify from its returned evidence (command output, file:line). If the
8502
- request carries real acceptance criteria or turns risky, ask the user to switch to
8503
- standard/strict instead of improvising rigor here.`
8504
- : fullVerificationContract;
8956
+ const capabilityState = [...capabilityResolution.active].map(pack => `${pack}:${capabilityResolution.reasons[pack]}`).join(", ");
8957
+ const provisionalState = capabilityResolution.provisional.map(pack => `${pack}:${capabilityResolution.reasons[pack]}`).join(", ");
8958
+ const stateCapsule = `## Current task state
8959
+ - tier: ${taskTier ?? DEFAULT_TASK_TIER}${taskTierAssumed ? "?" : ""}; turn dispatches: ${turnDispatchCount}; research: ${turnResearchCount}
8960
+ - task dispatches: ${taskDispatchCount}; research: ${taskResearchCount}; review rounds: ${taskReviewRounds}
8961
+ - packs active: ${capabilityState}; provisional: ${provisionalState || "none"}
8962
+ - 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"}
8963
+ - budgets: dispatch ${cap(budget.maxDispatches)}, research ${cap(budget.maxResearch)}, task wall ${capMin(taskBudget.wallMs)}.`;
8964
+
8965
+ const stableModeSection = fleetActive ? `## Task triage (before dispatch)
8966
+ 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.` : "";
8967
+
8968
+ const fullVerificationContract = `## Verification Contract
8969
+ 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.`;
8970
+
8971
+ const verificationSection = !verificationActive ? "" : fullVerificationContract;
8505
8972
 
8506
8973
  // Peer section only when coms initialised. Decision G4: the coms_* tools are
8507
8974
  // already in the active tool surface when ready; here we just teach the
8508
8975
  // dispatcher how and when to reach for them.
8509
- const comsSection = comsReady && identity
8976
+ const comsSection = peerActive && comsReady && identity
8510
8977
  ? `
8511
8978
  ## 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.
8979
+ 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
8980
  `
8533
8981
  : "";
8534
8982
 
8535
8983
  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;
8984
+ const herdrSection = workspaceActive && herdrFleetReady ? HUB_HERDR_SECTION : "";
8985
+ const compactionSection = compactionActive ? `
8986
+ ## Context recovery
8987
+ - 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.
8988
+ - \`request_compaction\` is available for explicit recovery. Automatic recovery preserves task state and continues from the compaction summary.
8989
+ ` : "";
8990
+ const systemPrompt = assembleHubSystemPrompt({
8991
+ intro: postureText.intro,
8992
+ toolList,
8993
+ languageLines,
8994
+ activeTeamName,
8995
+ teamMembers,
8996
+ dispatchSection,
8997
+ userLanguage,
8998
+ askUserBlock,
8999
+ modeSection: stableModeSection,
9000
+ verificationSection,
9001
+ stateCapsule,
9002
+ comsSection,
9003
+ herdrSection,
9004
+ compactionSection,
9005
+ hardRules: postureText.hardRules,
9006
+ ambiguityRule,
9007
+ agentCatalog,
9008
+ researchCatalog,
9009
+ dispatcherPersonaPrompt: dispatcherPersona?.systemPrompt,
9010
+ });
9011
+ // Ledger is metadata-only and never written back into the replacement prompt.
9012
+ lastHubLedger = recordHubLedger(systemPrompt, namedHubLedgerParts({
9013
+ intro: postureText.intro,
9014
+ languageLines,
9015
+ teamMembers,
9016
+ agentCards,
9017
+ dispatchSection,
9018
+ modeSection: stableModeSection,
9019
+ verificationSection,
9020
+ stateCapsule,
9021
+ researchCards,
9022
+ researchCatalog,
9023
+ comsSection,
9024
+ herdrSection,
9025
+ compactionSection,
9026
+ dispatcherPersonaPrompt: dispatcherPersona?.systemPrompt,
9027
+ })).concat(CAPABILITY_PACKS.map(pack => {
9028
+ const status = capabilityResolution.active.includes(pack) ? "active"
9029
+ : capabilityResolution.provisional.includes(pack) ? "provisional"
9030
+ : (pack === "peer" && comsReady) || (pack === "workspace" && herdrFleetReady) ? "ready-inactive"
9031
+ : pack === "peer" || pack === "workspace" ? "unavailable" : "inactive";
9032
+ return component({
9033
+ id: `hub/capability/${pack}`, plane: "hub", category: "system", label: `Capability ${pack}: ${status}`,
9034
+ source: capabilityResolution.reasons[pack], persistence: "turn", visibility: "ui-only", confidence: "exact-chars", chars: 0,
9035
+ });
9036
+ }));
8624
9037
 
8625
9038
  return { systemPrompt };
9039
+ }
9040
+
9041
+ pi.on("before_agent_start", async (_event, _ctx) => buildHubSystemPrompt(true));
9042
+
9043
+ 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.";
9044
+ type DeferredRecoveryInput = { text: string; images?: ImageContent[]; streamingBehavior?: "steer" | "followUp" };
9045
+ let automaticCompactionPending = false;
9046
+ let automaticCompactionRunning = false;
9047
+ let deferredReplayAllowance = 0;
9048
+ const deferredRecoveryInputs: DeferredRecoveryInput[] = [];
9049
+
9050
+ function recordContextPressure(source: "message_end" | "turn_end" | "context" | "input" | "agent_settled" | "session_start" | "session_compact" | "compaction_callback", action: string, reason: string): void {
9051
+ const diagnostic = contextPressureDiagnostic(contextPressureState);
9052
+ try {
9053
+ pi.appendEntry("agent-hub-context-pressure", {
9054
+ version: 1,
9055
+ source,
9056
+ phase: diagnostic.phase,
9057
+ pressure: diagnostic.pressure,
9058
+ episode: diagnostic.episode,
9059
+ tokens: diagnostic.tokens,
9060
+ context_window: diagnostic.contextWindow,
9061
+ percent: diagnostic.percent,
9062
+ warning_percent: diagnostic.warningPercent,
9063
+ automatic_percent: diagnostic.automaticPercent,
9064
+ last_recovery_outcome: diagnostic.lastRecoveryOutcome,
9065
+ action,
9066
+ reason,
9067
+ });
9068
+ } catch { /* diagnostics are best-effort */ }
9069
+ }
9070
+
9071
+ function updateContextPressureStatus(ctx: ExtensionContext): void {
9072
+ const diagnostic = contextPressureDiagnostic(contextPressureState);
9073
+ const percent = diagnostic.percent === null ? "unknown" : `${diagnostic.percent.toFixed(1)}%`;
9074
+ ctx.ui.setStatus("context-pressure", `Context: ${contextPressureState.phase} · ${percent} · auto ${diagnostic.automaticPercent}% · last ${diagnostic.lastRecoveryOutcome}`);
9075
+ }
9076
+
9077
+ function observeContextPressure(ctx: ExtensionContext, source: "message_end" | "turn_end" | "input" | "session_start", additionalTokens = 0): "none" | "expose-compaction" | "compact-now" {
9078
+ const usage = ctx.getContextUsage();
9079
+ const contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? null;
9080
+ const tokens = usage?.tokens == null ? null : usage.tokens + Math.max(0, additionalTokens);
9081
+ const percent = tokens != null && contextWindow != null && contextWindow > 0
9082
+ ? tokens / contextWindow * 100
9083
+ : usage?.percent ?? null;
9084
+ const decision = transitionContextPressure(contextPressureState, {
9085
+ type: "usage",
9086
+ usage: { tokens, contextWindow, percent },
9087
+ });
9088
+ const previousPhase = contextPressureState.phase;
9089
+ contextPressureState = decision.state;
9090
+ updateContextPressureStatus(ctx);
9091
+ resolveIncomingCapabilities("");
9092
+ applyPostureTools();
9093
+ if (decision.action !== "none" || previousPhase !== decision.state.phase) {
9094
+ recordContextPressure(source, decision.action, decision.reason);
9095
+ }
9096
+ if (decision.action === "compact-now") {
9097
+ automaticCompactionPending = true;
9098
+ if (ctx.hasUI) ctx.ui.notify("Context reached 90%; pausing the tool loop for automatic compaction.", "warning");
9099
+ }
9100
+ return decision.action;
9101
+ }
9102
+
9103
+ function markContextCompactionSucceeded(): void {
9104
+ automaticCompactionPending = false;
9105
+ if (contextPressureState.phase === "recovered") return;
9106
+ const decision = transitionContextPressure(contextPressureState, { type: "compaction-succeeded" });
9107
+ contextPressureState = decision.state;
9108
+ if (currentCtx) updateContextPressureStatus(currentCtx);
9109
+ resolveIncomingCapabilities("");
9110
+ applyPostureTools();
9111
+ recordContextPressure("session_compact", decision.action, decision.reason);
9112
+ }
9113
+
9114
+ function replayDeferredRecoveryInputs(): void {
9115
+ if (automaticCompactionPending || automaticCompactionRunning || deferredRecoveryInputs.length === 0) return;
9116
+ const queued = deferredRecoveryInputs.splice(0);
9117
+ deferredReplayAllowance += queued.length;
9118
+ for (let index = 0; index < queued.length; index++) {
9119
+ const input = queued[index];
9120
+ const content = input.images?.length
9121
+ ? [{ type: "text" as const, text: input.text }, ...input.images]
9122
+ : input.text;
9123
+ pi.sendUserMessage(content, {
9124
+ deliverAs: index === 0 ? input.streamingBehavior : "followUp",
9125
+ });
9126
+ }
9127
+ }
9128
+
9129
+ function runAutomaticCompaction(ctx: ExtensionContext, source: "input" | "agent_settled" | "session_start"): void {
9130
+ if (!automaticCompactionPending || automaticCompactionRunning) return;
9131
+ automaticCompactionPending = false;
9132
+ automaticCompactionRunning = true;
9133
+ recordContextPressure(source, "compact-now", "automatic-threshold");
9134
+ if (ctx.hasUI) ctx.ui.notify("Automatic context compaction started.", "warning");
9135
+ ctx.compact({
9136
+ customInstructions: AUTOMATIC_COMPACTION_INSTRUCTIONS,
9137
+ onComplete: () => {
9138
+ automaticCompactionRunning = false;
9139
+ markContextCompactionSucceeded();
9140
+ if (ctx.hasUI) ctx.ui.notify("Automatic context compaction completed.", "success");
9141
+ replayDeferredRecoveryInputs();
9142
+ },
9143
+ onError: (error) => {
9144
+ automaticCompactionRunning = false;
9145
+ const failed = transitionContextPressure(contextPressureState, { type: "compaction-failed", error: "automatic compaction failed" });
9146
+ contextPressureState = failed.state;
9147
+ updateContextPressureStatus(ctx);
9148
+ resolveIncomingCapabilities("");
9149
+ applyPostureTools();
9150
+ recordContextPressure("compaction_callback", failed.action, failed.reason);
9151
+ 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");
9152
+ },
9153
+ });
9154
+ }
9155
+
9156
+ // A finalized tool result is already present in Agent state when message_end
9157
+ // fires, so live usage includes its size. Abort synchronously here: compacting
9158
+ // directly from turn_end races the next provider request in Pi 0.84.x.
9159
+ pi.on("message_end", async (event, ctx) => {
9160
+ if (event.message.role !== "toolResult") return;
9161
+ // Pi persists the tool result after this hook, so project its model-visible
9162
+ // content onto the last trusted usage sample. JSON includes text and image
9163
+ // payload sizes while excluding non-contextual tool details.
9164
+ const projectedResultTokens = estimatePromptTokens(JSON.stringify(event.message.content ?? []));
9165
+ if (observeContextPressure(ctx, "message_end", projectedResultTokens) === "compact-now") ctx.abort();
9166
+ });
9167
+
9168
+ pi.on("turn_end", async (_event, ctx) => {
9169
+ observeContextPressure(ctx, "turn_end");
9170
+ });
9171
+
9172
+ // Abort again at Pi's pre-model context boundary. The message_end abort can
9173
+ // race agent-core's tool-loop continuation; this signal belongs to the next
9174
+ // request and prevents a network call while recovery is pending.
9175
+ pi.on("context", async (_event, ctx) => {
9176
+ if (!automaticCompactionPending) return;
9177
+ recordContextPressure("context", "compact-now", "single-flight");
9178
+ ctx.abort();
9179
+ });
9180
+
9181
+ // Wait until abort persistence and agent cleanup finish before compaction. This
9182
+ // gives prepareCompaction the finalized tool result and prevents a continuation
9183
+ // request from winning the race.
9184
+ pi.on("agent_settled", async (_event, ctx) => {
9185
+ runAutomaticCompaction(ctx, "agent_settled");
9186
+ });
9187
+
9188
+ pi.on("session_compact", async () => {
9189
+ markContextCompactionSucceeded();
9190
+ if (!automaticCompactionRunning) setTimeout(replayDeferredRecoveryInputs, 0);
8626
9191
  });
8627
9192
 
8628
9193
  // ── Persona gate: block input until a dispatcher persona is picked ──
8629
- pi.on("input", async (_event, ctx) => {
9194
+ function incomingText(event: unknown): string {
9195
+ const value = event as { text?: unknown; message?: unknown; input?: unknown } | null;
9196
+ if (typeof value?.text === "string") return value.text;
9197
+ if (typeof value?.message === "string") return value.message;
9198
+ if (typeof value?.input === "string") return value.input;
9199
+ const message = value?.message as { content?: unknown } | undefined;
9200
+ return typeof message?.content === "string" ? message.content : "";
9201
+ }
9202
+
9203
+ pi.on("input", async (event, ctx) => {
9204
+ const replayingDeferredRecoveryInput = event.source === "extension" && deferredReplayAllowance > 0;
9205
+ if (replayingDeferredRecoveryInput) {
9206
+ deferredReplayAllowance--;
9207
+ } else {
9208
+ // Session usage can already be over threshold before the first model turn
9209
+ // (resume/startup). Sample it here as a final preflight, retain the exact
9210
+ // input in memory, and replay only after compaction has completed.
9211
+ if (contextPressureState.phase === "normal") observeContextPressure(ctx, "input");
9212
+ if (automaticCompactionPending || automaticCompactionRunning || contextPressureState.phase === "failed") {
9213
+ deferredRecoveryInputs.push({
9214
+ text: event.text,
9215
+ images: event.images ? [...event.images] : undefined,
9216
+ streamingBehavior: event.streamingBehavior,
9217
+ });
9218
+ if (automaticCompactionPending && ctx.isIdle()) setTimeout(() => runAutomaticCompaction(ctx, "input"), 0);
9219
+ ctx.ui.notify(
9220
+ contextPressureState.phase === "failed"
9221
+ ? "Context recovery failed; input is retained. Run /compact or switch to a larger-context model."
9222
+ : "Input retained until automatic context recovery completes.",
9223
+ "warning",
9224
+ );
9225
+ return { action: "handled" as const };
9226
+ }
9227
+ }
9228
+ if (replayingDeferredRecoveryInput && modelWorkBlockedByRosterRecovery(ctx)) {
9229
+ // Compaction succeeded, but this resumed orchestrator still needs an
9230
+ // explicit roster decision. Retain the exact replay payload again and
9231
+ // resume it only after the live recovery command clears the gate.
9232
+ deferredRecoveryInputs.push({
9233
+ text: event.text,
9234
+ images: event.images ? [...event.images] : undefined,
9235
+ streamingBehavior: event.streamingBehavior,
9236
+ });
9237
+ return { action: "handled" as const };
9238
+ }
9239
+ if (modelWorkBlockedByRosterRecovery(ctx)) return { action: "handled" as const };
9240
+ // Pi routes normal, resumed, and remote prompts through this hook before
9241
+ // before_agent_start, so this local resolver changes the same request's surface.
9242
+ resolveIncomingCapabilities(incomingText(event));
9243
+ applyPostureTools();
8630
9244
  if (posture === "orchestrator" && personaGateEnabled && !personaGateSatisfied) {
8631
9245
  ctx.ui.notify("Pick a dispatcher persona first (see the select dialog).", "warning");
8632
9246
  return { action: "handled" as const };
@@ -8638,6 +9252,14 @@ ${researchCatalog}`;
8638
9252
 
8639
9253
  pi.on("session_start", async (_event, _ctx) => {
8640
9254
  registerVersionStatus(_ctx);
9255
+ contextPressureState = createContextPressureState();
9256
+ updateContextPressureStatus(_ctx);
9257
+ automaticCompactionPending = false;
9258
+ automaticCompactionRunning = false;
9259
+ deferredReplayAllowance = 0;
9260
+ deferredRecoveryInputs.length = 0;
9261
+ rosterRecoveryRequired = false;
9262
+ rosterRecoveryDiagnostic = "";
8641
9263
  // Capture the configured surface before Agent Hub applies either posture.
8642
9264
  // Operator mode restores this baseline (minus gated Hub-owned tools).
8643
9265
  baselineTools = pi.getActiveTools();
@@ -8656,6 +9278,11 @@ ${researchCatalog}`;
8656
9278
  taskClock = createTaskClock();
8657
9279
  askUserStarts.clear();
8658
9280
  turnAskUserIntervals.length = 0;
9281
+ turnBudgetAskUserWaitMs = 0;
9282
+ turnContinuationCount = 0;
9283
+ taskContinuationCount = 0;
9284
+ pendingBudgetContinuation = null;
9285
+ budgetContinuationAsks.clear();
8659
9286
  if (widgetCtx) {
8660
9287
  widgetCtx.ui.setWidget("agent-team", undefined);
8661
9288
  widgetCtx.ui.setWidget("agent-research", undefined);
@@ -8946,8 +9573,6 @@ ${researchCatalog}`;
8946
9573
  userLanguage = overrides.language;
8947
9574
  researchKeep = overrides.researchKeep;
8948
9575
  reconSearchTimeoutMs = overrides.reconSearchTimeoutMs;
8949
- const previousMode = hubMode;
8950
- hubMode = overrides.hubMode;
8951
9576
  budgetOverrides = overrides.budgetOverrides;
8952
9577
  watchdogSetting = overrides.watchdogSetting;
8953
9578
  watchdogJudgeModel = overrides.watchdogJudgeModel;
@@ -8956,13 +9581,6 @@ ${researchCatalog}`;
8956
9581
  // A new session is a new task by definition.
8957
9582
  resetTaskWindow(null);
8958
9583
  updateModeStatus();
8959
- appendHubModeEntry({
8960
- previousMode,
8961
- mode: hubMode,
8962
- source: overrides.hubModeSource,
8963
- overrideFile: overrides.hubModeSource === "project-override" ? ".ai/agent-fleet-overrides.md" : null,
8964
- ctx: _ctx,
8965
- });
8966
9584
  if (overrides.warnings.length > 0) {
8967
9585
  _ctx.ui.notify(`agent-fleet-overrides warnings:\n${overrides.warnings.join("\n")}`, "warning");
8968
9586
  }
@@ -8986,6 +9604,7 @@ ${researchCatalog}`;
8986
9604
  // Model switching state resets each session; per-project overrides replace
8987
9605
  // the persona defs' default model / candidate list before anything reads them.
8988
9606
  modelOverrides.clear();
9607
+ modelSubstitutions.clear();
8989
9608
  subagentModelOverrides.clear();
8990
9609
  thinkingOverrides.clear();
8991
9610
  for (const def of allAgentDefs) {
@@ -9054,22 +9673,49 @@ ${researchCatalog}`;
9054
9673
  personaGateEnabled = overrides.personaGate && orchestratorPersonas.length > 0;
9055
9674
  personaGateSatisfied = !personaGateEnabled;
9056
9675
 
9057
- // A roster is opt-in. Resolve it before posture so --agent-team can imply
9058
- // orchestrator while an explicit --posture operator still wins.
9676
+ // Explicit CLI selection wins; otherwise restore only the canonical team name
9677
+ // and re-resolve it against current teams.yaml/persona files. An explicit
9678
+ // operator posture suppresses an ambient persisted roster unless --agent-team
9679
+ // was also supplied.
9059
9680
  agentStates.clear();
9060
9681
  activeTeamName = "";
9061
9682
  comsMissNotified.clear();
9062
9683
  recomputeGrid();
9063
- const startupRoster = resolveStartupRoster(teams, pi.getFlag("agent-team"));
9684
+ const sessionEntries = _ctx.sessionManager.getEntries();
9685
+ const explicitPosture = pi.getFlag("posture");
9686
+ const explicitRoster = pi.getFlag("agent-team");
9687
+ const hasExplicitRoster = typeof explicitRoster === "string" && explicitRoster.trim() !== "";
9688
+ const startupRoster = resolveSessionRoster({
9689
+ teams,
9690
+ entries: sessionEntries,
9691
+ explicitRoster,
9692
+ availablePersonas: allAgentDefs.map(def => def.name),
9693
+ includePersisted: !(explicitPosture === "operator" && !hasExplicitRoster),
9694
+ });
9064
9695
  posture = resolveSessionPosture({
9065
- entries: _ctx.sessionManager.getEntries(),
9066
- explicitPosture: pi.getFlag("posture"),
9067
- hasExplicitRoster: startupRoster !== null,
9696
+ entries: sessionEntries,
9697
+ explicitPosture,
9698
+ hasExplicitRoster: startupRoster.source === "explicit",
9068
9699
  });
9069
- if (orchestratorNeedsRoster(posture, startupRoster?.members.length ?? 0)) {
9070
- throw new Error("Orchestrator posture requires --agent-team <name> with at least one native specialist.");
9700
+ if (startupRoster.roster) {
9701
+ activateTeam(startupRoster.roster.name);
9702
+ persistActiveRoster();
9703
+ }
9704
+ rosterRecoveryRequired = orchestratorNeedsRoster(posture, agentStates.size);
9705
+ rosterRecoveryDiagnostic = rosterRecoveryRequired
9706
+ ? startupRoster.diagnostic || "Persisted orchestrator posture has no native roster."
9707
+ : "";
9708
+ if (startupRoster.diagnostic) {
9709
+ _ctx.ui.notify(
9710
+ `${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."}`,
9711
+ rosterRecoveryRequired ? "error" : "warning",
9712
+ );
9713
+ } else if (rosterRecoveryRequired) {
9714
+ _ctx.ui.notify(
9715
+ `${rosterRecoveryDiagnostic} Model input is blocked until you select /af-agents-team, restart with --agent-team <name>, or switch explicitly with --posture operator.`,
9716
+ "error",
9717
+ );
9071
9718
  }
9072
- if (startupRoster) activateTeam(startupRoster.name);
9073
9719
 
9074
9720
  // Probe for `ask_user` (registered by the `pi-ask-user` companion package
9075
9721
  // when installed). Action methods like getAllTools are runtime-only, so
@@ -9079,7 +9725,15 @@ ${researchCatalog}`;
9079
9725
  // Fleet tools are available only inside a herdr pane with a live server.
9080
9726
  // The posture policy adds gated groups without activating unavailable tools.
9081
9727
  herdrFleetReady = herdrPaneId() !== null && (await herdrAvailable()) !== null;
9728
+ const persistedCapabilities = latestPersistedCapabilityState(_ctx.sessionManager.getEntries());
9729
+ taskCapabilityPacks = persistedCapabilities?.taskPacks ?? [];
9730
+ taskProvisionalPacks = persistedCapabilities?.provisional ?? [];
9731
+ capabilityConfirmation = persistedCapabilities?.confirmation ?? {};
9732
+ resolveIncomingCapabilities("");
9082
9733
  applyPostureTools();
9734
+ if (observeContextPressure(_ctx, "session_start") === "compact-now") {
9735
+ setTimeout(() => runAutomaticCompaction(_ctx, "session_start"), 0);
9736
+ }
9083
9737
  updatePostureStatus(_ctx);
9084
9738
 
9085
9739
  _ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"} (${agentStates.size})`);
@@ -9118,14 +9772,16 @@ ${researchCatalog}`;
9118
9772
  `Persona gate: ${personaGateLabel}\n` +
9119
9773
  `Coms: ${comsLabel}\n` +
9120
9774
  `Fleet: ${fleetLabel}\n\n` +
9121
- `/af-posture [mode] Show/switch operator|orchestrator posture\n` +
9775
+ `/af-work-mode [posture] Operator | Orchestrator (Alt+M)\n` +
9776
+ `/af-posture [posture] Show/switch operator|orchestrator posture\n` +
9122
9777
  `/af-agents-team Select a team\n` +
9123
9778
  `/af-agents-list Open Fleet Dashboard\n` +
9124
9779
  `/af-agents-history Timeline of agent runs — durations, parallel markers, grand total\n` +
9780
+ `/af-context Read-only full-screen context budget diagnostic\n` +
9125
9781
  `/af-agent-model <persona>[.<role>] Switch a persona's or sub-role's model\n` +
9126
9782
  `/af-agent-model-thinking <persona> Switch a persona's thinking level\n` +
9127
9783
  `/af-models [profile] Apply a named model profile to the team\n` +
9128
- `/af-agent-models-substitute <src> <tgt> Swap one model across all personas\n` +
9784
+ `/af-agent-models-substitute [src tgt] Pick/save a session-wide source → target model substitution\n` +
9129
9785
  `/af-dispatch-policy Show which members route to coms peers (dispatch-policy.yaml)\n` +
9130
9786
  `/af-agents-kill <name> SIGTERM a frozen specialist (and its delegate children)\n` +
9131
9787
  `/af-agents-restart <name> Kill + re-run its last task fresh\n` +
@@ -9145,7 +9801,7 @@ ${researchCatalog}`;
9145
9801
 
9146
9802
  // The persona gate restricts only orchestrator posture. Operators can work
9147
9803
  // directly and choose a dispatcher persona later without being blocked.
9148
- if (posture === "orchestrator" && personaGateEnabled) {
9804
+ if (posture === "orchestrator" && personaGateEnabled && !rosterRecoveryRequired) {
9149
9805
  void pickDispatcherPersona(_ctx);
9150
9806
  }
9151
9807
 
@@ -9166,7 +9822,7 @@ ${researchCatalog}`;
9166
9822
  const bar = "#".repeat(filled) + "-".repeat(10 - filled);
9167
9823
 
9168
9824
  const left = renderHubFooterLeft(theme, HARNESS_VERSION, model, think, activeTeamName);
9169
- const hint = theme.fg("dim", composeFleetFooterHint(viewMode));
9825
+ const hint = theme.fg("dim", composeFleetFooterHint(viewMode, compactPosture(posture)));
9170
9826
  // The btw extension flips this global the first time a /af-btw command or
9171
9827
  // Alt+' is used; surface its reopen shortcut right next to the Alt+A hint.
9172
9828
  const btwHint = (globalThis as { __btwActivated?: boolean }).__btwActivated