@bonesofspring/ai-rules 0.2.71 → 0.2.72

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 (248) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/bin/lib/engine-scripts.js +9 -0
  3. package/docs/OPENCODE.md +4 -2
  4. package/docs/TEAM-DB.md +10 -7
  5. package/package.json +1 -1
  6. package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +201 -0
  7. package/presets/_shared/ai-local/scripts/incidents.mjs +452 -0
  8. package/presets/_shared/ai-local/scripts/record-usage.mjs +163 -0
  9. package/presets/_shared/ai-local/scripts/team-db-project.mjs +2 -0
  10. package/presets/_shared/ai-local/scripts/verification.mjs +374 -0
  11. package/presets/_shared/core/agent-team/agent-task-metrics.md +61 -1
  12. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +5 -4
  13. package/presets/_shared/core/agent-team/incident-registry.md +47 -0
  14. package/presets/_shared/core/architecture/feature-delivery-workflow.md +1 -1
  15. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +108 -1
  16. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +108 -1
  17. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  18. package/presets/claude/go/hooks/chain-team-phases.sh +108 -1
  19. package/presets/claude/go/rules/architecture/feature-delivery.md +1 -1
  20. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  21. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +108 -1
  22. package/presets/claude/ios-swift/rules/architecture/feature-delivery.md +1 -1
  23. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  24. package/presets/claude/java/hooks/chain-team-phases.sh +108 -1
  25. package/presets/claude/java/rules/architecture/feature-delivery.md +1 -1
  26. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  27. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +108 -1
  28. package/presets/claude/mcp-ts/rules/architecture/feature-delivery.md +1 -1
  29. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  30. package/presets/claude/mol/hooks/chain-team-phases.sh +108 -1
  31. package/presets/claude/mol/rules/architecture/feature-delivery-workflow.md +1 -1
  32. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  33. package/presets/claude/next/agents/README.md +4 -3
  34. package/presets/claude/next/agents/api-contract-reviewer.md +1 -1
  35. package/presets/claude/next/agents/mockup-reviewer.md +1 -1
  36. package/presets/claude/next/agents/task-router.md +4 -4
  37. package/presets/claude/next/hooks/chain-team-phases.sh +108 -1
  38. package/presets/claude/next/rules/architecture/feature-delivery-workflow.md +2 -2
  39. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  40. package/presets/claude/nuxt/hooks/chain-team-phases.sh +108 -1
  41. package/presets/claude/nuxt/rules/architecture/feature-delivery-workflow.md +1 -1
  42. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  43. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  44. package/presets/claude/php-hexagonal/rules/architecture/feature-delivery.md +1 -1
  45. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  46. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +108 -1
  47. package/presets/claude/php-laravel/rules/architecture/feature-delivery.md +1 -1
  48. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  49. package/presets/claude/svelte/hooks/chain-team-phases.sh +108 -1
  50. package/presets/claude/svelte/rules/architecture/feature-delivery-workflow.md +1 -1
  51. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  52. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +108 -1
  53. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +1 -1
  54. package/presets/cursor/go/hooks/chain-team-phases.sh +108 -1
  55. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +1 -1
  56. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +108 -1
  57. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +1 -1
  58. package/presets/cursor/java/hooks/chain-team-phases.sh +108 -1
  59. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +1 -1
  60. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +108 -1
  61. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +1 -1
  62. package/presets/cursor/mol/hooks/chain-team-phases.sh +108 -1
  63. package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +1 -1
  64. package/presets/cursor/next/agents/README.md +4 -3
  65. package/presets/cursor/next/agents/api-contract-reviewer.md +1 -1
  66. package/presets/cursor/next/agents/mockup-reviewer.md +1 -1
  67. package/presets/cursor/next/agents/task-router.md +4 -4
  68. package/presets/cursor/next/hooks/chain-team-phases.sh +108 -1
  69. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +1 -1
  70. package/presets/cursor/next/rules/feature-delivery-workflow.mdc +1 -1
  71. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +108 -1
  72. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  73. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  74. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +1 -1
  75. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +108 -1
  76. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +1 -1
  77. package/presets/cursor/svelte/hooks/chain-team-phases.sh +108 -1
  78. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  79. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  80. package/presets/mavis/android-kotlin/agents/README.md +3 -3
  81. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +108 -1
  82. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +5 -4
  83. package/presets/mavis/go/adapter-map.json +1 -1
  84. package/presets/mavis/go/agents/README.md +2 -2
  85. package/presets/mavis/go/hooks/chain-team-phases.sh +108 -1
  86. package/presets/mavis/go/rules/agent-team-orchestrator.md +5 -4
  87. package/presets/mavis/go/rules/feature-delivery-workflow.md +1 -1
  88. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  89. package/presets/mavis/ios-swift/agents/README.md +3 -3
  90. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +108 -1
  91. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +5 -4
  92. package/presets/mavis/ios-swift/rules/feature-delivery-workflow.md +1 -1
  93. package/presets/mavis/java/adapter-map.json +1 -1
  94. package/presets/mavis/java/agents/README.md +2 -2
  95. package/presets/mavis/java/hooks/chain-team-phases.sh +108 -1
  96. package/presets/mavis/java/rules/agent-team-orchestrator.md +5 -4
  97. package/presets/mavis/java/rules/feature-delivery-workflow.md +1 -1
  98. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  99. package/presets/mavis/mcp-ts/agents/README.md +1 -1
  100. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +108 -1
  101. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +5 -4
  102. package/presets/mavis/mcp-ts/rules/feature-delivery-workflow.md +1 -1
  103. package/presets/mavis/mol/adapter-map.json +1 -1
  104. package/presets/mavis/mol/agents/README.md +3 -3
  105. package/presets/mavis/mol/hooks/chain-team-phases.sh +108 -1
  106. package/presets/mavis/mol/rules/agent-team-orchestrator.md +5 -4
  107. package/presets/mavis/mol/rules/feature-delivery-workflow.md +1 -1
  108. package/presets/mavis/next/adapter-map.json +1 -1
  109. package/presets/mavis/next/agents/README.md +3 -3
  110. package/presets/mavis/next/agents/task-router.md +4 -4
  111. package/presets/mavis/next/hooks/chain-team-phases.sh +108 -1
  112. package/presets/mavis/next/rules/agent-team-orchestrator.md +5 -4
  113. package/presets/mavis/next/rules/feature-delivery-workflow.md +2 -2
  114. package/presets/mavis/nuxt/adapter-map.json +1 -1
  115. package/presets/mavis/nuxt/agents/README.md +3 -3
  116. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +108 -1
  117. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +5 -4
  118. package/presets/mavis/nuxt/rules/feature-delivery-workflow.md +1 -1
  119. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  120. package/presets/mavis/php-hexagonal/agents/README.md +2 -2
  121. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  122. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
  123. package/presets/mavis/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
  124. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  125. package/presets/mavis/php-laravel/agents/README.md +2 -2
  126. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +108 -1
  127. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +5 -4
  128. package/presets/mavis/php-laravel/rules/feature-delivery-workflow.md +1 -1
  129. package/presets/mavis/svelte/adapter-map.json +1 -1
  130. package/presets/mavis/svelte/agents/README.md +3 -3
  131. package/presets/mavis/svelte/hooks/chain-team-phases.sh +108 -1
  132. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +5 -4
  133. package/presets/mavis/svelte/rules/feature-delivery-workflow.md +1 -1
  134. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  135. package/presets/opencode/android-kotlin/agents/README.md +4 -4
  136. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +108 -1
  137. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +5 -4
  138. package/presets/opencode/go/adapter-map.json +1 -1
  139. package/presets/opencode/go/agents/README.md +3 -3
  140. package/presets/opencode/go/hooks/chain-team-phases.sh +108 -1
  141. package/presets/opencode/go/rules/agent-team-orchestrator.md +5 -4
  142. package/presets/opencode/go/rules/feature-delivery-workflow.md +1 -1
  143. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  144. package/presets/opencode/ios-swift/agents/README.md +4 -4
  145. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +108 -1
  146. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +5 -4
  147. package/presets/opencode/ios-swift/rules/feature-delivery-workflow.md +1 -1
  148. package/presets/opencode/java/adapter-map.json +1 -1
  149. package/presets/opencode/java/agents/README.md +3 -3
  150. package/presets/opencode/java/hooks/chain-team-phases.sh +108 -1
  151. package/presets/opencode/java/rules/agent-team-orchestrator.md +5 -4
  152. package/presets/opencode/java/rules/feature-delivery-workflow.md +1 -1
  153. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  154. package/presets/opencode/mcp-ts/agents/README.md +2 -2
  155. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +108 -1
  156. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +5 -4
  157. package/presets/opencode/mcp-ts/rules/feature-delivery-workflow.md +1 -1
  158. package/presets/opencode/mol/adapter-map.json +1 -1
  159. package/presets/opencode/mol/agents/README.md +4 -4
  160. package/presets/opencode/mol/hooks/chain-team-phases.sh +108 -1
  161. package/presets/opencode/mol/rules/agent-team-orchestrator.md +5 -4
  162. package/presets/opencode/mol/rules/feature-delivery-workflow.md +1 -1
  163. package/presets/opencode/next/adapter-map.json +1 -1
  164. package/presets/opencode/next/agents/README.md +4 -4
  165. package/presets/opencode/next/agents/task-router.md +4 -4
  166. package/presets/opencode/next/hooks/chain-team-phases.sh +108 -1
  167. package/presets/opencode/next/rules/agent-team-orchestrator.md +5 -4
  168. package/presets/opencode/next/rules/feature-delivery-workflow.md +2 -2
  169. package/presets/opencode/nuxt/adapter-map.json +1 -1
  170. package/presets/opencode/nuxt/agents/README.md +4 -4
  171. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +108 -1
  172. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +5 -4
  173. package/presets/opencode/nuxt/rules/feature-delivery-workflow.md +1 -1
  174. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  175. package/presets/opencode/php-hexagonal/agents/README.md +3 -3
  176. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  177. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
  178. package/presets/opencode/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
  179. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  180. package/presets/opencode/php-laravel/agents/README.md +3 -3
  181. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +108 -1
  182. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +5 -4
  183. package/presets/opencode/php-laravel/rules/feature-delivery-workflow.md +1 -1
  184. package/presets/opencode/plugins/output-guard/README.md +17 -4
  185. package/presets/opencode/plugins/output-guard/index.ts +27 -9
  186. package/presets/opencode/plugins/output-guard/rewrite.ts +104 -1
  187. package/presets/opencode/svelte/adapter-map.json +1 -1
  188. package/presets/opencode/svelte/agents/README.md +4 -4
  189. package/presets/opencode/svelte/hooks/chain-team-phases.sh +108 -1
  190. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +5 -4
  191. package/presets/opencode/svelte/rules/feature-delivery-workflow.md +1 -1
  192. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  193. package/presets/zcode/android-kotlin/agents/README.md +3 -3
  194. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +108 -1
  195. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +5 -4
  196. package/presets/zcode/go/adapter-map.json +1 -1
  197. package/presets/zcode/go/agents/README.md +2 -2
  198. package/presets/zcode/go/hooks/chain-team-phases.sh +108 -1
  199. package/presets/zcode/go/rules/agent-team-orchestrator.md +5 -4
  200. package/presets/zcode/go/rules/feature-delivery-workflow.md +1 -1
  201. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  202. package/presets/zcode/ios-swift/agents/README.md +3 -3
  203. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +108 -1
  204. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +5 -4
  205. package/presets/zcode/ios-swift/rules/feature-delivery-workflow.md +1 -1
  206. package/presets/zcode/java/adapter-map.json +1 -1
  207. package/presets/zcode/java/agents/README.md +2 -2
  208. package/presets/zcode/java/hooks/chain-team-phases.sh +108 -1
  209. package/presets/zcode/java/rules/agent-team-orchestrator.md +5 -4
  210. package/presets/zcode/java/rules/feature-delivery-workflow.md +1 -1
  211. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  212. package/presets/zcode/mcp-ts/agents/README.md +1 -1
  213. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +108 -1
  214. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +5 -4
  215. package/presets/zcode/mcp-ts/rules/feature-delivery-workflow.md +1 -1
  216. package/presets/zcode/mol/adapter-map.json +1 -1
  217. package/presets/zcode/mol/agents/README.md +3 -3
  218. package/presets/zcode/mol/hooks/chain-team-phases.sh +108 -1
  219. package/presets/zcode/mol/rules/agent-team-orchestrator.md +5 -4
  220. package/presets/zcode/mol/rules/feature-delivery-workflow.md +1 -1
  221. package/presets/zcode/next/adapter-map.json +1 -1
  222. package/presets/zcode/next/agents/README.md +3 -3
  223. package/presets/zcode/next/agents/task-router.md +4 -4
  224. package/presets/zcode/next/hooks/chain-team-phases.sh +108 -1
  225. package/presets/zcode/next/rules/agent-team-orchestrator.md +5 -4
  226. package/presets/zcode/next/rules/feature-delivery-workflow.md +2 -2
  227. package/presets/zcode/nuxt/adapter-map.json +1 -1
  228. package/presets/zcode/nuxt/agents/README.md +3 -3
  229. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +108 -1
  230. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +5 -4
  231. package/presets/zcode/nuxt/rules/feature-delivery-workflow.md +1 -1
  232. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  233. package/presets/zcode/php-hexagonal/agents/README.md +2 -2
  234. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  235. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
  236. package/presets/zcode/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
  237. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  238. package/presets/zcode/php-laravel/agents/README.md +2 -2
  239. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +108 -1
  240. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +5 -4
  241. package/presets/zcode/php-laravel/rules/feature-delivery-workflow.md +1 -1
  242. package/presets/zcode/svelte/adapter-map.json +1 -1
  243. package/presets/zcode/svelte/agents/README.md +3 -3
  244. package/presets/zcode/svelte/hooks/chain-team-phases.sh +108 -1
  245. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +5 -4
  246. package/presets/zcode/svelte/rules/feature-delivery-workflow.md +1 -1
  247. package/scripts/aggregate-agent-task-metrics.mjs +201 -0
  248. package/scripts/report-context-cost.mjs +126 -0
