@bonesofspring/ai-rules 0.2.70 → 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 (249) hide show
  1. package/CHANGELOG.md +65 -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-api.mjs +4 -4
  10. package/presets/_shared/ai-local/scripts/team-db-project.mjs +2 -0
  11. package/presets/_shared/ai-local/scripts/verification.mjs +374 -0
  12. package/presets/_shared/core/agent-team/agent-task-metrics.md +61 -1
  13. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +5 -4
  14. package/presets/_shared/core/agent-team/incident-registry.md +47 -0
  15. package/presets/_shared/core/architecture/feature-delivery-workflow.md +1 -1
  16. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +108 -1
  17. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +108 -1
  18. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  19. package/presets/claude/go/hooks/chain-team-phases.sh +108 -1
  20. package/presets/claude/go/rules/architecture/feature-delivery.md +1 -1
  21. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  22. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +108 -1
  23. package/presets/claude/ios-swift/rules/architecture/feature-delivery.md +1 -1
  24. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  25. package/presets/claude/java/hooks/chain-team-phases.sh +108 -1
  26. package/presets/claude/java/rules/architecture/feature-delivery.md +1 -1
  27. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  28. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +108 -1
  29. package/presets/claude/mcp-ts/rules/architecture/feature-delivery.md +1 -1
  30. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  31. package/presets/claude/mol/hooks/chain-team-phases.sh +108 -1
  32. package/presets/claude/mol/rules/architecture/feature-delivery-workflow.md +1 -1
  33. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  34. package/presets/claude/next/agents/README.md +4 -3
  35. package/presets/claude/next/agents/api-contract-reviewer.md +1 -1
  36. package/presets/claude/next/agents/mockup-reviewer.md +1 -1
  37. package/presets/claude/next/agents/task-router.md +4 -4
  38. package/presets/claude/next/hooks/chain-team-phases.sh +108 -1
  39. package/presets/claude/next/rules/architecture/feature-delivery-workflow.md +2 -2
  40. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  41. package/presets/claude/nuxt/hooks/chain-team-phases.sh +108 -1
  42. package/presets/claude/nuxt/rules/architecture/feature-delivery-workflow.md +1 -1
  43. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  44. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  45. package/presets/claude/php-hexagonal/rules/architecture/feature-delivery.md +1 -1
  46. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  47. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +108 -1
  48. package/presets/claude/php-laravel/rules/architecture/feature-delivery.md +1 -1
  49. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  50. package/presets/claude/svelte/hooks/chain-team-phases.sh +108 -1
  51. package/presets/claude/svelte/rules/architecture/feature-delivery-workflow.md +1 -1
  52. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +5 -4
  53. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +108 -1
  54. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +1 -1
  55. package/presets/cursor/go/hooks/chain-team-phases.sh +108 -1
  56. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +1 -1
  57. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +108 -1
  58. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +1 -1
  59. package/presets/cursor/java/hooks/chain-team-phases.sh +108 -1
  60. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +1 -1
  61. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +108 -1
  62. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +1 -1
  63. package/presets/cursor/mol/hooks/chain-team-phases.sh +108 -1
  64. package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +1 -1
  65. package/presets/cursor/next/agents/README.md +4 -3
  66. package/presets/cursor/next/agents/api-contract-reviewer.md +1 -1
  67. package/presets/cursor/next/agents/mockup-reviewer.md +1 -1
  68. package/presets/cursor/next/agents/task-router.md +4 -4
  69. package/presets/cursor/next/hooks/chain-team-phases.sh +108 -1
  70. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +1 -1
  71. package/presets/cursor/next/rules/feature-delivery-workflow.mdc +1 -1
  72. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +108 -1
  73. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  74. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  75. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +1 -1
  76. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +108 -1
  77. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +1 -1
  78. package/presets/cursor/svelte/hooks/chain-team-phases.sh +108 -1
  79. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  80. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  81. package/presets/mavis/android-kotlin/agents/README.md +3 -3
  82. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +108 -1
  83. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +5 -4
  84. package/presets/mavis/go/adapter-map.json +1 -1
  85. package/presets/mavis/go/agents/README.md +2 -2
  86. package/presets/mavis/go/hooks/chain-team-phases.sh +108 -1
  87. package/presets/mavis/go/rules/agent-team-orchestrator.md +5 -4
  88. package/presets/mavis/go/rules/feature-delivery-workflow.md +1 -1
  89. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  90. package/presets/mavis/ios-swift/agents/README.md +3 -3
  91. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +108 -1
  92. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +5 -4
  93. package/presets/mavis/ios-swift/rules/feature-delivery-workflow.md +1 -1
  94. package/presets/mavis/java/adapter-map.json +1 -1
  95. package/presets/mavis/java/agents/README.md +2 -2
  96. package/presets/mavis/java/hooks/chain-team-phases.sh +108 -1
  97. package/presets/mavis/java/rules/agent-team-orchestrator.md +5 -4
  98. package/presets/mavis/java/rules/feature-delivery-workflow.md +1 -1
  99. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  100. package/presets/mavis/mcp-ts/agents/README.md +1 -1
  101. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +108 -1
  102. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +5 -4
  103. package/presets/mavis/mcp-ts/rules/feature-delivery-workflow.md +1 -1
  104. package/presets/mavis/mol/adapter-map.json +1 -1
  105. package/presets/mavis/mol/agents/README.md +3 -3
  106. package/presets/mavis/mol/hooks/chain-team-phases.sh +108 -1
  107. package/presets/mavis/mol/rules/agent-team-orchestrator.md +5 -4
  108. package/presets/mavis/mol/rules/feature-delivery-workflow.md +1 -1
  109. package/presets/mavis/next/adapter-map.json +1 -1
  110. package/presets/mavis/next/agents/README.md +3 -3
  111. package/presets/mavis/next/agents/task-router.md +4 -4
  112. package/presets/mavis/next/hooks/chain-team-phases.sh +108 -1
  113. package/presets/mavis/next/rules/agent-team-orchestrator.md +5 -4
  114. package/presets/mavis/next/rules/feature-delivery-workflow.md +2 -2
  115. package/presets/mavis/nuxt/adapter-map.json +1 -1
  116. package/presets/mavis/nuxt/agents/README.md +3 -3
  117. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +108 -1
  118. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +5 -4
  119. package/presets/mavis/nuxt/rules/feature-delivery-workflow.md +1 -1
  120. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  121. package/presets/mavis/php-hexagonal/agents/README.md +2 -2
  122. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  123. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
  124. package/presets/mavis/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
  125. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  126. package/presets/mavis/php-laravel/agents/README.md +2 -2
  127. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +108 -1
  128. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +5 -4
  129. package/presets/mavis/php-laravel/rules/feature-delivery-workflow.md +1 -1
  130. package/presets/mavis/svelte/adapter-map.json +1 -1
  131. package/presets/mavis/svelte/agents/README.md +3 -3
  132. package/presets/mavis/svelte/hooks/chain-team-phases.sh +108 -1
  133. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +5 -4
  134. package/presets/mavis/svelte/rules/feature-delivery-workflow.md +1 -1
  135. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  136. package/presets/opencode/android-kotlin/agents/README.md +4 -4
  137. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +108 -1
  138. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +5 -4
  139. package/presets/opencode/go/adapter-map.json +1 -1
  140. package/presets/opencode/go/agents/README.md +3 -3
  141. package/presets/opencode/go/hooks/chain-team-phases.sh +108 -1
  142. package/presets/opencode/go/rules/agent-team-orchestrator.md +5 -4
  143. package/presets/opencode/go/rules/feature-delivery-workflow.md +1 -1
  144. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  145. package/presets/opencode/ios-swift/agents/README.md +4 -4
  146. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +108 -1
  147. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +5 -4
  148. package/presets/opencode/ios-swift/rules/feature-delivery-workflow.md +1 -1
  149. package/presets/opencode/java/adapter-map.json +1 -1
  150. package/presets/opencode/java/agents/README.md +3 -3
  151. package/presets/opencode/java/hooks/chain-team-phases.sh +108 -1
  152. package/presets/opencode/java/rules/agent-team-orchestrator.md +5 -4
  153. package/presets/opencode/java/rules/feature-delivery-workflow.md +1 -1
  154. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  155. package/presets/opencode/mcp-ts/agents/README.md +2 -2
  156. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +108 -1
  157. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +5 -4
  158. package/presets/opencode/mcp-ts/rules/feature-delivery-workflow.md +1 -1
  159. package/presets/opencode/mol/adapter-map.json +1 -1
  160. package/presets/opencode/mol/agents/README.md +4 -4
  161. package/presets/opencode/mol/hooks/chain-team-phases.sh +108 -1
  162. package/presets/opencode/mol/rules/agent-team-orchestrator.md +5 -4
  163. package/presets/opencode/mol/rules/feature-delivery-workflow.md +1 -1
  164. package/presets/opencode/next/adapter-map.json +1 -1
  165. package/presets/opencode/next/agents/README.md +4 -4
  166. package/presets/opencode/next/agents/task-router.md +4 -4
  167. package/presets/opencode/next/hooks/chain-team-phases.sh +108 -1
  168. package/presets/opencode/next/rules/agent-team-orchestrator.md +5 -4
  169. package/presets/opencode/next/rules/feature-delivery-workflow.md +2 -2
  170. package/presets/opencode/nuxt/adapter-map.json +1 -1
  171. package/presets/opencode/nuxt/agents/README.md +4 -4
  172. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +108 -1
  173. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +5 -4
  174. package/presets/opencode/nuxt/rules/feature-delivery-workflow.md +1 -1
  175. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  176. package/presets/opencode/php-hexagonal/agents/README.md +3 -3
  177. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  178. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
  179. package/presets/opencode/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
  180. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  181. package/presets/opencode/php-laravel/agents/README.md +3 -3
  182. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +108 -1
  183. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +5 -4
  184. package/presets/opencode/php-laravel/rules/feature-delivery-workflow.md +1 -1
  185. package/presets/opencode/plugins/output-guard/README.md +25 -4
  186. package/presets/opencode/plugins/output-guard/index.ts +57 -11
  187. package/presets/opencode/plugins/output-guard/rewrite.ts +104 -1
  188. package/presets/opencode/svelte/adapter-map.json +1 -1
  189. package/presets/opencode/svelte/agents/README.md +4 -4
  190. package/presets/opencode/svelte/hooks/chain-team-phases.sh +108 -1
  191. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +5 -4
  192. package/presets/opencode/svelte/rules/feature-delivery-workflow.md +1 -1
  193. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  194. package/presets/zcode/android-kotlin/agents/README.md +3 -3
  195. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +108 -1
  196. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +5 -4
  197. package/presets/zcode/go/adapter-map.json +1 -1
  198. package/presets/zcode/go/agents/README.md +2 -2
  199. package/presets/zcode/go/hooks/chain-team-phases.sh +108 -1
  200. package/presets/zcode/go/rules/agent-team-orchestrator.md +5 -4
  201. package/presets/zcode/go/rules/feature-delivery-workflow.md +1 -1
  202. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  203. package/presets/zcode/ios-swift/agents/README.md +3 -3
  204. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +108 -1
  205. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +5 -4
  206. package/presets/zcode/ios-swift/rules/feature-delivery-workflow.md +1 -1
  207. package/presets/zcode/java/adapter-map.json +1 -1
  208. package/presets/zcode/java/agents/README.md +2 -2
  209. package/presets/zcode/java/hooks/chain-team-phases.sh +108 -1
  210. package/presets/zcode/java/rules/agent-team-orchestrator.md +5 -4
  211. package/presets/zcode/java/rules/feature-delivery-workflow.md +1 -1
  212. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  213. package/presets/zcode/mcp-ts/agents/README.md +1 -1
  214. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +108 -1
  215. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +5 -4
  216. package/presets/zcode/mcp-ts/rules/feature-delivery-workflow.md +1 -1
  217. package/presets/zcode/mol/adapter-map.json +1 -1
  218. package/presets/zcode/mol/agents/README.md +3 -3
  219. package/presets/zcode/mol/hooks/chain-team-phases.sh +108 -1
  220. package/presets/zcode/mol/rules/agent-team-orchestrator.md +5 -4
  221. package/presets/zcode/mol/rules/feature-delivery-workflow.md +1 -1
  222. package/presets/zcode/next/adapter-map.json +1 -1
  223. package/presets/zcode/next/agents/README.md +3 -3
  224. package/presets/zcode/next/agents/task-router.md +4 -4
  225. package/presets/zcode/next/hooks/chain-team-phases.sh +108 -1
  226. package/presets/zcode/next/rules/agent-team-orchestrator.md +5 -4
  227. package/presets/zcode/next/rules/feature-delivery-workflow.md +2 -2
  228. package/presets/zcode/nuxt/adapter-map.json +1 -1
  229. package/presets/zcode/nuxt/agents/README.md +3 -3
  230. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +108 -1
  231. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +5 -4
  232. package/presets/zcode/nuxt/rules/feature-delivery-workflow.md +1 -1
  233. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  234. package/presets/zcode/php-hexagonal/agents/README.md +2 -2
  235. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +108 -1
  236. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +5 -4
  237. package/presets/zcode/php-hexagonal/rules/feature-delivery-workflow.md +1 -1
  238. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  239. package/presets/zcode/php-laravel/agents/README.md +2 -2
  240. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +108 -1
  241. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +5 -4
  242. package/presets/zcode/php-laravel/rules/feature-delivery-workflow.md +1 -1
  243. package/presets/zcode/svelte/adapter-map.json +1 -1
  244. package/presets/zcode/svelte/agents/README.md +3 -3
  245. package/presets/zcode/svelte/hooks/chain-team-phases.sh +108 -1
  246. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +5 -4
  247. package/presets/zcode/svelte/rules/feature-delivery-workflow.md +1 -1
  248. package/scripts/aggregate-agent-task-metrics.mjs +201 -0
  249. package/scripts/report-context-cost.mjs +126 -0
