@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
@@ -0,0 +1,374 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Persist verification evidence for a task: the commands a verifier ran, their
4
+ * exit codes, captured log tails, and the git snapshot they were verified on.
5
+ *
6
+ * `validation-report.md` stays the human-readable narrative. This module owns
7
+ * the machine-checkable half: `<team>/tasks/<slug>/verification.json` plus
8
+ * `evidence/*.log`. `check` answers one question — is the recorded evidence
9
+ * still bound to the current worktree? — so closure cannot silently rely on a
10
+ * snapshot taken before the last edit.
11
+ *
12
+ * Usage:
13
+ * node .ai.local/scripts/verification.mjs record --task <slug|dir> \
14
+ * --command "<cmd>" --exit <n> [--log <file>] [--agent <id>] [--attempt <id>] [--json]
15
+ * node .ai.local/scripts/verification.mjs snapshot --task <slug|dir> [--json]
16
+ * node .ai.local/scripts/verification.mjs check --task <slug|dir> [--json] [--strict]
17
+ * node .ai.local/scripts/verification.mjs show --task <slug|dir> [--json]
18
+ *
19
+ * Exit codes: 0 ok, 1 stale (check --strict) or write failure, 2 usage/validation.
20
+ */
21
+ import crypto from 'node:crypto';
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { spawnSync } from 'node:child_process';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ const here = path.dirname(fileURLToPath(import.meta.url));
28
+ const DEFAULT_TEAM_ROOT = path.resolve(here, '..', 'team');
29
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
30
+ const MAX_COMMAND_CHARS = 500;
31
+ const MAX_LOG_BYTES = 64 * 1024;
32
+ const GIT_TIMEOUT_MS = 10_000;
33
+
34
+ const fail = (message, code = 2) => {
35
+ process.stderr.write(`verification: ${message}\n`);
36
+ process.exit(code);
37
+ };
38
+
39
+ const FLAGS = new Set(['--json', '--strict']);
40
+ const VALUED = new Set(['--task', '--command', '--exit', '--log', '--agent', '--attempt', '--team-root']);
41
+
42
+ const readArgs = (argv) => {
43
+ const args = {};
44
+ for (let index = 0; index < argv.length; index += 1) {
45
+ const key = argv[index];
46
+ if (key === '--help' || key === '-h') {
47
+ process.stdout.write(
48
+ 'Usage: verification.mjs <record|snapshot|check|show> --task <slug|dir> [--json]\n',
49
+ );
50
+ process.exit(0);
51
+ }
52
+ if (FLAGS.has(key)) {
53
+ args[key.slice(2)] = true;
54
+ continue;
55
+ }
56
+ if (!VALUED.has(key)) fail(`unknown argument ${key}`);
57
+ const value = argv[index + 1];
58
+ if (value === undefined) fail(`missing value for ${key}`);
59
+ args[key.slice(2)] = value;
60
+ index += 1;
61
+ }
62
+ return args;
63
+ };
64
+
65
+ const teamRootFor = (args) =>
66
+ args['team-root'] ? path.resolve(args['team-root']) : DEFAULT_TEAM_ROOT;
67
+
68
+ const taskDirFor = (args, teamRoot) => {
69
+ if (!args.task) fail('--task is required');
70
+ if (path.isAbsolute(args.task)) return args.task;
71
+ if (SLUG_RE.test(args.task)) return path.join(teamRoot, 'tasks', args.task);
72
+ return path.resolve(args.task);
73
+ };
74
+
75
+ const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
76
+
77
+ const readJson = (filePath, fallback) => {
78
+ try {
79
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
80
+ } catch {
81
+ return fallback;
82
+ }
83
+ };
84
+
85
+ const acquire = (lockFilePath) => {
86
+ for (let attempt = 0; attempt < 200; attempt += 1) {
87
+ try {
88
+ const fd = fs.openSync(lockFilePath, 'wx');
89
+ fs.writeSync(fd, `${process.pid}:${Date.now()}`);
90
+ fs.closeSync(fd);
91
+ return () => {
92
+ try {
93
+ fs.unlinkSync(lockFilePath);
94
+ } catch {
95
+ // another writer already released it
96
+ }
97
+ };
98
+ } catch (error) {
99
+ if (error.code !== 'EEXIST') fail(`cannot lock ${lockFilePath}: ${error.message}`, 1);
100
+ let stale = false;
101
+ try {
102
+ stale = Date.now() - fs.statSync(lockFilePath).mtimeMs > 30_000;
103
+ } catch {
104
+ // lock vanished; retry
105
+ }
106
+ if (stale) {
107
+ try {
108
+ fs.unlinkSync(lockFilePath);
109
+ } catch {
110
+ // another writer reclaimed it
111
+ }
112
+ }
113
+ }
114
+ }
115
+ fail(`lock timeout: ${lockFilePath}`, 1);
116
+ };
117
+
118
+ const writeJsonAtomic = (filePath, value) => {
119
+ const temporary = `${filePath}.${process.pid}.tmp`;
120
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`);
121
+ fs.renameSync(temporary, filePath);
122
+ };
123
+
124
+ const git = (root, args) => {
125
+ const result = spawnSync('git', args, {
126
+ cwd: root,
127
+ encoding: 'utf8',
128
+ timeout: GIT_TIMEOUT_MS,
129
+ maxBuffer: 32 * 1024 * 1024,
130
+ env: process.env,
131
+ });
132
+ if (result.error || result.status !== 0) return null;
133
+ return String(result.stdout ?? '');
134
+ };
135
+
136
+ /**
137
+ * Worktree snapshot. `head` and `worktreeHash` are the freshness keys: the hash
138
+ * covers tracked modifications and the untracked-name set, not untracked file
139
+ * contents (which would make the check unbounded on a dirty tree).
140
+ */
141
+ const captureSnapshot = (root) => {
142
+ const head = git(root, ['rev-parse', 'HEAD']);
143
+ if (head === null) {
144
+ return { head: null, branch: null, dirtyFiles: null, worktreeHash: null, git: false, capturedAt: new Date().toISOString() };
145
+ }
146
+ const branch = git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
147
+ // `.ai.local/` holds the evidence this module writes; including it would make
148
+ // every record instantly stale against its own snapshot.
149
+ const exclude = ['--', '.', ':(exclude).ai.local'];
150
+ const statusText = git(root, ['status', '--porcelain=v1', ...exclude]) ?? '';
151
+ const diffText = git(root, ['diff', '--binary', 'HEAD', ...exclude]) ?? '';
152
+ const untrackedText = git(root, ['ls-files', '--others', '--exclude-standard', ...exclude]) ?? '';
153
+ const dirtyFiles = statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length;
154
+ return {
155
+ head: head.trim(),
156
+ branch: branch === null ? null : branch.trim(),
157
+ dirtyFiles,
158
+ worktreeHash: sha256(`${statusText}\u0000${diffText}\u0000${untrackedText}`),
159
+ git: true,
160
+ capturedAt: new Date().toISOString(),
161
+ };
162
+ };
163
+
164
+ const SECRET_RE =
165
+ /(-----BEGIN [A-Z ]+PRIVATE KEY-----|authorization:\s*bearer\s+[A-Za-z0-9._-]{10,}|(?:api[_-]?key|token|secret|password)\s*[:=]\s*\S{8,})/i;
166
+
167
+ const redact = (text) =>
168
+ text
169
+ .replace(/(authorization:\s*bearer\s+)\S+/gi, '$1[redacted]')
170
+ .replace(/((?:api[_-]?key|token|secret|password)\s*[:=]\s*)\S+/gi, '$1[redacted]');
171
+
172
+ const appendMetricsEvent = (taskDir, event) => {
173
+ const metricsPath = path.join(taskDir, 'metrics.json');
174
+ if (!fs.existsSync(metricsPath)) return;
175
+ const release = acquire(`${metricsPath}.lock`);
176
+ try {
177
+ const metrics = readJson(metricsPath, null);
178
+ if (!metrics || !Array.isArray(metrics.events)) return;
179
+ const runId = metrics.task && typeof metrics.task.runId === 'string' ? metrics.task.runId : 'run';
180
+ metrics.events.push({
181
+ eventId: `${runId}:verification:${Date.now()}:${crypto.randomBytes(4).toString('hex')}`,
182
+ source: 'agent',
183
+ attributionConfidence: 'high',
184
+ ...event,
185
+ });
186
+ writeJsonAtomic(metricsPath, metrics);
187
+ } finally {
188
+ release();
189
+ }
190
+ };
191
+
192
+ const loadVerification = (taskDir) => {
193
+ const file = path.join(taskDir, 'verification.json');
194
+ const value = readJson(file, null);
195
+ if (!value || value.schemaVersion !== 1 || !Array.isArray(value.commands)) return null;
196
+ return value;
197
+ };
198
+
199
+ const snapshotFile = (taskDir) => {
200
+ const dir = path.join(taskDir, 'evidence');
201
+ fs.mkdirSync(dir, { recursive: true });
202
+ return dir;
203
+ };
204
+
205
+ /**
206
+ * Copy the tail of a command log into the task's evidence directory with
207
+ * secret-shaped values redacted. The stored file is capped, so a huge log never
208
+ * lands in the artifact tree.
209
+ */
210
+ const captureLog = (taskDir, logPath, seq) => {
211
+ let raw;
212
+ try {
213
+ raw = fs.readFileSync(logPath);
214
+ } catch (error) {
215
+ fail(`cannot read --log ${logPath}: ${error.message}`);
216
+ }
217
+ const tail = raw.subarray(Math.max(0, raw.length - MAX_LOG_BYTES));
218
+ const text = redact(tail.toString('utf8').replace(/\u0000/g, ''));
219
+ const evidenceDir = snapshotFile(taskDir);
220
+ const name = `verification-${seq}.log`;
221
+ fs.writeFileSync(path.join(evidenceDir, name), text);
222
+ return { logRef: `evidence/${name}`, logSha256: sha256(text) };
223
+ };
224
+
225
+ const formatHuman = (verification) => {
226
+ const commands = verification.commands
227
+ .map((entry) => ` ${entry.id} exit=${entry.exit} ${entry.command}`)
228
+ .join('\n');
229
+ return [
230
+ `verification: ${verification.task} snapshot=${verification.snapshot.head ?? 'no-git'} dirty=${verification.snapshot.dirtyFiles ?? '-'}`,
231
+ commands,
232
+ ]
233
+ .filter(Boolean)
234
+ .join('\n');
235
+ };
236
+
237
+ const actionRecord = (args) => {
238
+ const teamRoot = teamRootFor(args);
239
+ const taskDir = taskDirFor(args, teamRoot);
240
+ if (!fs.existsSync(taskDir)) fail(`task directory does not exist: ${taskDir}`, 1);
241
+ const command = String(args.command ?? '').trim();
242
+ if (command === '') fail('--command is required');
243
+ if (command.length > MAX_COMMAND_CHARS) fail(`--command exceeds ${MAX_COMMAND_CHARS} characters`);
244
+ if (SECRET_RE.test(command)) fail('--command looks like it carries a secret; pass a redacted command line');
245
+ const exitCode = Number(args.exit);
246
+ if (!Number.isInteger(exitCode) || exitCode < 0) fail('--exit must be a non-negative integer');
247
+
248
+ const file = path.join(taskDir, 'verification.json');
249
+ const release = acquire(`${file}.lock`);
250
+ let verification;
251
+ let entry;
252
+ try {
253
+ verification = loadVerification(taskDir) ?? {
254
+ schemaVersion: 1,
255
+ task: path.basename(taskDir),
256
+ snapshot: null,
257
+ commands: [],
258
+ gate: { status: 'recorded', checkedAt: null },
259
+ };
260
+ const seq = verification.commands.length + 1;
261
+ const log = args.log ? captureLog(taskDir, args.log, seq) : null;
262
+ entry = {
263
+ id: `cmd-${seq}`,
264
+ command,
265
+ exit: exitCode,
266
+ at: new Date().toISOString(),
267
+ agent: args.agent ?? null,
268
+ attempt: args.attempt ?? null,
269
+ ...(log ?? {}),
270
+ };
271
+ verification.commands.push(entry);
272
+ verification.task = path.basename(taskDir);
273
+ verification.snapshot = captureSnapshot(path.resolve(teamRoot, '..', '..'));
274
+ verification.gate = { status: 'recorded', checkedAt: new Date().toISOString() };
275
+ writeJsonAtomic(file, verification);
276
+ } finally {
277
+ release();
278
+ }
279
+
280
+ appendMetricsEvent(taskDir, {
281
+ type: 'verification_recorded',
282
+ at: entry.at,
283
+ commandId: entry.id,
284
+ exit: entry.exit,
285
+ agent: entry.agent,
286
+ attempt: entry.attempt,
287
+ head: verification.snapshot.head,
288
+ worktreeHash: verification.snapshot.worktreeHash,
289
+ });
290
+
291
+ if (args.json) {
292
+ process.stdout.write(`${JSON.stringify({ ok: true, task: verification.task, command: entry, snapshot: verification.snapshot })}\n`);
293
+ return;
294
+ }
295
+ process.stdout.write(`verification: recorded ${entry.id} exit=${entry.exit} for ${verification.task}\n`);
296
+ };
297
+
298
+ const actionSnapshot = (args) => {
299
+ const teamRoot = teamRootFor(args);
300
+ const taskDir = taskDirFor(args, teamRoot);
301
+ if (!fs.existsSync(taskDir)) fail(`task directory does not exist: ${taskDir}`, 1);
302
+ const file = path.join(taskDir, 'verification.json');
303
+ const release = acquire(`${file}.lock`);
304
+ let verification;
305
+ try {
306
+ verification = loadVerification(taskDir) ?? {
307
+ schemaVersion: 1,
308
+ task: path.basename(taskDir),
309
+ commands: [],
310
+ gate: { status: 'recorded', checkedAt: null },
311
+ };
312
+ verification.snapshot = captureSnapshot(path.resolve(teamRoot, '..', '..'));
313
+ writeJsonAtomic(file, verification);
314
+ } finally {
315
+ release();
316
+ }
317
+ if (args.json) {
318
+ process.stdout.write(`${JSON.stringify({ ok: true, snapshot: verification.snapshot })}\n`);
319
+ return;
320
+ }
321
+ process.stdout.write(`verification: snapshot ${verification.snapshot.head ?? 'no-git'} dirty=${verification.snapshot.dirtyFiles ?? '-'}\n`);
322
+ };
323
+
324
+ const actionCheck = (args) => {
325
+ const teamRoot = teamRootFor(args);
326
+ const taskDir = taskDirFor(args, teamRoot);
327
+ const verification = loadVerification(taskDir);
328
+ if (!verification) {
329
+ if (args.json) process.stdout.write(`${JSON.stringify({ fresh: false, reason: 'missing' })}\n`);
330
+ else process.stdout.write('verification: missing\n');
331
+ process.exit(args.strict ? 2 : 0);
332
+ }
333
+ const current = captureSnapshot(path.resolve(teamRoot, '..', '..'));
334
+ const reasons = [];
335
+ if (!verification.snapshot) reasons.push('no-snapshot');
336
+ else {
337
+ if (verification.snapshot.head !== current.head) reasons.push('head-changed');
338
+ if (verification.snapshot.worktreeHash !== current.worktreeHash) reasons.push('worktree-changed');
339
+ }
340
+ if (verification.commands.length === 0) reasons.push('no-command-evidence');
341
+ const fresh = reasons.length === 0;
342
+ const result = { fresh, reasons, recordedHead: verification.snapshot?.head ?? null, currentHead: current.head };
343
+ if (args.json) process.stdout.write(`${JSON.stringify(result)}\n`);
344
+ else {
345
+ process.stdout.write(
346
+ fresh
347
+ ? `verification: fresh (${verification.commands.length} command(s))\n`
348
+ : `verification: stale (${reasons.join(', ')})\n`,
349
+ );
350
+ }
351
+ if (!fresh && args.strict) process.exit(1);
352
+ };
353
+
354
+ const actionShow = (args) => {
355
+ const teamRoot = teamRootFor(args);
356
+ const taskDir = taskDirFor(args, teamRoot);
357
+ const verification = loadVerification(taskDir);
358
+ if (!verification) fail(`no verification.json for ${path.basename(taskDir)}`, 1);
359
+ process.stdout.write(
360
+ args.json ? `${JSON.stringify(verification, null, 2)}\n` : `${formatHuman(verification)}\n`,
361
+ );
362
+ };
363
+
364
+ const main = () => {
365
+ const [action] = process.argv.slice(2);
366
+ const args = readArgs(process.argv.slice(3));
367
+ if (action === 'record') actionRecord(args);
368
+ else if (action === 'snapshot') actionSnapshot(args);
369
+ else if (action === 'check') actionCheck(args);
370
+ else if (action === 'show') actionShow(args);
371
+ else fail(`unknown action ${action ?? '(none)'}; use record|snapshot|check|show`);
372
+ };
373
+
374
+ main();
@@ -16,7 +16,7 @@ Each pipeline run owns `<team>/tasks/<slug>/metrics.json`:
16
16
 
17
17
  `events` is append-only. A task is one `runId`; a subtask is one invocation of `pipeline.steps[i]`. Every invocation has an `attemptId`, including each member of a parallel step. Events inherit the immutable task dimensions rather than duplicating them.
18
18
 
19
- Allowed event types are `task_started`, `attempt_started`, `attempt_finished`, `retry_scheduled`, `attempt_skipped`, `human_gate_started`, `human_gate_ended`, `pipeline_parse_error`, `task_completed`, `profile_changed`, `out_of_band_started`, `out_of_band_finished`, and the parallel events `parallel_wave_started`, `step_joined`, `parallel_attribution_repair`, `parallel_conflict_deferred`.
19
+ Allowed event types are `task_started`, `attempt_started`, `attempt_finished`, `retry_scheduled`, `attempt_skipped`, `human_gate_started`, `human_gate_ended`, `pipeline_parse_error`, `task_completed`, `profile_changed`, `out_of_band_started`, `out_of_band_finished`, `usage_recorded`, `verification_recorded`, `verification_stale`, and the parallel events `parallel_wave_started`, `step_joined`, `parallel_attribution_repair`, `parallel_conflict_deferred`.
20
20
 
21
21
  Outcome values, with their actual emission site:
22
22
 
@@ -57,3 +57,63 @@ A **wave** is the scheduling unit: one `parallel: true` step, or (in graph mode)
57
57
  - `parallel_attribution_repair` marks a stop the payload could not attribute that a fallback rule bound (`attemptIds[]`, `attributionConfidence: "fallback"`).
58
58
  - `parallel_conflict_deferred` marks a ready step the hook deferred because the ready set was not conflict-free or a member lacked declared scopes (`stepIndex`, `deferredStepIndexes[]`, `reason`). The hook defers and logs; it never blocks and never stalls.
59
59
  - Attribution always prefers the active attempt or an explicit receipt; `currentAgent` is only a third disambiguator and is always marked `fallback`.
60
+
61
+ ## Token usage
62
+
63
+ Tokens are optional evidence, never an estimate. A missing record stays missing
64
+ (`null`), not `0`; a token kind nobody reported stays `null` as well.
65
+
66
+ Two write paths exist, in precedence order:
67
+
68
+ 1. **Host object.** When the host exposes counts, put a `usage` object on the
69
+ `attempt_finished` receipt (the chain hook forwards `hookInput.usage`). The
70
+ hook allowlists the shape before the ledger sees it:
71
+ `{ input, output, reasoning, cacheRead, cacheWrite, costUsd, model, origin }`
72
+ — numbers are non-negative integers (or `null`), `model` is capped at 120
73
+ characters, `origin` is `measured` unless the host says `estimated`.
74
+ 2. **`usage_recorded` events.** When only some turns are observable, append one
75
+ event per turn next to the attempt (writer: `record-usage.mjs`):
76
+
77
+ ```bash
78
+ node .ai.local/scripts/record-usage.mjs --task <slug> --attempt <attemptId> \
79
+ --input <n> --output <n> [--cached <n>] [--cache-write <n>] [--reasoning <n>] \
80
+ [--turn <turnId>] [--model <id>]
81
+ ```
82
+
83
+ The projection collapses events per `turn` (latest wins) and sums the
84
+ survivors. A host object wins over `usage_recorded` rows for the same
85
+ attempt; the two are never added together.
86
+
87
+ `aggregate-agent-task-metrics.mjs` reports `usage` at the task, agent, and model
88
+ level with an explicit coverage ratio (`reportedAttempts / attempts`). Read a
89
+ partial coverage as "some turns were observable", never as a cost baseline.
90
+
91
+ ## Verification evidence
92
+
93
+ `validation-report.md` stays the human-readable narrative. The machine-checkable
94
+ half is `<team>/tasks/<slug>/verification.json` plus `evidence/*.log`, written by
95
+ the verifier with `verification.mjs`:
96
+
97
+ ```bash
98
+ node .ai.local/scripts/verification.mjs record --task <slug> \
99
+ --command "<exact command>" --exit <code> [--log <file>] [--agent <id>] [--attempt <attemptId>]
100
+ node .ai.local/scripts/verification.mjs check --task <slug> [--strict]
101
+ ```
102
+
103
+ - `record` appends one command entry (`id`, `command`, `exit`, `at`, optional
104
+ `logRef`/`logSha256`), stores a capped, secret-redacted log tail under
105
+ `evidence/`, and snapshots the git state (`head`, `branch`, `dirtyFiles`,
106
+ `worktreeHash`). `.ai.local/**` is excluded from the snapshot.
107
+ - `check` compares the stored snapshot with the current worktree:
108
+ `head-changed` / `worktree-changed` mean the evidence belongs to an older
109
+ tree. `--strict` exits `1` when stale and `2` when missing.
110
+ - When a `build-verifier` attempt finishes without an explicit `record`, the
111
+ chain hook seeds the file once (`gate.status: snapshot-only`): the git snapshot
112
+ plus a SHA-256 of `validation-report.md`, with `commands: []`. An existing file
113
+ is never refreshed, so its binding keeps pointing at the tree the commands ran
114
+ on.
115
+ - The chain hook warns at closure when a `verification.json` is stale and writes
116
+ one `verification_stale` event (`reasons[]`). It never blocks: re-running the
117
+ gate is the fix, not a new approval.
118
+ - `verification_recorded` marks each persisted command in the ledger; command
119
+ text stays out of `metrics.json`.
@@ -145,7 +145,7 @@ Replanning is a **named, auditable operation** — never a silent reorder. Trigg
145
145
 
146
146
  ## Context budget & checkpoint/resume
147
147
 
148
- 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.
148
+ 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.
149
149
 
150
150
  ## Self-review & context hygiene
151
151
 
@@ -263,9 +263,10 @@ Use Task tool or `/agent-name`. Pass: slug, artifact paths, step `scope` if set.
263
263
 
264
264
  1. Read `steps[i].model` if present; else use the agent’s frontmatter `model` (see `agents/README.md` matrix).
265
265
  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.
266
- - **`cheap`** → mechanical steps only (router, analyst, tech-writer, codebase-analyzer).
267
- - **`standard`** → implementation, verification, review, QA, contract review.
268
- - **`strong`** → architecture, security, migration, performance, mockup review. Never downgrade a `strong` step to the parent default.
266
+ - **`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`.
267
+ - **`standard`** → implementation and the other non-review specialists. `feature-developer` stays on this tier.
268
+ - **`strong`** → architecture, security, migration, performance. Never downgrade a `strong` step to the parent default, and do not put `mockup-reviewer` on `strong`.
269
+ - 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.
269
270
  - If a tier is declared but the file has no mapping, **STOP** and report `model-tier-unmapped`; do not silently inherit the parent model.
270
271
  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.
271
272
  4. Parallel steps: apply the step-level `model` to **each** agent in the array (or omit → each agent’s own frontmatter).
@@ -0,0 +1,47 @@
1
+ # Incident registry
2
+
3
+ Durable memory for agent-pipeline failures. A task finding is local and dies
4
+ with the slug; the registry keeps the failure class, the rule that should have
5
+ prevented it, and the evidence, until either the class is promoted or archived.
6
+
7
+ Writer: `.ai.local/scripts/incidents.mjs`. Store:
8
+ `<team>/incidents.jsonl` — one record per line, append-only.
9
+
10
+ ## Record shape
11
+
12
+ `incident` rows carry `id`, `at`, `signature`, `state`, `title`, `scope`,
13
+ `failure`, `rule`, `advice`, `task`, `tags`, `evidence[]`. `state` rows carry
14
+ `id`, `at`, `state`, and the promotion fields (`enforcement`, `rulePath`).
15
+ Current state is the latest `state` row, defaulting to `open`.
16
+
17
+ `signature` is derived from `scope | failure | rule` (normalized, hashed), so the
18
+ same class recorded from two tasks lands in one recurrence group. Secrets are
19
+ rejected at write time; evidence is a reference (path + anchor, command id,
20
+ incident id), never a log body.
21
+
22
+ ## Stabilization threshold
23
+
24
+ An incident is **stabilized** when the same signature occurs at least **twice in
25
+ 30 days** (`check --window-days` overrides the window). One occurrence is a
26
+ finding, not a rule.
27
+
28
+ ## Promotion
29
+
30
+ Only a stabilized incident can be promoted, and promotion requires a named
31
+ enforcement — `ci`, `test`, `lint`, or `policy-check`. Enforcement is the reason
32
+ the rule will not silently rot; a rule without one is documentation, not a gate.
33
+
34
+ `promote <id> --enforcement <kind> [--stem <kebab>]` writes an **inactive draft**
35
+ to `.ai.local/rules-library/<stem>.md` and appends the state row. A human moves
36
+ the file into `.ai.local/rules/` to activate it — the registry never edits active
37
+ rules, and the overlay's envelope caps still apply.
38
+
39
+ ## Use
40
+
41
+ - After a retro or a repeated agent mistake: `incidents.mjs record`.
42
+ - Before a similar task: `incidents.mjs advise --query "<symptom>"` — targeted
43
+ lookup, never a bulk load.
44
+ - Periodic review: `incidents.mjs check` (stabilized groups), then
45
+ `incidents.mjs promote`, `archive`, or leave `open`.
46
+
47
+ Archiving keeps the line, removes it from advice, and preserves the history.
@@ -14,7 +14,7 @@ Typical feature with data and UI. Concrete directories and rule stems — in the
14
14
 
15
15
  ## Context hygiene
16
16
 
17
- 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.
17
+ 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.
18
18
 
19
19
  ## Iterative refinement loop
20
20
 
@@ -961,11 +961,117 @@ function reconcileStatusFromManifest(agent, step, resolved) {
961
961
  return status.state;
962
962
  }
963
963
 
964
+ /**
965
+ * Keep only the numeric usage fields and the two provenance fields. A host may
966
+ * forward richer objects; the ledger is allowlisted so nothing unbounded or
967
+ * secret-shaped reaches `metrics.json`.
968
+ */
969
+ function sanitizeUsage(value) {
970
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
971
+ const num = (input) => (typeof input === 'number' && Number.isFinite(input) && input >= 0 ? input : null);
972
+ const usage = {
973
+ input: num(value.input), output: num(value.output), reasoning: num(value.reasoning),
974
+ cacheRead: num(value.cacheRead === undefined ? value.cached : value.cacheRead),
975
+ cacheWrite: num(value.cacheWrite), costUsd: num(value.costUsd),
976
+ model: typeof value.model === 'string' ? value.model.slice(0, 120) : null,
977
+ origin: value.origin === 'estimated' ? 'estimated' : 'measured',
978
+ };
979
+ const reported = usage.input !== null || usage.output !== null || usage.reasoning !== null ||
980
+ usage.cacheRead !== null || usage.cacheWrite !== null || usage.costUsd !== null;
981
+ return reported ? usage : null;
982
+ }
983
+
984
+ /**
985
+ * Freshness of a persisted verification snapshot against the current worktree.
986
+ * Read-only: closure warns, it never blocks on a stale snapshot.
987
+ */
988
+ function gitSnapshot() {
989
+ const { spawnSync } = require('child_process');
990
+ const git = (args) => {
991
+ const result = spawnSync('git', args, { cwd: process.cwd(), encoding: 'utf8', timeout: 10000, maxBuffer: 32 * 1024 * 1024 });
992
+ return result && result.status === 0 ? String(result.stdout || '') : null;
993
+ };
994
+ const head = git(['rev-parse', 'HEAD']);
995
+ if (head === null) return null;
996
+ const branch = git(['rev-parse', '--abbrev-ref', 'HEAD']);
997
+ const exclude = ['--', '.', ':(exclude).ai.local'];
998
+ const statusText = git(['status', '--porcelain=v1', ...exclude]) || '';
999
+ const diffText = git(['diff', '--binary', 'HEAD', ...exclude]) || '';
1000
+ const untracked = git(['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
1001
+ return {
1002
+ head: head.trim(),
1003
+ branch: branch === null ? null : branch.trim(),
1004
+ dirtyFiles: statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length,
1005
+ worktreeHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1006
+ capturedAt: now,
1007
+ };
1008
+ }
1009
+
1010
+ /**
1011
+ * Seed the evidence file when the verifier finishes without an explicit
1012
+ * `verification.mjs record`: the snapshot plus a hash of `validation-report.md`.
1013
+ * An existing file is never refreshed — its binding must keep pointing at the
1014
+ * tree the commands actually ran on.
1015
+ */
1016
+ function ensureVerificationSnapshot(dir, agent) {
1017
+ const file = path.join(dir, 'verification.json');
1018
+ if (fs.existsSync(file)) return;
1019
+ const snapshot = gitSnapshot();
1020
+ if (!snapshot) return;
1021
+ const reportPath = path.join(dir, 'validation-report.md');
1022
+ let report = null;
1023
+ try {
1024
+ const text = fs.readFileSync(reportPath);
1025
+ report = { path: 'validation-report.md', sha256: crypto.createHash('sha256').update(text).digest('hex') };
1026
+ } catch {}
1027
+ const verification = {
1028
+ schemaVersion: 1,
1029
+ task: path.basename(dir),
1030
+ snapshot,
1031
+ report,
1032
+ commands: [],
1033
+ gate: { status: 'snapshot-only', recordedBy: agent || null, checkedAt: now },
1034
+ };
1035
+ const temporary = `${file}.${process.pid}.tmp`;
1036
+ fs.writeFileSync(temporary, JSON.stringify(verification, null, 2) + '\n');
1037
+ fs.renameSync(temporary, file);
1038
+ appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, worktreeHash: snapshot.worktreeHash, source: 'hook', attributionConfidence: 'high' });
1039
+ }
1040
+
1041
+ function verificationFreshness(dir) {
1042
+ const file = path.join(dir, 'verification.json');
1043
+ if (!fs.existsSync(file)) return { present: false };
1044
+ let verification;
1045
+ try { verification = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { present: true, fresh: false, reasons: ['unreadable'] }; }
1046
+ const snapshot = verification && verification.snapshot;
1047
+ if (!snapshot || typeof snapshot.head !== 'string') return { present: true, fresh: false, reasons: ['no-snapshot'] };
1048
+ const current = gitSnapshot();
1049
+ if (!current) return { present: true, fresh: false, reasons: ['no-git'] };
1050
+ const reasons = [];
1051
+ if (current.head !== snapshot.head) reasons.push('head-changed');
1052
+ if (current.worktreeHash !== snapshot.worktreeHash) reasons.push('worktree-changed');
1053
+ return { present: true, fresh: reasons.length === 0, reasons };
1054
+ }
1055
+
1056
+ let verificationStaleNoted = false;
1057
+
1058
+ function noteVerificationFreshness(dir, agent) {
1059
+ if (verificationStaleNoted) return;
1060
+ const freshness = verificationFreshness(dir);
1061
+ if (!freshness.present) return;
1062
+ if (freshness.fresh) return;
1063
+ verificationStaleNoted = true;
1064
+ appendMetric({ type: 'verification_stale', at: now, agent: agent || null, reasons: freshness.reasons, source: 'hook', attributionConfidence: 'high' });
1065
+ process.stderr.write(`verification evidence is stale (${freshness.reasons.join(', ')}); re-run the gate and record it before closure\n`);
1066
+ }
1067
+
964
1068
  function finishActiveAttempt(forced) {
965
1069
  const resolved = forced || resolvedAttempt(); if (!resolved) return null;
966
1070
  const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
967
1071
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
968
- 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 } : {}) });
1072
+ const usage = sanitizeUsage(hookInput.usage);
1073
+ 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 } : {}) });
1074
+ if (resolved.entry && resolved.entry.agent === 'build-verifier') { ensureVerificationSnapshot(taskDir, resolved.entry.agent); noteVerificationFreshness(taskDir, resolved.entry.agent); }
969
1075
  const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
970
1076
  }
971
1077
  function missingConsumerArtifacts() {
@@ -995,6 +1101,7 @@ function completePipeline(statusPatch) {
995
1101
  // task_completed is written only on this branch. A missing receipt blocks
996
1102
  // above and must not be counted as a finished task.
997
1103
  status.state = 'completed';
1104
+ noteVerificationFreshness(taskDir, null);
998
1105
  completeTaskMetrics();
999
1106
  writeStatus(statusPatch);
1000
1107
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);