@@ -78,9 +78,9 @@ is advisory for the operator's ZCode session model — see `task-router.md`.
78
78
 
79
79
  | Tier | Agents |
80
80
  |------|--------|
81
- | **cheap** | `task-router`, `task-analyst`, `build-verifier`, `code-reviewer`, `tech-writer`, `codebase-analyzer` |
82
- | **standard** | `feature-developer`, `debugger`, `ci-investigator`, `api-contract-reviewer`, `accessibility-reviewer`, `qa-tester`, `unit-test-*`, `playwright-test-*`, `openspec-author` |
83
- | **strong** | `solution-architect`, `migration-specialist`, `security-reviewer`, `performance-auditor`, `mockup-reviewer` |
81
+ | **cheap** | `task-router`, `task-analyst`, `build-verifier`, `code-reviewer`, `api-contract-reviewer`, `mockup-reviewer`, `tech-writer`, `codebase-analyzer` |
82
+ | **standard** | `feature-developer`, `debugger`, `ci-investigator`, `accessibility-reviewer`, `qa-tester`, `unit-test-*`, `playwright-test-*`, `openspec-author` |
83
+ | **strong** | `solution-architect`, `migration-specialist`, `security-reviewer`, `performance-auditor` |
84
84
 
85
85
  ## Orchestration