@@ -21,7 +21,7 @@ Typical feature with data and UI. Concrete directories and rule stems — in the
21
21
 
22
22
  ## Context hygiene
23
23
 
24
- 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.
24
+ 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.
25
25
 
26
26
  ## Iterative refinement loop
27
27
 
@@ -156,7 +156,7 @@ Replanning is a **named, auditable operation** — never a silent reorder. Trigg
156
156
 
157
157
  ## Context budget & checkpoint/resume
158
158
 
159
- 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.
159
+ 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.
160
160
 
161
161
  ## Self-review & context hygiene
162
162
 
@@ -274,9 +274,10 @@ Use Task tool or `/agent-name`. Pass: slug, artifact paths, step `scope` if set.
274
274
 
275
275
  1. Read `steps[i].model` if present; else use the agent’s frontmatter `model` (see `agents/README.md` matrix).
276
276
  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.
277
- - **`cheap`** → mechanical steps only (router, analyst, tech-writer, codebase-analyzer).
278
- - **`standard`** → implementation, verification, review, QA, contract review.
279
- - **`strong`** → architecture, security, migration, performance, mockup review. Never downgrade a `strong` step to the parent default.
277
+ - **`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`.
278
+ - **`standard`** → implementation and the other non-review specialists. `feature-developer` stays on this tier.
279
+ - **`strong`** → architecture, security, migration, performance. Never downgrade a `strong` step to the parent default, and do not put `mockup-reviewer` on `strong`.
280
+ - 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.
280
281
  - If a tier is declared but the file has no mapping, **STOP** and report `model-tier-unmapped`; do not silently inherit the parent model.