86
86
 
@@ -980,11 +980,117 @@ function reconcileStatusFromManifest(agent, step, resolved) {
980
980
  return status.state;
981
981
  }
982
982
 
983
+ /**
984
+ * Keep only the numeric usage fields and the two provenance fields. A host may
985
+ * forward richer objects; the ledger is allowlisted so nothing unbounded or
986
+ * secret-shaped reaches `metrics.json`.
987
+ */
988
+ function sanitizeUsage(value) {
989
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
990
+ const num = (input) => (typeof input === 'number' && Number.isFinite(input) && input >= 0 ? input : null);
991
+ const usage = {
992
+ input: num(value.input), output: num(value.output), reasoning: num(value.reasoning),
993
+ cacheRead: num(value.cacheRead === undefined ? value.cached : value.cacheRead),
994
+ cacheWrite: num(value.cacheWrite), costUsd: num(value.costUsd),
995
+ model: typeof value.model === 'string' ? value.model.slice(0, 120) : null,
996
+ origin: value.origin === 'estimated' ? 'estimated' : 'measured',
997
+ };
998
+ const reported = usage.input !== null || usage.output !== null || usage.reasoning !== null ||
999
+ usage.cacheRead !== null || usage.cacheWrite !== null || usage.costUsd !== null;
1000
+ return reported ? usage : null;
1001
+ }
1002
+
1003
+ /**
1004
+ * Freshness of a persisted verification snapshot against the current worktree.
1005
+ * Read-only: closure warns, it never blocks on a stale snapshot.
1006
+ */
1007
+ function gitSnapshot() {
1008
+ const { spawnSync } = require('child_process');
1009
+ const git = (args) => {
1010
+ const result = spawnSync('git', args, { cwd: process.cwd(), encoding: 'utf8', timeout: 10000, maxBuffer: 32 * 1024 * 1024 });
1011
+ return result && result.status === 0 ? String(result.stdout || '') : null;
1012
+ };
1013
+ const head = git(['rev-parse', 'HEAD']);
1014
+ if (head === null) return null;
1015
+ const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']);
1016
+ const exclude = ['--', '.', ':(exclude).ai.local'];
1017
+ const statusText = git(['status', '--porcelain=v1', ...exclude]) || '';
1018
+ const diffText = git(['diff', '--binary', 'HEAD', ...exclude]) || '';
1019
+ const untracked = git(['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
1020
+ return {
1021
+ head: head.trim(),
1022
+ branch: branch === null ? null : branch.trim(),
1023
+ dirtyFiles: statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length,
1024
+ worktreeHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1025
+ capturedAt: now,
1026
+ };
1027
+ }
1028
+
1029
+ /**
1030
+ * Seed the evidence file when the verifier finishes without an explicit
1031
+ * `verification.mjs record`: the snapshot plus a hash of `validation-report.md`.
1032
+ * An existing file is never refreshed — its binding must keep pointing at the
1033
+ * tree the commands actually ran on.
1034
+ */
1035
+ function ensureVerificationSnapshot(dir, agent) {
1036
+ const file = path.join(dir, 'verification.json');
1037
+ if (fs.existsSync(file)) return;
1038
+ const snapshot = gitSnapshot();
1039
+ if (!snapshot) return;
1040
+ const reportPath = path.join(dir, 'validation-report.md');
1041
+ let report = null;
1042
+ try {
1043
+ const text = fs.readFileSync(reportPath);
1044
+ report = { path: 'validation-report.md', sha256: crypto.createHash('sha256').update(text).digest('hex') };
1045
+ } catch {}
1046
+ const verification = {
1047
+ schemaVersion: 1,
1048
+ task: path.basename(dir),
1049
+ snapshot,
1050
+ report,
1051
+ commands: [],
1052
+ gate: { status: 'snapshot-only', recordedBy: agent || null, checkedAt: now },
1053
+ };
1054
+ const temporary = `${file}.${process.pid}.tmp`;
1055
+ fs.writeFileSync(temporary, JSON.stringify(verification, null, 2) + '\n');
1056
+ fs.renameSync(temporary, file);
1057
+ appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, worktreeHash: snapshot.worktreeHash, source: 'hook', attributionConfidence: 'high' });
1058
+ }
1059
+
1060
+ function verificationFreshness(dir) {
1061
+ const file = path.join(dir, 'verification.json');
1062
+ if (!fs.existsSync(file)) return { present: false };
1063
+ let verification;
1064
+ try { verification = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { present: true, fresh: false, reasons: ['unreadable'] }; }
1065
+ const snapshot = verification && verification.snapshot;
1066
+ if (!snapshot || typeof snapshot.head !== 'string') return { present: true, fresh: false, reasons: ['no-snapshot'] };
1067
+ const current = gitSnapshot();
1068
+ if (!current) return { present: true, fresh: false, reasons: ['no-git'] };
1069
+ const reasons = [];
1070
+ if (current.head !== snapshot.head) reasons.push('head-changed');
1071
+ if (current.worktreeHash !== snapshot.worktreeHash) reasons.push('worktree-changed');
1072
+ return { present: true, fresh: reasons.length === 0, reasons };
1073
+ }
1074
+
1075
+ let verificationStaleNoted = false;
1076
+
1077
+ function noteVerificationFreshness(dir, agent) {
1078
+ if (verificationStaleNoted) return;
1079
+ const freshness = verificationFreshness(dir);
1080
+ if (!freshness.present) return;
1081
+ if (freshness.fresh) return;
1082
+ verificationStaleNoted = true;
1083
+ appendMetric({ type: 'verification_stale', at: now, agent: agent || null, reasons: freshness.reasons, source: 'hook', attributionConfidence: 'high' });
1084
+ process.stderr.write(`verification evidence is stale (${freshness.reasons.join(', ')}); re-run the gate and record it before closure\n`);
1085
+ }
1086
+
983
1087
  function finishActiveAttempt(forced) {
984
1088
  const resolved = forced || resolvedAttempt(); if (!resolved) return null;
985
1089
  const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
986
1090
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
987
- appendMetric({ type: 'attempt_finished', at: now, attemptId: resolved.attemptId, outcome, durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null, retryAfterFix: status.retryAfterFix || null, source: resolved.source || 'hook', attributionConfidence: resolved.confidence, ...(hookInput.usage && typeof hookInput.usage === 'object' ? { usage: hookInput.usage } : {}) });
1091
+ const usage = sanitizeUsage(hookInput.usage);
1092
+ appendMetric({ type: 'attempt_finished', at: now, attemptId: resolved.attemptId, outcome, durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null, retryAfterFix: status.retryAfterFix || null, source: resolved.source || 'hook', attributionConfidence: resolved.confidence, ...(usage ? { usage } : {}) });
1093
+ if (resolved.entry && resolved.entry.agent === 'build-verifier') { ensureVerificationSnapshot(taskDir, resolved.entry.agent); noteVerificationFreshness(taskDir, resolved.entry.agent); }
988
1094
  const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
989
1095
  }