281
282
  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.
282
283
  4. Parallel steps: apply the step-level `model` to **each** agent in the array (or omit → each agent’s own frontmatter).
@@ -985,11 +985,117 @@ function reconcileStatusFromManifest(agent, step, resolved) {
985
985
  return status.state;
986
986
  }
987
987
 
988
+ /**
989
+ * Keep only the numeric usage fields and the two provenance fields. A host may
990
+ * forward richer objects; the ledger is allowlisted so nothing unbounded or
991
+ * secret-shaped reaches `metrics.json`.
992
+ */
993
+ function sanitizeUsage(value) {
994
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
995
+ const num = (input) => (typeof input === 'number' && Number.isFinite(input) && input >= 0 ? input : null);
996
+ const usage = {
997
+ input: num(value.input), output: num(value.output), reasoning: num(value.reasoning),
998
+ cacheRead: num(value.cacheRead === undefined ? value.cached : value.cacheRead),
999
+ cacheWrite: num(value.cacheWrite), costUsd: num(value.costUsd),
1000
+ model: typeof value.model === 'string' ? value.model.slice(0, 120) : null,
1001
+ origin: value.origin === 'estimated' ? 'estimated' : 'measured',
1002
+ };
1003
+ const reported = usage.input !== null || usage.output !== null || usage.reasoning !== null ||
1004
+ usage.cacheRead !== null || usage.cacheWrite !== null || usage.costUsd !== null;
1005
+ return reported ? usage : null;
1006
+ }
1007
+
1008
+ /**
1009
+ * Freshness of a persisted verification snapshot against the current worktree.
1010
+ * Read-only: closure warns, it never blocks on a stale snapshot.
1011
+ */
1012
+ function gitSnapshot() {
1013
+ const { spawnSync } = require('child_process');
1014
+ const git = (args) => {
1015
+ const result = spawnSync('git', args, { cwd: process.cwd(), encoding: 'utf8', timeout: 10000, maxBuffer: 32 * 1024 * 1024 });
1016
+ return result && result.status === 0 ? String(result.stdout || '') : null;
1017
+ };
1018
+ const head = git(['rev-parse', 'HEAD']);
1019
+ if (head === null) return null;
1020
+ const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']);
1021
+ const exclude = ['--', '.', ':(exclude).ai.local'];
1022
+ const statusText = git(['status', '--porcelain=v1', ...exclude]) || '';
1023
+ const diffText = git(['diff', '--binary', 'HEAD', ...exclude]) || '';
1024
+ const untracked = git(['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
1025
+ return {
1026
+ head: head.trim(),
1027
+ branch: branch === null ? null : branch.trim(),
1028
+ dirtyFiles: statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length,
1029
+ worktreeHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1030
+ capturedAt: now,
1031
+ };
1032
+ }
1033
+
1034
+ /**
1035
+ * Seed the evidence file when the verifier finishes without an explicit
1036
+ * `verification.mjs record`: the snapshot plus a hash of `validation-report.md`.
1037
+ * An existing file is never refreshed — its binding must keep pointing at the
1038
+ * tree the commands actually ran on.
1039
+ */
1040
+ function ensureVerificationSnapshot(dir, agent) {
1041
+ const file = path.join(dir, 'verification.json');
1042
+ if (fs.existsSync(file)) return;
1043
+ const snapshot = gitSnapshot();
1044
+ if (!snapshot) return;
1045
+ const reportPath = path.join(dir, 'validation-report.md');
1046
+ let report = null;
1047
+ try {
1048
+ const text = fs.readFileSync(reportPath);
1049
+ report = { path: 'validation-report.md', sha256: crypto.createHash('sha256').update(text).digest('hex') };
1050
+ } catch {}
1051
+ const verification = {
1052
+ schemaVersion: 1,
1053
+ task: path.basename(dir),
1054
+ snapshot,
1055
+ report,
1056
+ commands: [],
1057
+ gate: { status: 'snapshot-only', recordedBy: agent || null, checkedAt: now },
1058
+ };
1059
+ const temporary = `${file}.${process.pid}.tmp`;
1060
+ fs.writeFileSync(temporary, JSON.stringify(verification, null, 2) + '\n');
1061
+ fs.renameSync(temporary, file);
1062
+ appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, worktreeHash: snapshot.worktreeHash, source: 'hook', attributionConfidence: 'high' });
1063
+ }
1064
+
1065
+ function verificationFreshness(dir) {
1066
+ const file = path.join(dir, 'verification.json');
1067
+ if (!fs.existsSync(file)) return { present: false };
1068
+ let verification;
1069
+ try { verification = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { present: true, fresh: false, reasons: ['unreadable'] }; }
1070
+ const snapshot = verification && verification.snapshot;
1071
+ if (!snapshot || typeof snapshot.head !== 'string') return { present: true, fresh: false, reasons: ['no-snapshot'] };
1072
+ const current = gitSnapshot();
1073
+ if (!current) return { present: true, fresh: false, reasons: ['no-git'] };
1074
+ const reasons = [];
1075
+ if (current.head !== snapshot.head) reasons.push('head-changed');
1076
+ if (current.worktreeHash !== snapshot.worktreeHash) reasons.push('worktree-changed');
1077
+ return { present: true, fresh: reasons.length === 0, reasons };
1078
+ }
1079
+
1080
+ let verificationStaleNoted = false;
1081
+
1082
+ function noteVerificationFreshness(dir, agent) {
1083
+ if (verificationStaleNoted) return;
1084
+ const freshness = verificationFreshness(dir);
1085
+ if (!freshness.present) return;
1086
+ if (freshness.fresh) return;
1087
+ verificationStaleNoted = true;
1088
+ appendMetric({ type: 'verification_stale', at: now, agent: agent || null, reasons: freshness.reasons, source: 'hook', attributionConfidence: 'high' });
1089
+ process.stderr.write(`verification evidence is stale (${freshness.reasons.join(', ')}); re-run the gate and record it before closure\n`);
1090
+ }
1091
+
988
1092
  function finishActiveAttempt(forced) {
989
1093
  const resolved = forced || resolvedAttempt(); if (!resolved) return null;
990
1094
  const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
991
1095
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
992
- 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 } : {}) });
1096
+ const usage = sanitizeUsage(hookInput.usage);
1097
+ 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 } : {}) });
1098
+ if (resolved.entry && resolved.entry.agent === 'build-verifier') { ensureVerificationSnapshot(taskDir, resolved.entry.agent); noteVerificationFreshness(taskDir, resolved.entry.agent); }
993
1099
  const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
994
1100
  }
995
1101
  function missingConsumerArtifacts() {
@@ -1019,6 +1125,7 @@ function completePipeline(statusPatch) {
1019
1125
  // task_completed is written only on this branch. A missing receipt blocks
1020
1126
  // above and must not be counted as a finished task.
1021
1127
  status.state = 'completed';
1128
+ noteVerificationFreshness(taskDir, null);
1022
1129
  completeTaskMetrics();
1023
1130
  writeStatus(statusPatch);
1024
1131
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
@@ -21,7 +21,7 @@ Typical feature with data and UI. Concrete directories and rule stems — in the
21
21
 
22
22
  ## Context hygiene
23
23
 
24
- 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.
24
+ 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.
25
25
 
26
26
  ## Iterative refinement loop
27
27
 
@@ -156,7 +156,7 @@ Replanning is a **named, auditable operation** — never a silent reorder. Trigg
156
156
 
157
157
  ## Context budget & checkpoint/resume
158
158
 
159
- 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.
159
+ 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.
160
160
 
161
161
  ## Self-review & context hygiene
162
162
 
@@ -274,9 +274,10 @@ Use Task tool or `/agent-name`. Pass: slug, artifact paths, step `scope` if set.
274
274
 
275
275
  1. Read `steps[i].model` if present; else use the agent’s frontmatter `model` (see `agents/README.md` matrix).
276
276
  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.
277
- - **`cheap`** → mechanical steps only (router, analyst, tech-writer, codebase-analyzer).
278
- - **`standard`** → implementation, verification, review, QA, contract review.
279
- - **`strong`** → architecture, security, migration, performance, mockup review. Never downgrade a `strong` step to the parent default.
277
+ - **`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`.
278
+ - **`standard`** → implementation and the other non-review specialists. `feature-developer` stays on this tier.
279
+ - **`strong`** → architecture, security, migration, performance. Never downgrade a `strong` step to the parent default, and do not put `mockup-reviewer` on `strong`.
280
+ - 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.
280
281
  - If a tier is declared but the file has no mapping, **STOP** and report `model-tier-unmapped`; do not silently inherit the parent model.
281
282
  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.
282
283
  4. Parallel steps: apply the step-level `model` to **each** agent in the array (or omit → each agent’s own frontmatter).
@@ -998,11 +998,117 @@ function reconcileStatusFromManifest(agent, step, resolved) {
998
998
  return status.state;
999
999
  }
1000
1000
 
1001
+ /**
1002
+ * Keep only the numeric usage fields and the two provenance fields. A host may
1003
+ * forward richer objects; the ledger is allowlisted so nothing unbounded or
1004
+ * secret-shaped reaches `metrics.json`.
1005
+ */
1006
+ function sanitizeUsage(value) {
1007
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
1008
+ const num = (input) => (typeof input === 'number' && Number.isFinite(input) && input >= 0 ? input : null);
1009
+ const usage = {
1010
+ input: num(value.input), output: num(value.output), reasoning: num(value.reasoning),
1011
+ cacheRead: num(value.cacheRead === undefined ? value.cached : value.cacheRead),
1012
+ cacheWrite: num(value.cacheWrite), costUsd: num(value.costUsd),
1013
+ model: typeof value.model === 'string' ? value.model.slice(0, 120) : null,
1014
+ origin: value.origin === 'estimated' ? 'estimated' : 'measured',
1015
+ };
1016
+ const reported = usage.input !== null || usage.output !== null || usage.reasoning !== null ||
1017
+ usage.cacheRead !== null || usage.cacheWrite !== null || usage.costUsd !== null;
1018
+ return reported ? usage : null;
1019
+ }
1020
+
1021
+ /**
1022
+ * Freshness of a persisted verification snapshot against the current worktree.
1023
+ * Read-only: closure warns, it never blocks on a stale snapshot.
1024
+ */
1025
+ function gitSnapshot() {
1026
+ const { spawnSync } = require('child_process');
1027
+ const git = (args) => {
1028
+ const result = spawnSync('git', args, { cwd: process.cwd(), encoding: 'utf8', timeout: 10000, maxBuffer: 32 * 1024 * 1024 });
1029
+ return result && result.status === 0 ? String(result.stdout || '') : null;
1030
+ };
1031
+ const head = git(['rev-parse', 'HEAD']);
1032
+ if (head === null) return null;
1033
+ const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']);
1034
+ const exclude = ['--', '.', ':(exclude).ai.local'];
1035
+ const statusText = git(['status', '--porcelain=v1', ...exclude]) || '';
1036
+ const diffText = git(['diff', '--binary', 'HEAD', ...exclude]) || '';
1037
+ const untracked = git(['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
1038
+ return {
1039
+ head: head.trim(),
1040
+ branch: branch === null ? null : branch.trim(),
1041
+ dirtyFiles: statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length,
1042
+ worktreeHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1043
+ capturedAt: now,
1044
+ };
1045
+ }
1046
+
1047
+ /**
1048
+ * Seed the evidence file when the verifier finishes without an explicit
1049
+ * `verification.mjs record`: the snapshot plus a hash of `validation-report.md`.
1050
+ * An existing file is never refreshed — its binding must keep pointing at the
1051
+ * tree the commands actually ran on.
1052
+ */
1053
+ function ensureVerificationSnapshot(dir, agent) {
1054
+ const file = path.join(dir, 'verification.json');
1055
+ if (fs.existsSync(file)) return;
1056
+ const snapshot = gitSnapshot();
1057
+ if (!snapshot) return;
1058
+ const reportPath = path.join(dir, 'validation-report.md');
1059
+ let report = null;
1060
+ try {
1061
+ const text = fs.readFileSync(reportPath);
1062
+ report = { path: 'validation-report.md', sha256: crypto.createHash('sha256').update(text).digest('hex') };
1063
+ } catch {}
1064
+ const verification = {
1065
+ schemaVersion: 1,
1066
+ task: path.basename(dir),
1067
+ snapshot,
1068
+ report,
1069
+ commands: [],
1070
+ gate: { status: 'snapshot-only', recordedBy: agent || null, checkedAt: now },
1071
+ };
1072
+ const temporary = `${file}.${process.pid}.tmp`;
1073
+ fs.writeFileSync(temporary, JSON.stringify(verification, null, 2) + '\n');
1074
+ fs.renameSync(temporary, file);
1075
+ appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, worktreeHash: snapshot.worktreeHash, source: 'hook', attributionConfidence: 'high' });
1076
+ }
1077
+
1078
+ function verificationFreshness(dir) {
1079
+ const file = path.join(dir, 'verification.json');
1080
+ if (!fs.existsSync(file)) return { present: false };
1081
+ let verification;
1082
+ try { verification = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { present: true, fresh: false, reasons: ['unreadable'] }; }
1083
+ const snapshot = verification && verification.snapshot;
1084
+ if (!snapshot || typeof snapshot.head !== 'string') return { present: true, fresh: false, reasons: ['no-snapshot'] };
1085
+ const current = gitSnapshot();
1086
+ if (!current) return { present: true, fresh: false, reasons: ['no-git'] };
1087
+ const reasons = [];
1088
+ if (current.head !== snapshot.head) reasons.push('head-changed');
1089
+ if (current.worktreeHash !== snapshot.worktreeHash) reasons.push('worktree-changed');
1090
+ return { present: true, fresh: reasons.length === 0, reasons };
1091
+ }
1092
+
1093
+ let verificationStaleNoted = false;
1094
+
1095
+ function noteVerificationFreshness(dir, agent) {
1096
+ if (verificationStaleNoted) return;
1097
+ const freshness = verificationFreshness(dir);
1098
+ if (!freshness.present) return;
1099
+ if (freshness.fresh) return;
1100
+ verificationStaleNoted = true;
1101
+ appendMetric({ type: 'verification_stale', at: now, agent: agent || null, reasons: freshness.reasons, source: 'hook', attributionConfidence: 'high' });
1102
+ process.stderr.write(`verification evidence is stale (${freshness.reasons.join(', ')}); re-run the gate and record it before closure\n`);
1103
+ }
1104
+
1001
1105
  function finishActiveAttempt(forced) {
1002
1106
  const resolved = forced || resolvedAttempt(); if (!resolved) return null;
1003
1107
  const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
1004
1108
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1005
- 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 } : {}) });
1109
+ const usage = sanitizeUsage(hookInput.usage);
1110
+ 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 } : {}) });
1111
+ if (resolved.entry && resolved.entry.agent === 'build-verifier') { ensureVerificationSnapshot(taskDir, resolved.entry.agent); noteVerificationFreshness(taskDir, resolved.entry.agent); }
1006
1112
  const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