990
1096
  function missingConsumerArtifacts() {
@@ -1014,6 +1120,7 @@ function completePipeline(statusPatch) {
1014
1120
  // task_completed is written only on this branch. A missing receipt blocks
1015
1121
  // above and must not be counted as a finished task.
1016
1122
  status.state = 'completed';
1123
+ noteVerificationFreshness(taskDir, null);
1017
1124
  completeTaskMetrics();
1018
1125
  writeStatus(statusPatch);
1019
1126
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
@@ -151,7 +151,7 @@ Replanning is a **named, auditable operation** — never a silent reorder. Trigg
151
151
 
152
152
  ## Context budget & checkpoint/resume
153
153
 
154
- Work in bounded waves (one artifact class across the target surface). **Checkpoint** each completed wave to `.memlog.md` (`## <date>` + an `event:` line) and record the produced paths on the `implementation` manifest entry (`authoritativePaths`). That checkpoint is the hook `writeStatus` path: it rewrites `.ai.local/team/tasks/<slug>/focus.md`. `focus.md` is a view, not the system of record. It lists slug, pipeline step index, authoritative paths for incomplete manifest ids, the last `.memlog.md` `event:` line, the next gate, one decomposition ready-set line, and one archive index line, and it stays under 100 lines. `status.json`, `metrics.json`, `artifact-manifest.json`, and `.memlog.md` stay the system of record. A resumed run (`/task-continue`) reads `focus.md` first, then `artifact-manifest.json` and `.memlog.md`, and continues at the first stage whose exit criteria are unmet — never re-derive state from the chat. A completed manifest entry keeps id, status, and `authoritativePaths`, and the default resume read omits that entry's markdown body; closing it appends one new `.memlog.md` event: line, moves the bulky body to `.ai.local/team/tasks/<slug>/archive/YYYY-MM-DD/`, and leaves earlier memlog lines, the human-readable slug and artifact ids, and the manifest entry in place, with no Beads hash ids and no Taskmaster tags. Mechanical waves (generation, embed sync) are delegated to repo scripts. A large command output (log, diff, test run, `git log`) is piped through `.ai.local/scripts/dump-output.mjs` instead of being read whole: take its ≤40-line head, then `grep -n` the stored file or find it with `team-db.mjs search "<term>"`. An **interrupted producer** (tool abort, killed session) is resumed, not restarted: run the stack's compile gate on the working tree first, and when it is red hand the failing output to the same producer with a `fix and finish` brief instead of starting a second parallel attempt. When the host runtime writes no `status.json` (manual-hook hosts such as OpenCode), the resume checkpoint is `artifact-manifest.json` + `.memlog.md`; never gate a resume on a file the runtime does not produce. See **context-and-iteration** for the budget, checkpoint, resume, and refinement loop.
154
+ Work in bounded waves (one artifact class across the target surface). **Checkpoint** each completed wave to `.memlog.md` (`## <date>` + an `event:` line) and record the produced paths on the `implementation` manifest entry (`authoritativePaths`). That checkpoint is the hook `writeStatus` path: it rewrites `.ai.local/team/tasks/<slug>/focus.md`. `focus.md` is a view, not the system of record. It lists slug, pipeline step index, authoritative paths for incomplete manifest ids, the last `.memlog.md` `event:` line, the next gate, one decomposition ready-set line, and one archive index line, and it stays under 100 lines. `status.json`, `metrics.json`, `artifact-manifest.json`, and `.memlog.md` stay the system of record. A resumed run (`/task-continue`) reads `focus.md` first, then `artifact-manifest.json` and `.memlog.md`, and continues at the first stage whose exit criteria are unmet — never re-derive state from the chat. A session approaching ~50 turns does not keep growing its history: the producer finishes the current wave, checkpoints it (`focus.md` + `artifact-manifest.json` + `.memlog.md`), and hands off to a fresh session. A wave that cannot finish before the cap checkpoints its partial state the same way. A completed manifest entry keeps id, status, and `authoritativePaths`, and the default resume read omits that entry's markdown body; closing it appends one new `.memlog.md` event: line, moves the bulky body to `.ai.local/team/tasks/<slug>/archive/YYYY-MM-DD/`, and leaves earlier memlog lines, the human-readable slug and artifact ids, and the manifest entry in place, with no Beads hash ids and no Taskmaster tags. Mechanical waves (generation, embed sync) are delegated to repo scripts. A large command output (log, diff, test run, `git log`) is piped through `.ai.local/scripts/dump-output.mjs` instead of being read whole: take its ≤40-line head, then `grep -n` the stored file or find it with `team-db.mjs search "<term>"`. An **interrupted producer** (tool abort, killed session) is resumed, not restarted: run the stack's compile gate on the working tree first, and when it is red hand the failing output to the same producer with a `fix and finish` brief instead of starting a second parallel attempt. When the host runtime writes no `status.json` (manual-hook hosts such as OpenCode), the resume checkpoint is `artifact-manifest.json` + `.memlog.md`; never gate a resume on a file the runtime does not produce. See **context-and-iteration** for the budget, checkpoint, resume, and refinement loop.
155
155
 
156
156
  ## Self-review & context hygiene
157
157
 
@@ -269,9 +269,10 @@ Use Task tool or `/agent-name`. Pass: slug, artifact paths, step `scope` if set.
269
269
 
270
270
  1. Read `steps[i].model` if present; else use the agent’s frontmatter `model` (see `agents/README.md` matrix).
271
271
  2. Resolve the tier through `.ai.local/team/model-tiers.json` → `tiers.<tier>` when that file exists. The user approved that map, so passing an explicit model is allowed. Pass the resolved `providerID/modelID` (or `providerID/modelID#variant`) to the Task/subagent tool.
272
- - **`cheap`** → mechanical steps only (router, analyst, tech-writer, codebase-analyzer).
273
- - **`standard`** → implementation, verification, review, QA, contract review.
274
- - **`strong`** → architecture, security, migration, performance, mockup review. Never downgrade a `strong` step to the parent default.
272
+ - **`cheap`** → router, analyst, tech-writer, codebase-analyzer, and the review roles `code-reviewer`, `build-verifier`, `api-contract-reviewer`, `mockup-reviewer`. Resolve the provider through `.ai.local/team/model-tiers.json`. Do not write a provider id into the agent file. Pass the mapped id as written; do not append `#high`.
273
+ - **`standard`** → implementation and the other non-review specialists. `feature-developer` stays on this tier.
274
+ - **`strong`** → architecture, security, migration, performance. Never downgrade a `strong` step to the parent default, and do not put `mockup-reviewer` on `strong`.
275
+ - When `steps[i].model` is omitted and the agent file has no `model`, those four review roles stay `cheap` when `.ai.local/team/model-tiers.json` exists. Without that file, omit the model and the session model applies.
275
276
  - If a tier is declared but the file has no mapping, **STOP** and report `model-tier-unmapped`; do not silently inherit the parent model.
276
277
  3. If the tool does not accept a model (Cursor/Claude adapters), record the resolved tier in the handoff and let the platform pin apply.
277
278
  4. Parallel steps: apply the step-level `model` to **each** agent in the array (or omit → each agent’s own frontmatter).
@@ -16,7 +16,7 @@ Typical feature with data and UI. Concrete directories and rule stems — in the
16
16
 
17
17
  ## Context hygiene
18
18
 
19
- A command whose output can exceed ~4 KB — a test run, a build/lint log, `git log`, a diff — is piped through `.ai.local/scripts/dump-output.mjs --task <slug>` instead of being read whole. Work from its ≤40-line head and the stored file (grep it or use `team-db.mjs search`), and when that output informed a decision, record the repo-relative `outputs/…` path in `implementation.md` or `validation-report.md`; a `code-reviewer` may ask for that path. Do not read the whole output into context.
19
+ A command whose output can exceed ~4 KB — a test run, a build/lint log, `git log`, a diff — is piped through `.ai.local/scripts/dump-output.mjs --task <slug>` instead of being read whole. Work from its ≤40-line head and the stored file (grep it or use `team-db.mjs search`), and when that output informed a decision, record the repo-relative `outputs/…` path in `implementation.md` or `validation-report.md`; a `code-reviewer` may ask for that path. Do not read the whole output into context. Artifact reads take the same slice: read the `artifact-manifest.json` entry, not the artifact body, and never re-read a completed entry's body. Read a large artifact with offset/limit ranges instead of a whole-file read.
20
20
 
21
21
  ## Iterative refinement loop
22
22
 
@@ -81,11 +81,127 @@ function readMetrics(filePath) {
81
81
  }
82
82
  }
83
83
 
84
+ /**
85
+ * Usage math for the report. The SQLite projection owns the same AD-3 rules
86
+ * (host `attempt_finished.usage` wins; `usage_recorded` rows collapse per turn)
87
+ * in `team-db-project.mjs`. Keep the two in step: a token kind nobody reported
88
+ * stays `null`, never `0`.
89
+ */
90
+ const usageNumber = (value) =>
91
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
92
+
93
+ const usageEventAt = (event) => {
94
+ const at = Date.parse(event.at ?? '');
95
+ return Number.isFinite(at) ? at : null;
96
+ };
97
+
98
+ const collapseUsageTurns = (events) => {
99
+ const winners = new Map();
100
+ events.forEach((event, index) => {
101
+ if (typeof event.turn !== 'string' || event.turn === '') {
102
+ winners.set(`#${index}`, index);
103
+ return;
104
+ }
105
+ const current = winners.get(event.turn);
106
+ if (current === undefined) {
107
+ winners.set(event.turn, index);
108
+ return;
109
+ }
110
+ const at = usageEventAt(event);
111
+ const currentAt = usageEventAt(events[current]);
112
+ const later = at === null || currentAt === null || at === currentAt ? index > current : at > currentAt;
113
+ if (later) winners.set(event.turn, index);
114
+ });
115
+ const kept = new Set(winners.values());
116
+ return events.filter((event, index) => kept.has(index) || typeof event.turn !== 'string' || event.turn === '');
117
+ };
118
+
119
+ const EMPTY_USAGE = {
120
+ input: null,
121
+ output: null,
122
+ reasoning: null,
123
+ cacheRead: null,
124
+ cacheWrite: null,
125
+ costUsd: null,
126
+ source: null,
127
+ model: null,
128
+ turns: 0,
129
+ };
130
+
131
+ const normalizeUsage = (hostUsage, usageEvents = []) => {
132
+ if (hostUsage && typeof hostUsage === 'object' && !Array.isArray(hostUsage)) {
133
+ const usage = {
134
+ input: usageNumber(hostUsage.input),
135
+ output: usageNumber(hostUsage.output),
136
+ reasoning: usageNumber(hostUsage.reasoning),
137
+ cacheRead: usageNumber(hostUsage.cacheRead),
138
+ cacheWrite: usageNumber(hostUsage.cacheWrite),
139
+ costUsd: usageNumber(hostUsage.costUsd),
140
+ source: 'host',
141
+ model: typeof hostUsage.model === 'string' && hostUsage.model !== '' ? hostUsage.model : null,
142
+ turns: 0,
143
+ };
144
+ const reported = Object.entries(usage).some(
145
+ ([key, value]) => !['source', 'model', 'turns'].includes(key) && value !== null,
146
+ );
147
+ return reported ? usage : { ...EMPTY_USAGE };
148
+ }
149
+ const events = collapseUsageTurns(usageEvents.filter((event) => event && typeof event === 'object'));
150
+ if (events.length === 0) return { ...EMPTY_USAGE };
151
+ const sum = (key) => {
152
+ let total = null;
153
+ for (const event of events) {
154
+ const value = usageNumber(event[key]);
155
+ if (value !== null) total = (total ?? 0) + value;
156
+ }
157
+ return total;
158
+ };
159
+ const model = events.find((event) => typeof event.model === 'string' && event.model !== '')?.model ?? null;
160
+ return {
161
+ ...EMPTY_USAGE,
162
+ input: sum('input'),
163
+ output: sum('output'),
164
+ reasoning: sum('reasoning'),
165
+ cacheRead: sum('cached'),
166
+ cacheWrite: sum('cacheWrite'),
167
+ source: 'cli',
168
+ model,
169
+ turns: events.length,
170
+ };
171
+ };
172
+
173
+ const hasUsage = (usage) =>
174
+ Boolean(usage) &&
175
+ ['input', 'output', 'reasoning', 'cacheRead', 'cacheWrite', 'costUsd'].some((key) => usage[key] !== null);
176
+
177
+ const addUsage = (total, usage) => {
178
+ if (!hasUsage(usage)) return total;
179
+ const next = { ...total };
180
+ for (const key of ['input', 'output', 'reasoning', 'cacheRead', 'cacheWrite', 'costUsd']) {
181
+ if (usage[key] === null) continue;
182
+ next[key] = (next[key] ?? 0) + usage[key];
183
+ }
184
+ next.reported += 1;
185
+ return next;
186
+ };
187
+
188
+ const emptyUsageTotal = () => ({
189
+ input: null,
190
+ output: null,
191
+ reasoning: null,
192
+ cacheRead: null,
193
+ cacheWrite: null,
194
+ costUsd: null,
195
+ reported: 0,
196
+ });
197
+
84
198
  function collect(metrics, filePath) {
85
199
  const starts = new Map();
86
200
  const gateStarts = new Map();
87
201
  const terminalAttempts = new Set();
88
202
  const attemptDurations = [];
203
+ const hostUsage = new Map();
204
+ const usageEventsByAttempt = new Map();
89
205
  let taskCompleted = false;
90
206
  let ledgerIncomplete = false;
91
207
  let taskStartedAt = null;
@@ -93,6 +209,7 @@ function collect(metrics, filePath) {
93
209
  let taskGateWaitMs = 0;
94
210
  let taskOutOfBandMs = 0;
95
211
  let taskOutOfBandCount = 0;
212
+ let taskUsage = emptyUsageTotal();
96
213
 
97
214
  for (const event of metrics.events) {
98
215
  if (event.type === 'task_started') taskStartedAt = event.at;
@@ -143,6 +260,12 @@ function collect(metrics, filePath) {
143
260
  (attributionConfidenceCounts.get(attributionConfidence) ?? 0) + 1,
144
261
  );
145
262
  if (Number.isFinite(event.durationMs)) attemptDurations.push(event.durationMs);
263
+ const usage = normalizeUsage(
264
+ hostUsage.get(event.attemptId) ??
265
+ (event.usage && typeof event.usage === 'object' ? event.usage : null),
266
+ usageEventsByAttempt.get(event.attemptId) ?? [],
267
+ );
268
+ taskUsage = addUsage(taskUsage, usage);
146
269
  attempts.push({
147
270
  ...metrics.task,
148
271
  agent: start.agent ?? 'unknown',
@@ -150,7 +273,25 @@ function collect(metrics, filePath) {
150
273
  durationMs: Number.isFinite(event.durationMs) ? event.durationMs : null,
151
274
  outcome: event.outcome ?? 'unknown',
152
275
  attributionConfidence,
276
+ usage,
277
+ });
278
+ }
279
+ if (event.type === 'attempt_finished' && event.attemptId && event.usage && typeof event.usage === 'object') {
280
+ hostUsage.set(event.attemptId, event.usage);
281
+ }
282
+ if (event.type === 'usage_recorded' && event.attemptId) {
283
+ const list = usageEventsByAttempt.get(event.attemptId) ?? [];
284
+ list.push({
285
+ at: event.at,
286
+ turn: event.turn,
287
+ model: event.model,
288
+ input: event.input,
289
+ output: event.output,
290
+ cached: event.cached,
291
+ cacheWrite: event.cacheWrite,
292
+ reasoning: event.reasoning,
153
293
  });
294
+ usageEventsByAttempt.set(event.attemptId, list);
154
295
  }
155
296
  if (event.type === 'human_gate_started' && event.eventId) {
156
297
  gateStarts.set(event.eventId, event);
@@ -192,6 +333,18 @@ function collect(metrics, filePath) {
192
333
  attemptCount: terminalAttempts.size,
193
334
  completed: taskCompleted,
194
335
  incomplete: ledgerIncomplete,
336
+ usage: {
337
+ reportedAttempts: taskUsage.reported,
338
+ coverage: terminalAttempts.size ? taskUsage.reported / terminalAttempts.size : null,
339
+ tokens: {
340
+ input: taskUsage.input,
341
+ output: taskUsage.output,
342
+ reasoning: taskUsage.reasoning,
343
+ cacheRead: taskUsage.cacheRead,
344
+ cacheWrite: taskUsage.cacheWrite,
345
+ },
346
+ costUsd: taskUsage.costUsd,
347
+ },
195
348
  });
196
349
  }
197
350
  }
@@ -223,6 +376,7 @@ const byAgentRole = groupBy(
223
376
  const sample = group[0];
224
377
  const durations = group.map((item) => item.durationMs).filter((value) => value !== null);
225
378
  const sumDurationMs = durations.reduce((sum, value) => sum + value, 0);
379
+ const usageTotal = group.reduce((total, item) => addUsage(total, item.usage), emptyUsageTotal());
226
380
  return {
227
381
  platform: sample.platform,
228
382
  stack: sample.stack,
@@ -233,6 +387,17 @@ const byAgentRole = groupBy(
233
387
  completedCount: group.filter((item) => item.outcome === 'completed').length,
234
388
  sumDurationMs,
235
389
  avgDurationMs: durations.length ? sumDurationMs / durations.length : null,
390
+ usage: {
391
+ reportedAttempts: usageTotal.reported,
392
+ tokens: {
393
+ input: usageTotal.input,
394
+ output: usageTotal.output,
395
+ reasoning: usageTotal.reasoning,
396
+ cacheRead: usageTotal.cacheRead,
397
+ cacheWrite: usageTotal.cacheWrite,
398
+ },
399
+ costUsd: usageTotal.costUsd,
400
+ },
236
401
  };
237
402
  });
238
403
 
@@ -245,11 +410,47 @@ const taskCountsByRunId = [...new Map(tasks.map((task) => [task.runId, task])).v
245
410
  intent: task.intent,
246
411
  }));