1007
1113
  }
1008
1114
  function missingConsumerArtifacts() {
@@ -1032,6 +1138,7 @@ function completePipeline(statusPatch) {
1032
1138
  // task_completed is written only on this branch. A missing receipt blocks
1033
1139
  // above and must not be counted as a finished task.
1034
1140
  status.state = 'completed';
1141
+ noteVerificationFreshness(taskDir, null);
1035
1142
  completeTaskMetrics();
1036
1143
  writeStatus(statusPatch);
1037
1144
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
@@ -21,7 +21,7 @@ Typical feature with data and UI. Concrete directories and rule stems — in the
21
21
 
22
22
  ## Context hygiene
23
23
 
24
- 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.
24
+ 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.
25
25
 
26
26
  ## Iterative refinement loop
27
27
 
@@ -156,7 +156,7 @@ Replanning is a **named, auditable operation** — never a silent reorder. Trigg
156
156
 
157
157
  ## Context budget & checkpoint/resume
158
158
 
159
- 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.
159
+ 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.
160
160
 
161
161
  ## Self-review & context hygiene
162
162
 
@@ -274,9 +274,10 @@ Use Task tool or `/agent-name`. Pass: slug, artifact paths, step `scope` if set.
274
274
 
275
275
  1. Read `steps[i].model` if present; else use the agent’s frontmatter `model` (see `agents/README.md` matrix).
276
276
  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.
277
- - **`cheap`** → mechanical steps only (router, analyst, tech-writer, codebase-analyzer).
278
- - **`standard`** → implementation, verification, review, QA, contract review.
279
- - **`strong`** → architecture, security, migration, performance, mockup review. Never downgrade a `strong` step to the parent default.
277
+ - **`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`.
278
+ - **`standard`** → implementation and the other non-review specialists. `feature-developer` stays on this tier.
279
+ - **`strong`** → architecture, security, migration, performance. Never downgrade a `strong` step to the parent default, and do not put `mockup-reviewer` on `strong`.
280
+ - 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.
280
281
  - If a tier is declared but the file has no mapping, **STOP** and report `model-tier-unmapped`; do not silently inherit the parent model.
281
282
  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.
282
283
  4. Parallel steps: apply the step-level `model` to **each** agent in the array (or omit → each agent’s own frontmatter).
@@ -64,15 +64,16 @@ Default SoT — YAML `model` in each agent file. Optional `steps[].model` (`chea
64
64
 
65
65
  | Tier | Default frontmatter | Agents |
66
66
  |------|---------------------|--------|
67
- | **cheap** | `haiku` | `task-router`, `task-analyst`, `build-verifier`, `code-reviewer`, `tech-writer`, `codebase-analyzer` |
68
- | **standard** | `inherit` or `sonnet` | `feature-developer`, `debugger`, `ci-investigator`, `api-contract-reviewer`, `accessibility-reviewer`, `qa-tester`, `unit-test-*`, `playwright-test-*`, `openspec-author` (`sonnet` where already pinned) |
69
- | **strong** | `opus` | `solution-architect`, `migration-specialist`, `security-reviewer`, `performance-auditor`, `mockup-reviewer` |
67
+ | **cheap** | `haiku` | `task-router`, `task-analyst`, `build-verifier`, `code-reviewer`, `api-contract-reviewer`, `mockup-reviewer`, `tech-writer`, `codebase-analyzer` |
68
+ | **standard** | `inherit` or `sonnet` | `feature-developer`, `debugger`, `ci-investigator`, `accessibility-reviewer`, `qa-tester`, `unit-test-*`, `playwright-test-*`, `openspec-author` (`sonnet` where already pinned) |
69
+ | **strong** | `opus` | `solution-architect`, `migration-specialist`, `security-reviewer`, `performance-auditor` |
70
70
 
71
71
  **Notes**
72
72
 
73
73
  - Claude Code aliases: `haiku` / `sonnet` / `opus` / `inherit` (full IDs also OK). Cheap agents pin `haiku`; an unknown value is substituted with the parent model, so the cheap tier is not delivered. Cursor keeps its own `fast` tier, which is not a Claude alias.
74
74
  - Resolution order (Claude Code): per-invocation `model` → frontmatter `model` → env `CLAUDE_CODE_SUBAGENT_MODEL` → parent session.
75
75
  - Never put `strong` on `build-verifier` / `tech-writer` / `task-router`.
76
+ - Review-shaped reviewers (`code-reviewer`, `build-verifier`, `api-contract-reviewer`, `mockup-reviewer`) sit on `cheap` (`haiku` here). OpenCode does not pin a provider in the agent file; this repo maps `cheap` in `.ai.local/team/model-tiers.json`. The 2026-11-16 flash vs v4-pro bench on `guard-tests` (n=5) was cost −76.7% and tokens +12.3%. Its oracle checks that a test script's last line is echoed. That run did not measure code review, contract review, or mockup review, and it did not measure Cursor `fast` or Claude `haiku`.
76
77
 
77
78
  ## Orchestration
78
79
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: api-contract-reviewer
3
3
  description: API contract review specialist. Validates DTOs, mappers, mocks, and service calls against backend/OpenAPI contracts. Writes api-contract-review.md only; never edits production code.
4
- model: inherit
4
+ model: haiku
5
5
  ---
6
6
 
7
7
  ## Rules to load (subagent context)
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: mockup-reviewer
3
3
  description: Figma mockup review specialist. Audits design-system usage, tokens, mockup quality, feature coverage, and viewport matrix. Writes mockup-review.md only; never edits production code or Figma.
4
- model: opus
4
+ model: haiku
5
5
  ---
6
6
 
7
7
  ## Rules to load (subagent context)
@@ -99,7 +99,7 @@ SoT: `agent-team/task-classification` (shared-core marker above; do not invent a
99
99
  **L2-lite routing.** When `.ai.local/rules/task-levels.md` selects L2-lite:
100
100
 
101
101
  - keep `profile: standard`; do not set `full` because generated trees, snapshots, CLI goldens, docs, or test fixtures push the raw file count over 10;
102
- - keep only the risk specialists: `api-contract-reviewer` when the public contract changes, `security-reviewer` when destructive/auth-bearing, `mockup-reviewer` when `app/src/ui/**` changes;
102
+ - keep only the risk specialists: `api-contract-reviewer` when the public contract changes (skipIf no API/DTO diff), `security-reviewer` when destructive/auth-bearing, `mockup-reviewer` when `app/src/ui/**` changes (skipIf no Figma/UI surface);
103
103
  - set `humanGates` to exactly `["after:task-analyst"]`; the contract gate and review freeze the design — a second architecture gate needs a real open decision;
104
104
  - do not add `solution-architect`, `openspec-author`, or `tech-writer` unless a genuine open decision or install-surface docs require them; fold docs into the developer or one docs step;
105
105
  - count substantive files only. Record the L2-lite selection and the machine-checked gate in `routingReasons`.
@@ -149,7 +149,7 @@ Keep top-level `profile` and emit this top-level object in every new `pipeline.j
149
149
 
150
150
  ## Adjust steps (when context is clear)
151
151
 
152
- - If prompt or `brief.md` contains `figma.com` on `feature` / `refactor` / `spike` / `spec-gen`, insert **mockup-reviewer** after **task-analyst** (when present) and before **solution-architect** and **feature-developer**. Set `model: "strong"` on that step. Do not add static `humanGates: ["after:mockup-reviewer"]` (FAIL-only hook exception). Never put `mockup-reviewer` in a `parallel: true` step (FAIL-only gate is serial).
152
+ - If prompt or `brief.md` contains `figma.com` on `feature` / `refactor` / `spike` / `spec-gen`, insert **mockup-reviewer** after **task-analyst** (when present) and before **solution-architect** and **feature-developer**. Do not set `model` on that step: `mockup-reviewer` stays on its cheap frontmatter. Do not add static `humanGates: ["after:mockup-reviewer"]` (FAIL-only hook exception). Never put `mockup-reviewer` in a `parallel: true` step (FAIL-only gate is serial).
153
153
  - Classify intent `mockup-review` **before** `ux-design` **before** `review-only`. A `figma.com` URL with review-not-implement language is `mockup-review` even without the word «макет», including when the user said «ревью UX». <!-- i18n-keep: E4 -->
154
154
  - If UI stack and (required-signal or advisory UI AC), instruct **task-analyst** to load skill `ux-design` (no new pipeline step; analyst default model, not `strong`). Required-signal: user asked UX, or AC require flows/states, or spec-gen page/feature.
155
155
  - If the resolved scope touches UI paths (`app/src/ui/**`, or the repo's component-catalog root) on `feature` / `refactor`, insert **mockup-reviewer** before **feature-developer**. This includes a UI change with no `figma.com` URL; the reviewer then uses the AC / `ux-design.md`. Do not insert it when `profile` is `light` and the prompt has no `figma.com` URL and no required-signal UX AC. A `figma.com` URL still inserts **mockup-reviewer** on every profile, including `light`.
@@ -182,11 +182,11 @@ Optional per-step field: `"model": "cheap" | "standard" | "strong"`. Omit → ag
182
182
 
183
183
  | When | What to write |
184
184
  |------|----------------|
185
- | `profile: light` | set `cheap` on **all** steps (exceptions: unclear bug root cause on `debugger` → `strong`; `mockup-reviewer` always `strong`) |
185
+ | `profile: light` | set `cheap` on **all** steps (exception: unclear bug root cause on `debugger` → `strong`) |
186
186
  | `profile: standard` | omit (frontmatter defaults) |
187
187
  | `profile: full` | set `strong` on `solution-architect`, `migration-specialist`, `security-reviewer`, `performance-auditor` when present; omit others |
188
188
  | `intent: spike` | set `strong` on `solution-architect` (and analyst may stay default/`cheap`) |
189
- | `intent: perf-audit` / `mockup-review` / security-heavy feature | `strong` on auditor/reviewer step (`mockup-reviewer` never `cheap`) |
189
+ | `intent: perf-audit` / security-heavy feature | `strong` on `security-reviewer` / `performance-auditor` when that step exists. `mockup-review` does not set `strong` — `mockup-reviewer` stays cheap |
190
190
  | Always | **never** `strong` on `build-verifier`, `tech-writer`, `task-router` |
191
191
 
192
192
  Claude Code mapping when orchestrator invokes Agent tool: `cheap` → `haiku` (or rely on frontmatter `fast`); `standard` → omit / `sonnet` / inherit; `strong` → pass `opus` (or rely on frontmatter `opus`). Prefer explicit per-invocation `model` when frontmatter is unreliable.
@@ -998,11 +998,117 @@ function reconcileStatusFromManifest(agent, step, resolved) {
998
998
  return status.state;
999
999
  }
1000
1000
 
1001
+ /**
1002
+ * Keep only the numeric usage fields and the two provenance fields. A host may
1003
+ * forward richer objects; the ledger is allowlisted so nothing unbounded or
1004
+ * secret-shaped reaches `metrics.json`.
1005
+ */
1006
+ function sanitizeUsage(value) {
1007
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
1008
+ const num = (input) => (typeof input === 'number' && Number.isFinite(input) && input >= 0 ? input : null);
1009
+ const usage = {
1010
+ input: num(value.input), output: num(value.output), reasoning: num(value.reasoning),
1011
+ cacheRead: num(value.cacheRead === undefined ? value.cached : value.cacheRead),
1012
+ cacheWrite: num(value.cacheWrite), costUsd: num(value.costUsd),
1013
+ model: typeof value.model === 'string' ? value.model.slice(0, 120) : null,
1014
+ origin: value.origin === 'estimated' ? 'estimated' : 'measured',
1015
+ };
1016
+ const reported = usage.input !== null || usage.output !== null || usage.reasoning !== null ||
1017
+ usage.cacheRead !== null || usage.cacheWrite !== null || usage.costUsd !== null;
1018
+ return reported ? usage : null;
1019
+ }
1020
+
1021
+ /**
1022
+ * Freshness of a persisted verification snapshot against the current worktree.
1023
+ * Read-only: closure warns, it never blocks on a stale snapshot.
1024
+ */
1025
+ function gitSnapshot() {
1026
+ const { spawnSync } = require('child_process');
1027
+ const git = (args) => {
1028
+ const result = spawnSync('git', args, { cwd: process.cwd(), encoding: 'utf8', timeout: 10000, maxBuffer: 32 * 1024 * 1024 });
1029
+ return result && result.status === 0 ? String(result.stdout || '') : null;
1030
+ };
1031
+ const head = git(['rev-parse', 'HEAD']);
1032
+ if (head === null) return null;
1033
+ const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']);
1034
+ const exclude = ['--', '.', ':(exclude).ai.local'];
1035
+ const statusText = git(['status', '--porcelain=v1', ...exclude]) || '';
1036
+ const diffText = git(['diff', '--binary', 'HEAD', ...exclude]) || '';
1037
+ const untracked = git(['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
1038
+ return {
1039
+ head: head.trim(),
1040
+ branch: branch === null ? null : branch.trim(),
1041
+ dirtyFiles: statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length,
1042
+ worktreeHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1043
+ capturedAt: now,
1044
+ };
1045
+ }
1046
+
1047
+ /**
1048
+ * Seed the evidence file when the verifier finishes without an explicit
1049
+ * `verification.mjs record`: the snapshot plus a hash of `validation-report.md`.
1050
+ * An existing file is never refreshed — its binding must keep pointing at the
1051
+ * tree the commands actually ran on.
1052
+ */
1053
+ function ensureVerificationSnapshot(dir, agent) {
1054
+ const file = path.join(dir, 'verification.json');
1055
+ if (fs.existsSync(file)) return;
1056
+ const snapshot = gitSnapshot();
1057
+ if (!snapshot) return;
1058
+ const reportPath = path.join(dir, 'validation-report.md');
1059
+ let report = null;
1060
+ try {
1061
+ const text = fs.readFileSync(reportPath);
1062
+ report = { path: 'validation-report.md', sha256: crypto.createHash('sha256').update(text).digest('hex') };
1063
+ } catch {}
1064
+ const verification = {
1065
+ schemaVersion: 1,
1066
+ task: path.basename(dir),
1067
+ snapshot,
1068
+ report,
1069
+ commands: [],
1070
+ gate: { status: 'snapshot-only', recordedBy: agent || null, checkedAt: now },
1071
+ };
1072
+ const temporary = `${file}.${process.pid}.tmp`;
1073
+ fs.writeFileSync(temporary, JSON.stringify(verification, null, 2) + '\n');
1074
+ fs.renameSync(temporary, file);
1075
+ appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, worktreeHash: snapshot.worktreeHash, source: 'hook', attributionConfidence: 'high' });
1076
+ }
1077
+
1078
+ function verificationFreshness(dir) {
1079
+ const file = path.join(dir, 'verification.json');
1080
+ if (!fs.existsSync(file)) return { present: false };
1081
+ let verification;
1082
+ try { verification = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { present: true, fresh: false, reasons: ['unreadable'] }; }
1083
+ const snapshot = verification && verification.snapshot;
1084
+ if (!snapshot || typeof snapshot.head !== 'string') return { present: true, fresh: false, reasons: ['no-snapshot'] };
1085
+ const current = gitSnapshot();
1086
+ if (!current) return { present: true, fresh: false, reasons: ['no-git'] };
1087
+ const reasons = [];
1088
+ if (current.head !== snapshot.head) reasons.push('head-changed');
1089
+ if (current.worktreeHash !== snapshot.worktreeHash) reasons.push('worktree-changed');
1090
+ return { present: true, fresh: reasons.length === 0, reasons };
1091
+ }
1092
+
1093
+ let verificationStaleNoted = false;
1094
+
1095
+ function noteVerificationFreshness(dir, agent) {
1096
+ if (verificationStaleNoted) return;
1097
+ const freshness = verificationFreshness(dir);
1098
+ if (!freshness.present) return;
1099
+ if (freshness.fresh) return;
1100
+ verificationStaleNoted = true;
1101
+ appendMetric({ type: 'verification_stale', at: now, agent: agent || null, reasons: freshness.reasons, source: 'hook', attributionConfidence: 'high' });
1102
+ process.stderr.write(`verification evidence is stale (${freshness.reasons.join(', ')}); re-run the gate and record it before closure\n`);
1103
+ }
1104
+
1001
1105
  function finishActiveAttempt(forced) {
1002
1106
  const resolved = forced || resolvedAttempt(); if (!resolved) return null;
1003
1107
  const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
1004
1108
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1005
- 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 } : {}) });
1109
+ const usage = sanitizeUsage(hookInput.usage);
1110
+ 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 } : {}) });
1111
+ if (resolved.entry && resolved.entry.agent === 'build-verifier') { ensureVerificationSnapshot(taskDir, resolved.entry.agent); noteVerificationFreshness(taskDir, resolved.entry.agent); }
1006
1112
  const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
1007
1113
  }
1008
1114
  function missingConsumerArtifacts() {
@@ -1032,6 +1138,7 @@ function completePipeline(statusPatch) {
1032
1138
  // task_completed is written only on this branch. A missing receipt blocks
1033
1139
  // above and must not be counted as a finished task.
1034
1140
  status.state = 'completed';
1141
+ noteVerificationFreshness(taskDir, null);
1035
1142
  completeTaskMetrics();
1036
1143
  writeStatus(statusPatch);
1037
1144
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
@@ -21,7 +21,7 @@ Typical feature with data and UI. Concrete directories and rule stems — in the
21
21
 
22
22
  ## Context hygiene
23
23
 
24
- 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.
24
+ 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.
25
25
 
26
26
  ## Iterative refinement loop
27
27
 
@@ -105,7 +105,7 @@ Typical feature with backend data and shared state. Layer details — `architect
105
105
 
106
106
  ## Context hygiene
107
107
 
108
- 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 -n` or `team-db.mjs search`), and record the repo-relative `outputs/…` path in `implementation.md` or `validation-report.md` when it informed a decision. Do not read the whole output into context.
108
+ 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 -n` or `team-db.mjs search`), and record the repo-relative `outputs/…` path in `implementation.md` or `validation-report.md` when it informed a decision. 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.
109
109
 
110
110
  ## Data flow (orientation)
111
111