247
412
 
413
+ const usageTotal = attempts.reduce((total, item) => addUsage(total, item.usage), emptyUsageTotal());
414
+ const usageModels = new Map();
415
+ for (const item of attempts) {
416
+ if (!hasUsage(item.usage) || typeof item.usage.model !== 'string') continue;
417
+ const key = item.usage.model;
418
+ const current = usageModels.get(key) ?? { model: key, attempts: 0, usage: emptyUsageTotal() };
419
+ current.attempts += 1;
420
+ current.usage = addUsage(current.usage, item.usage);
421
+ usageModels.set(key, current);
422
+ }
423
+
248
424
  process.stdout.write(
249
425
  `${JSON.stringify(
250
426
  {
251
427
  schemaVersion: 1,
252
428
  teamRoot,
429
+ usage: {
430
+ attempts: attempts.length,
431
+ reportedAttempts: usageTotal.reported,
432
+ coverage: attempts.length ? usageTotal.reported / attempts.length : null,
433
+ tokens: {
434
+ input: usageTotal.input,
435
+ output: usageTotal.output,
436
+ reasoning: usageTotal.reasoning,
437
+ cacheRead: usageTotal.cacheRead,
438
+ cacheWrite: usageTotal.cacheWrite,
439
+ },
440
+ costUsd: usageTotal.costUsd,
441
+ byModel: [...usageModels.values()].map((entry) => ({
442
+ model: entry.model,
443
+ attempts: entry.attempts,
444
+ tokens: {
445
+ input: entry.usage.input,
446
+ output: entry.usage.output,
447
+ reasoning: entry.usage.reasoning,
448
+ cacheRead: entry.usage.cacheRead,
449
+ cacheWrite: entry.usage.cacheWrite,
450
+ },
451
+ costUsd: entry.usage.costUsd,
452
+ })),
453
+ },
253
454
  agentRole: byAgentRole,
254
455
  taskCountsByRunId,
255
456
  taskReports,
@@ -341,6 +341,82 @@ export function summarizeOutputGuard(rows) {
341
341
  };
342
342
  }
343
343
 
344
+ /**
345
+ * Summarize tool activity over the output-guard `results.jsonl` rows: the
346
+ * read-slice norm's measurement (`readCountPerPath`) and the tool-error split
347
+ * (`mcpErrors`). Read calls are `tool === 'read'` rows keyed by their exact
348
+ * `command` — the read tool's `command` is the file path it read. A plugin
349
+ * reload can repeat a `(sessionID, callID)` pair, so the first row wins.
350
+ *
351
+ * `error: true` rows are tool results the host delivered as its error variant;
352
+ * rows written before the field existed carry no key and stay non-errors. MCP
353
+ * attribution prefers the server names the context snapshot recorded
354
+ * (`mcpServers[].name` prefixes, `serverNames`); only when no snapshot names
355
+ * any server does the `<server>_<tool>` naming convention stay as the
356
+ * documented fallback (`mcpAttribution` names which basis was used).
357
+ */
358
+ export function summarizeToolActivity(rows, serverNames = []) {
359
+ const servers = Array.isArray(serverNames)
360
+ ? serverNames.filter((name) => typeof name === 'string' && name !== '')
361
+ : [];
362
+ const isMcp =
363
+ servers.length > 0
364
+ ? (tool) => servers.some((name) => tool.startsWith(`${name}_`))
365
+ : (tool) => tool.includes('_');
366
+ const seen = new Set();
367
+ const readCounts = new Map();
368
+ const errorCounts = new Map();
369
+ let reads = 0;
370
+ let unattributedReads = 0;
371
+ let errors = 0;
372
+ let mcpErrors = 0;
373
+ let invalid = 0;
374
+ for (const row of Array.isArray(rows) ? rows : []) {
375
+ if (!row || typeof row !== 'object') {
376
+ invalid += 1;
377
+ continue;
378
+ }
379
+ const sessionID = typeof row.sessionID === 'string' ? row.sessionID : '';
380
+ const callID = typeof row.callID === 'string' ? row.callID : '';
381
+ const tool = typeof row.tool === 'string' ? row.tool : '';
382
+ if (sessionID === '' || callID === '' || tool === '') {
383
+ invalid += 1;
384
+ continue;
385
+ }
386
+ const key = `${sessionID}|${callID}`;
387
+ if (seen.has(key)) continue;
388
+ seen.add(key);
389
+ if (tool === 'read') {
390
+ reads += 1;
391
+ if (typeof row.command === 'string' && row.command !== '') {
392
+ readCounts.set(row.command, (readCounts.get(row.command) ?? 0) + 1);
393
+ } else {
394
+ unattributedReads += 1;
395
+ }
396
+ }
397
+ if (row.error === true) {
398
+ errors += 1;
399
+ if (isMcp(tool)) mcpErrors += 1;
400
+ errorCounts.set(tool, (errorCounts.get(tool) ?? 0) + 1);
401
+ }
402
+ }
403
+ return {
404
+ reads,
405
+ unattributedReads,
406
+ distinctPaths: readCounts.size,
407
+ readCountPerPath: [...readCounts.entries()]
408
+ .map(([path, count]) => ({ path, count }))
409
+ .sort((a, b) => b.count - a.count || a.path.localeCompare(b.path)),
410
+ errors,
411
+ mcpErrors,
412
+ mcpAttribution: servers.length > 0 ? 'servers' : 'naming-convention',
413
+ errorsByTool: [...errorCounts.entries()]
414
+ .map(([tool, count]) => ({ tool, count }))
415
+ .sort((a, b) => b.count - a.count || a.tool.localeCompare(b.tool)),
416
+ invalid,
417
+ };
418
+ }
419
+
344
420
  /**
345
421
  * Attribute the hook-time schema snapshot. The plugin writes one row per
346
422
  * `(sessionID, toolset)`; a reload can repeat a key, so the first row wins.
@@ -490,6 +566,30 @@ function outputGuardReport() {
490
566
  return { present: true, file: toRepoPath(file), ...summarizeOutputGuard(rows) };
491
567
  }
492
568
 
569
+ function toolActivityReport() {
570
+ const file = path.join(repoRoot, '.ai.local', 'team', 'output-guard', 'results.jsonl');
571
+ const ledger = readJsonlRows(file);
572
+ const contextLedger = readJsonlRows(
573
+ path.join(repoRoot, '.ai.local', 'team', 'output-guard', 'context.jsonl'),
574
+ );
575
+ const serverNames = [];
576
+ for (const row of contextLedger.rows) {
577
+ if (!Array.isArray(row?.mcpServers)) continue;
578
+ for (const server of row.mcpServers) {
579
+ if (server && typeof server === 'object' && typeof server.name === 'string') {
580
+ serverNames.push(server.name);
581
+ }
582
+ }
583
+ }
584
+ const summary = summarizeToolActivity(ledger.rows, [...new Set(serverNames)]);
585
+ return {
586
+ file: toRepoPath(file),
587
+ present: ledger.present,
588
+ ...summary,
589
+ invalid: summary.invalid + ledger.invalid,
590
+ };
591
+ }
592
+
493
593
  function buildReport() {
494
594
  const slugs = listTaskSlugs();
495
595
  return {
@@ -506,6 +606,7 @@ function buildReport() {
506
606
  tasks: taskReport(slugs),
507
607
  usage: usageReport(slugs),
508
608
  outputGuard: outputGuardReport(),
609
+ toolActivity: toolActivityReport(),
509
610
  mcpSchemas: mcpSchemasReport(),
510
611
  };
511
612
  }
@@ -611,6 +712,31 @@ function humanReport(report) {
611
712
  lines.push(` ${formatInt(report.outputGuard.invalid)} invalid row(s) ignored`);
612
713
  }
613
714
  lines.push('');
715
+ const activity = report.toolActivity;
716
+ lines.push('TOOL ACTIVITY — artifact reads and tool errors (results.jsonl, deduped by sessionID+callID)');
717
+ if (!activity.present) {
718
+ lines.push('no results.jsonl yet (nothing measured)');
719
+ } else {
720
+ lines.push(
721
+ `${padStart(formatInt(activity.reads), 7)} reads` +
722
+ `${padStart(formatInt(activity.distinctPaths), 12)} distinct paths` +
723
+ `${padStart(formatInt(activity.unattributedReads), 12)} no-target` +
724
+ ` ${formatInt(activity.errors)} errored tool result(s), ${formatInt(activity.mcpErrors)} on MCP tools`,
725
+ );
726
+ for (const entry of activity.readCountPerPath.slice(0, 5)) {
727
+ lines.push(` ${padStart(formatInt(entry.count), 5)} ${entry.path}`);
728
+ }
729
+ if (activity.readCountPerPath.length > 5) {
730
+ lines.push(` … and ${formatInt(activity.readCountPerPath.length - 5)} more paths (--json carries the full map)`);
731
+ }
732
+ for (const entry of activity.errorsByTool.slice(0, 5)) {
733
+ lines.push(` ${padStart(formatInt(entry.count), 5)}x errored ${entry.tool}`);
734
+ }
735
+ if (activity.invalid > 0) {
736
+ lines.push(` ${formatInt(activity.invalid)} invalid row(s) ignored`);
737
+ }
738
+ }
739
+ lines.push('');
614
740
  lines.push('USAGE — usage_recorded events across task metrics.json (a missing record stays missing)');
615
741
  lines.push(
616
742
  `${padStart(formatInt(report.usage.events), 7)} events${padStart(formatInt(report.usage.input), 10)} input` +