@bonesofspring/ai-rules 0.2.74 → 0.2.76

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 (301) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +2 -2
  3. package/bin/lib/engine-scripts.js +4 -0
  4. package/docs/TEAM-DB.md +10 -0
  5. package/docs/TOKEN-ECONOMY.md +18 -5
  6. package/package.json +2 -2
  7. package/presets/_shared/ai-local/scripts/check-write-scope.mjs +56 -26
  8. package/presets/_shared/ai-local/scripts/lock.mjs +103 -30
  9. package/presets/_shared/ai-local/scripts/rule-improver.mjs +4 -0
  10. package/presets/_shared/ai-local/scripts/run-compact.mjs +132 -0
  11. package/presets/_shared/ai-local/scripts/signals.mjs +3 -1
  12. package/presets/_shared/ai-local/scripts/team-db-api.mjs +7 -2
  13. package/presets/_shared/ai-local/scripts/team-db-project.mjs +276 -1
  14. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +32 -2
  15. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +99 -0
  16. package/presets/_shared/ai-local/scripts/team-db-task-runner.mjs +3 -1
  17. package/presets/_shared/core/agent-team/agent-task-metrics.md +29 -0
  18. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +1 -1
  19. package/presets/_shared/core/meta/preset-pr-checklist.md +2 -2
  20. package/presets/_shared/core/quality/context-and-iteration.md +1 -1
  21. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +4 -1
  22. package/presets/_shared/hooks/compact-shell-output.mjs +68 -0
  23. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +4 -1
  24. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  25. package/presets/claude/android-kotlin/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  26. package/presets/claude/android-kotlin/team/README.md +1 -1
  27. package/presets/claude/go/hooks/chain-team-phases.sh +4 -1
  28. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  29. package/presets/claude/go/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  30. package/presets/claude/go/team/README.md +1 -1
  31. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +4 -1
  32. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  33. package/presets/claude/ios-swift/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  34. package/presets/claude/ios-swift/team/README.md +1 -1
  35. package/presets/claude/java/hooks/chain-team-phases.sh +4 -1
  36. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  37. package/presets/claude/java/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  38. package/presets/claude/java/team/README.md +1 -1
  39. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +4 -1
  40. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  41. package/presets/claude/mcp-ts/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  42. package/presets/claude/mcp-ts/team/README.md +1 -1
  43. package/presets/claude/mol/hooks/chain-team-phases.sh +4 -1
  44. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  45. package/presets/claude/mol/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  46. package/presets/claude/mol/team/README.md +1 -1
  47. package/presets/claude/next/agents/build-verifier.md +1 -1
  48. package/presets/claude/next/agents/code-reviewer.md +2 -0
  49. package/presets/claude/next/hooks/chain-team-phases.sh +4 -1
  50. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  51. package/presets/claude/next/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  52. package/presets/claude/next/team/README.md +1 -1
  53. package/presets/claude/nuxt/hooks/chain-team-phases.sh +4 -1
  54. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  55. package/presets/claude/nuxt/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  56. package/presets/claude/nuxt/team/README.md +1 -1
  57. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  58. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  59. package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  60. package/presets/claude/php-hexagonal/team/README.md +1 -1
  61. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +4 -1
  62. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  63. package/presets/claude/php-laravel/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  64. package/presets/claude/php-laravel/team/README.md +1 -1
  65. package/presets/claude/svelte/hooks/chain-team-phases.sh +4 -1
  66. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  67. package/presets/claude/svelte/rules/tooling-and-review/preset-pr-checklist.md +2 -2
  68. package/presets/claude/svelte/team/README.md +1 -1
  69. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +4 -1
  70. package/presets/cursor/android-kotlin/hooks/compact-shell-output.mjs +68 -0
  71. package/presets/cursor/android-kotlin/hooks.json +7 -0
  72. package/presets/cursor/android-kotlin/rules/preset-pr-checklist.mdc +2 -2
  73. package/presets/cursor/android-kotlin/team/README.md +1 -1
  74. package/presets/cursor/go/hooks/chain-team-phases.sh +4 -1
  75. package/presets/cursor/go/hooks/compact-shell-output.mjs +68 -0
  76. package/presets/cursor/go/hooks.json +7 -0
  77. package/presets/cursor/go/rules/preset-pr-checklist.mdc +2 -2
  78. package/presets/cursor/go/team/README.md +1 -1
  79. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +4 -1
  80. package/presets/cursor/ios-swift/hooks/compact-shell-output.mjs +68 -0
  81. package/presets/cursor/ios-swift/hooks.json +7 -0
  82. package/presets/cursor/ios-swift/rules/preset-pr-checklist.mdc +2 -2
  83. package/presets/cursor/ios-swift/team/README.md +1 -1
  84. package/presets/cursor/java/hooks/chain-team-phases.sh +4 -1
  85. package/presets/cursor/java/hooks/compact-shell-output.mjs +68 -0
  86. package/presets/cursor/java/hooks.json +7 -0
  87. package/presets/cursor/java/rules/preset-pr-checklist.mdc +2 -2
  88. package/presets/cursor/java/team/README.md +1 -1
  89. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +4 -1
  90. package/presets/cursor/mcp-ts/hooks/compact-shell-output.mjs +68 -0
  91. package/presets/cursor/mcp-ts/hooks.json +7 -0
  92. package/presets/cursor/mcp-ts/rules/preset-pr-checklist.mdc +2 -2
  93. package/presets/cursor/mcp-ts/team/README.md +1 -1
  94. package/presets/cursor/mol/hooks/chain-team-phases.sh +4 -1
  95. package/presets/cursor/mol/hooks/compact-shell-output.mjs +68 -0
  96. package/presets/cursor/mol/hooks.json +7 -0
  97. package/presets/cursor/mol/rules/preset-pr-checklist.mdc +2 -2
  98. package/presets/cursor/mol/team/README.md +1 -1
  99. package/presets/cursor/next/agents/build-verifier.md +1 -1
  100. package/presets/cursor/next/agents/code-reviewer.md +2 -0
  101. package/presets/cursor/next/hooks/chain-team-phases.sh +4 -1
  102. package/presets/cursor/next/hooks/compact-shell-output.mjs +68 -0
  103. package/presets/cursor/next/hooks.json +7 -0
  104. package/presets/cursor/next/rules/preset-pr-checklist.mdc +2 -2
  105. package/presets/cursor/next/team/README.md +1 -1
  106. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +4 -1
  107. package/presets/cursor/nuxt/hooks/compact-shell-output.mjs +68 -0
  108. package/presets/cursor/nuxt/hooks.json +7 -0
  109. package/presets/cursor/nuxt/rules/preset-pr-checklist.mdc +2 -2
  110. package/presets/cursor/nuxt/team/README.md +1 -1
  111. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  112. package/presets/cursor/php-hexagonal/hooks/compact-shell-output.mjs +68 -0
  113. package/presets/cursor/php-hexagonal/hooks.json +7 -0
  114. package/presets/cursor/php-hexagonal/rules/preset-pr-checklist.mdc +2 -2
  115. package/presets/cursor/php-hexagonal/team/README.md +1 -1
  116. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +4 -1
  117. package/presets/cursor/php-laravel/hooks/compact-shell-output.mjs +68 -0
  118. package/presets/cursor/php-laravel/hooks.json +7 -0
  119. package/presets/cursor/php-laravel/rules/preset-pr-checklist.mdc +2 -2
  120. package/presets/cursor/php-laravel/team/README.md +1 -1
  121. package/presets/cursor/svelte/hooks/chain-team-phases.sh +4 -1
  122. package/presets/cursor/svelte/hooks/compact-shell-output.mjs +68 -0
  123. package/presets/cursor/svelte/hooks.json +7 -0
  124. package/presets/cursor/svelte/rules/preset-pr-checklist.mdc +2 -2
  125. package/presets/cursor/svelte/team/README.md +1 -1
  126. package/presets/mavis/android-kotlin/adapter-map.json +9 -1
  127. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +4 -1
  128. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  129. package/presets/mavis/android-kotlin/rules/preset-pr-checklist.md +2 -2
  130. package/presets/mavis/android-kotlin/team/README.md +1 -1
  131. package/presets/mavis/go/adapter-map.json +9 -1
  132. package/presets/mavis/go/hooks/chain-team-phases.sh +4 -1
  133. package/presets/mavis/go/rules/agent-team-orchestrator.md +1 -1
  134. package/presets/mavis/go/rules/preset-pr-checklist.md +2 -2
  135. package/presets/mavis/go/team/README.md +1 -1
  136. package/presets/mavis/ios-swift/adapter-map.json +9 -1
  137. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +4 -1
  138. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +1 -1
  139. package/presets/mavis/ios-swift/rules/preset-pr-checklist.md +2 -2
  140. package/presets/mavis/ios-swift/team/README.md +1 -1
  141. package/presets/mavis/java/adapter-map.json +9 -1
  142. package/presets/mavis/java/hooks/chain-team-phases.sh +4 -1
  143. package/presets/mavis/java/rules/agent-team-orchestrator.md +1 -1
  144. package/presets/mavis/java/rules/preset-pr-checklist.md +2 -2
  145. package/presets/mavis/java/team/README.md +1 -1
  146. package/presets/mavis/mcp-ts/adapter-map.json +9 -1
  147. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +4 -1
  148. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  149. package/presets/mavis/mcp-ts/rules/preset-pr-checklist.md +2 -2
  150. package/presets/mavis/mcp-ts/team/README.md +1 -1
  151. package/presets/mavis/mol/adapter-map.json +9 -1
  152. package/presets/mavis/mol/hooks/chain-team-phases.sh +4 -1
  153. package/presets/mavis/mol/rules/agent-team-orchestrator.md +1 -1
  154. package/presets/mavis/mol/rules/preset-pr-checklist.md +2 -2
  155. package/presets/mavis/mol/team/README.md +1 -1
  156. package/presets/mavis/next/adapter-map.json +9 -1
  157. package/presets/mavis/next/agents/build-verifier.md +1 -1
  158. package/presets/mavis/next/agents/code-reviewer.md +2 -0
  159. package/presets/mavis/next/hooks/chain-team-phases.sh +4 -1
  160. package/presets/mavis/next/rules/agent-team-orchestrator.md +1 -1
  161. package/presets/mavis/next/rules/preset-pr-checklist.md +2 -2
  162. package/presets/mavis/next/team/README.md +1 -1
  163. package/presets/mavis/nuxt/adapter-map.json +9 -1
  164. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +4 -1
  165. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +1 -1
  166. package/presets/mavis/nuxt/rules/preset-pr-checklist.md +2 -2
  167. package/presets/mavis/nuxt/team/README.md +1 -1
  168. package/presets/mavis/php-hexagonal/adapter-map.json +9 -1
  169. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  170. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  171. package/presets/mavis/php-hexagonal/rules/preset-pr-checklist.md +2 -2
  172. package/presets/mavis/php-hexagonal/team/README.md +1 -1
  173. package/presets/mavis/php-laravel/adapter-map.json +9 -1
  174. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +4 -1
  175. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +1 -1
  176. package/presets/mavis/php-laravel/rules/preset-pr-checklist.md +2 -2
  177. package/presets/mavis/php-laravel/team/README.md +1 -1
  178. package/presets/mavis/svelte/adapter-map.json +9 -1
  179. package/presets/mavis/svelte/hooks/chain-team-phases.sh +4 -1
  180. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +1 -1
  181. package/presets/mavis/svelte/rules/preset-pr-checklist.md +2 -2
  182. package/presets/mavis/svelte/team/README.md +1 -1
  183. package/presets/opencode/android-kotlin/adapter-map.json +9 -1
  184. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +4 -1
  185. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  186. package/presets/opencode/android-kotlin/rules/preset-pr-checklist.md +2 -2
  187. package/presets/opencode/android-kotlin/team/README.md +1 -1
  188. package/presets/opencode/go/adapter-map.json +9 -1
  189. package/presets/opencode/go/hooks/chain-team-phases.sh +4 -1
  190. package/presets/opencode/go/rules/agent-team-orchestrator.md +1 -1
  191. package/presets/opencode/go/rules/preset-pr-checklist.md +2 -2
  192. package/presets/opencode/go/team/README.md +1 -1
  193. package/presets/opencode/ios-swift/adapter-map.json +9 -1
  194. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +4 -1
  195. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +1 -1
  196. package/presets/opencode/ios-swift/rules/preset-pr-checklist.md +2 -2
  197. package/presets/opencode/ios-swift/team/README.md +1 -1
  198. package/presets/opencode/java/adapter-map.json +9 -1
  199. package/presets/opencode/java/hooks/chain-team-phases.sh +4 -1
  200. package/presets/opencode/java/rules/agent-team-orchestrator.md +1 -1
  201. package/presets/opencode/java/rules/preset-pr-checklist.md +2 -2
  202. package/presets/opencode/java/team/README.md +1 -1
  203. package/presets/opencode/mcp-ts/adapter-map.json +9 -1
  204. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +4 -1
  205. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  206. package/presets/opencode/mcp-ts/rules/preset-pr-checklist.md +2 -2
  207. package/presets/opencode/mcp-ts/team/README.md +1 -1
  208. package/presets/opencode/mol/adapter-map.json +9 -1
  209. package/presets/opencode/mol/hooks/chain-team-phases.sh +4 -1
  210. package/presets/opencode/mol/rules/agent-team-orchestrator.md +1 -1
  211. package/presets/opencode/mol/rules/preset-pr-checklist.md +2 -2
  212. package/presets/opencode/mol/team/README.md +1 -1
  213. package/presets/opencode/next/adapter-map.json +9 -1
  214. package/presets/opencode/next/agents/build-verifier.md +1 -1
  215. package/presets/opencode/next/agents/code-reviewer.md +2 -0
  216. package/presets/opencode/next/hooks/chain-team-phases.sh +4 -1
  217. package/presets/opencode/next/rules/agent-team-orchestrator.md +1 -1
  218. package/presets/opencode/next/rules/preset-pr-checklist.md +2 -2
  219. package/presets/opencode/next/team/README.md +1 -1
  220. package/presets/opencode/nuxt/adapter-map.json +9 -1
  221. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +4 -1
  222. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +1 -1
  223. package/presets/opencode/nuxt/rules/preset-pr-checklist.md +2 -2
  224. package/presets/opencode/nuxt/team/README.md +1 -1
  225. package/presets/opencode/php-hexagonal/adapter-map.json +9 -1
  226. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  227. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  228. package/presets/opencode/php-hexagonal/rules/preset-pr-checklist.md +2 -2
  229. package/presets/opencode/php-hexagonal/team/README.md +1 -1
  230. package/presets/opencode/php-laravel/adapter-map.json +9 -1
  231. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +4 -1
  232. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +1 -1
  233. package/presets/opencode/php-laravel/rules/preset-pr-checklist.md +2 -2
  234. package/presets/opencode/php-laravel/team/README.md +1 -1
  235. package/presets/opencode/plugins/output-guard/README.md +3 -2
  236. package/presets/opencode/plugins/output-guard/rewrite.ts +10 -1
  237. package/presets/opencode/svelte/adapter-map.json +9 -1
  238. package/presets/opencode/svelte/hooks/chain-team-phases.sh +4 -1
  239. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +1 -1
  240. package/presets/opencode/svelte/rules/preset-pr-checklist.md +2 -2
  241. package/presets/opencode/svelte/team/README.md +1 -1
  242. package/presets/zcode/android-kotlin/adapter-map.json +9 -1
  243. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +4 -1
  244. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  245. package/presets/zcode/android-kotlin/rules/preset-pr-checklist.md +2 -2
  246. package/presets/zcode/android-kotlin/team/README.md +1 -1
  247. package/presets/zcode/go/adapter-map.json +9 -1
  248. package/presets/zcode/go/hooks/chain-team-phases.sh +4 -1
  249. package/presets/zcode/go/rules/agent-team-orchestrator.md +1 -1
  250. package/presets/zcode/go/rules/preset-pr-checklist.md +2 -2
  251. package/presets/zcode/go/team/README.md +1 -1
  252. package/presets/zcode/ios-swift/adapter-map.json +9 -1
  253. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +4 -1
  254. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +1 -1
  255. package/presets/zcode/ios-swift/rules/preset-pr-checklist.md +2 -2
  256. package/presets/zcode/ios-swift/team/README.md +1 -1
  257. package/presets/zcode/java/adapter-map.json +9 -1
  258. package/presets/zcode/java/hooks/chain-team-phases.sh +4 -1
  259. package/presets/zcode/java/rules/agent-team-orchestrator.md +1 -1
  260. package/presets/zcode/java/rules/preset-pr-checklist.md +2 -2
  261. package/presets/zcode/java/team/README.md +1 -1
  262. package/presets/zcode/mcp-ts/adapter-map.json +9 -1
  263. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +4 -1
  264. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  265. package/presets/zcode/mcp-ts/rules/preset-pr-checklist.md +2 -2
  266. package/presets/zcode/mcp-ts/team/README.md +1 -1
  267. package/presets/zcode/mol/adapter-map.json +9 -1
  268. package/presets/zcode/mol/hooks/chain-team-phases.sh +4 -1
  269. package/presets/zcode/mol/rules/agent-team-orchestrator.md +1 -1
  270. package/presets/zcode/mol/rules/preset-pr-checklist.md +2 -2
  271. package/presets/zcode/mol/team/README.md +1 -1
  272. package/presets/zcode/next/adapter-map.json +9 -1
  273. package/presets/zcode/next/agents/build-verifier.md +1 -1
  274. package/presets/zcode/next/agents/code-reviewer.md +2 -0
  275. package/presets/zcode/next/hooks/chain-team-phases.sh +4 -1
  276. package/presets/zcode/next/rules/agent-team-orchestrator.md +1 -1
  277. package/presets/zcode/next/rules/preset-pr-checklist.md +2 -2
  278. package/presets/zcode/next/team/README.md +1 -1
  279. package/presets/zcode/nuxt/adapter-map.json +9 -1
  280. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +4 -1
  281. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +1 -1
  282. package/presets/zcode/nuxt/rules/preset-pr-checklist.md +2 -2
  283. package/presets/zcode/nuxt/team/README.md +1 -1
  284. package/presets/zcode/php-hexagonal/adapter-map.json +9 -1
  285. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +4 -1
  286. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  287. package/presets/zcode/php-hexagonal/rules/preset-pr-checklist.md +2 -2
  288. package/presets/zcode/php-hexagonal/team/README.md +1 -1
  289. package/presets/zcode/php-laravel/adapter-map.json +9 -1
  290. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +4 -1
  291. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +1 -1
  292. package/presets/zcode/php-laravel/rules/preset-pr-checklist.md +2 -2
  293. package/presets/zcode/php-laravel/team/README.md +1 -1
  294. package/presets/zcode/svelte/adapter-map.json +9 -1
  295. package/presets/zcode/svelte/hooks/chain-team-phases.sh +4 -1
  296. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +1 -1
  297. package/presets/zcode/svelte/rules/preset-pr-checklist.md +2 -2
  298. package/presets/zcode/svelte/team/README.md +1 -1
  299. package/scripts/close-agent-task-human-gate.mjs +3 -3
  300. package/scripts/report-context-cost.mjs +10 -3
  301. package/scripts/aggregate-agent-task-metrics.mjs +0 -480
package/CHANGELOG.md CHANGED
@@ -1,5 +1,70 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.76
4
+
5
+ ### `preset` — guard accounting reads every ledger generation
6
+
7
+ - **Two ratios, one numerator.** `report-efficiency.mjs` prints `all calls` (25.2% of measured traffic) beside `replaced only` (76.7% of the outputs the guard rewrote). `report-context-cost.mjs` prints only the second, now labelled "of replaced bytes" with a pointer to the all-calls figure, and its JSON carries `scope: "replaced"`. The 48× gap between the two reports was a denominator, not a contradiction: `stats.jsonl` receives a row only for `result.changed`.
8
+ - **Rotation is a window, not a loss.** The report reads `results*.jsonl` and `usage*.jsonl` oldest archive first, so the 8 MiB rotation of `results.1.jsonl` no longer hides ~96% of the measured calls; rows still dedupe by `(sessionID, callID)` and `(sessionID, messageID)`.
9
+ - **One byte instrument.** The bench takes `rawBytes` from the run stream and `returnedBytes` as that total minus the ledger's measured savings. Before, the on arm's denominator came from the ledger, which never sees a tool result produced after the last `context` hook — a zero-replacement run read 6,991 B against 6,196 B. Records gain `savedBytes` and `unobservedBytes`; deltas gain `rawBytesPct`.
10
+ - **`--rescore`.** `bench-efficiency.mjs --rescore <run-dir>` rebuilds a matrix from `runs/<run>/run.json` plus each run's ledger, without a model call, and writes `efficiency.rescored.{json,md}`. Artifacts written before the `replaced` field existed regain their real counts: `bench/runs/20261117T070906Z` becomes `inconclusive` (0 replacements), bench-v2 becomes `adopt` with 12.
11
+ - **Schema 3.** The verdict reason names the replacement count, and `report-efficiency` treats any `schemaVersion >= 2` as the session-token definition instead of pinning `2`.
12
+
13
+ ### `engine` — large test and git output stays on disk
14
+
15
+ - **Cursor `preToolUse`.** An eligible simple `test`, `lint`, `git log`, or `git diff` command is rewritten to `run-compact.mjs` when `TEAM_TASK_SLUG` is set. The child exit code is preserved. Payloads over 4096 bytes keep the failure lines in context; the full output stays in `outputs/`. Pipelines, quoted arguments, and commands without a slug are not rewritten. The hook fails open.
16
+
17
+ ### `engine` — a live reclaimer keeps its guard
18
+
19
+ - **Identity, not age.** `removeStaleGuard` deleted `<lock>.d.reclaim` and the preset-tree `<lock>.reclaim` once the directory was older than 30s. A reclaimer still inside that guard lost it, and the next contender created a second one. A guard now carries `owner.json` (pid + token). A live pid is never removed, a dead pid is removed on the next attempt, and an owner-less directory still waits out the 30s window. Removal renames that directory aside and deletes it only when the renamed inode and owner are the ones just evaluated.
20
+
21
+ ### `preset` — session token total includes cache
22
+
23
+ - **Schema 2.** The efficiency bench `schemaVersion` is 2 because `medianTokens` now includes cache read and cache write. `report:efficiency --bench` keeps the old token column titles and prints that those totals exclude cache when the file's `schemaVersion` is not 2.
24
+
25
+ ### `team` — the write-scope audit skips what it cannot attribute
26
+
27
+ - **Skip, not fail.** `check-write-scope.mjs` reconciles one step's paths against that step's `writeScopes`. With no step baseline it audited the whole uncommitted change-set and hard-failed an implementation step on paths that belong to earlier steps or to another task in the same worktree — the live `agent-action-telemetry` verdict was `baseline: null` with 7 foreign paths. It now skips with `skipReason: no-baseline` (exit `3`, the same "skip, not a failure" contract a legacy pipeline already had) and prints the labelled change-set as suspects, so no evidence is lost and no step fails on writes it cannot own. An empty change-set still reconciles to a pass.
28
+ - **Escape hatches keep their verdict.** `--paths` (the caller's authoritative list) and `--base <ref>` (a committed change-set) are explicit requests and still hard-fail an out-of-scope implementation write.
29
+ - **Orchestration.** `build-verifier` and `code-reviewer` read exit `3` as a skip, and a `no-baseline` skip as an orchestration defect: the orchestrator saves the step baseline (`--step <id> --save-baseline`) before the step writes and re-runs the audit.
30
+ - **A step without an id is not auditable.** Auto-selection took any step with `writeScopes`, but the baseline is keyed by `id`: `--save-baseline` exited `2` and the audit then labelled the whole uncommitted change-set as that step's surface — the attribution error the baseline exists to prevent. Selection now requires an `id`, and a pipeline whose only scoped steps lack one skips with `no-step-ids` (exit `3`).
31
+ - **The recovery hint is runnable.** `no-step-ids` named `team-db.mjs migrate-tasks`, which projects task folders into SQLite and never rewrites `pipeline.json`. It now names the task-router regeneration the hook itself prescribes, then `/task-continue`.
32
+ - **Exit `2` is in the contract.** `build-verifier`, `code-reviewer`, and the orchestrator rule listed `0`/`1`/`3` only. Exit `2` is a usage error (unknown `--step`, unreadable `pipeline.json`, failed git ref): the audit did not run, so it is neither a pass nor a finding.
33
+ - **The skip report keeps its surface.** A `no-baseline` skip printed `step.writeScopes: []` in JSON even though it classified the change-set against those scopes. The report now echoes the resolved scopes, so a skip and a pass describe the same surface.
34
+
35
+ ### `preset` — the generator accepts the Cursor output-guard hook
36
+
37
+ - **Unmapped source.** The new Cursor `preToolUse` rewrite (`hooks/compact-shell-output.mjs`) had no `OMIT` entry in the Mavis, OpenCode, and ZCode generators, so `fix:generated` and `check:generated-drift` stopped with `unmapped cursor source` and no stack could be regenerated. The three generators omit it with a platform reason; the adapter maps and the CLI goldens (stale since the same change) were regenerated.
38
+
39
+ ### `team-db` — behavior research joins calls to attempts
40
+
41
+ - **Migration `0007-behavior-research`.** `tool_calls.attempt_id` plus an `(attempt_id, observed_at)` index, the `attempt_episodes` table, and a `task_quality` view (`failed | rework | met | unverified`). Every column is nullable and the episode table starts empty, so a v6 file migrates in place. `met` requires `task_completed` and `verification_recorded` with no `verification_stale`, `rework` is any `changes_requested`, `failed` is `blocked` or `validation_failed` with no `task_completed`, and a task still running stays `null`.
42
+ - **Binding.** A full `sync` (no `--slug`) binds a `lease` or `window` call to the attempt whose window contains it: an `agent` match outranks the narrowest window, then the later start. `dir-mtime` and `unmapped` stay unbound, and a stored row moves to a stronger rung only.
43
+ - **Episodes and gaps.** One episode per attempt, capped at 40 ordered `(intent, target_key, error_class)` steps — the target stays the existing hash, never a path or command text. An empty `gap_ms` is filled from the previous call in the same session when the gap is at most 30 minutes; `duration_ms` stays `null` unless the host measured it.
44
+ - **Session usage.** `usage_source: session` is written only when neither the host nor the CLI reported usage: the projector sums the `usage_turns` the lease or window rung already mapped onto the attempt and records `usage_turn_count`. A host rollup replaces it on the next full projection.
45
+ - **Instant lease.** A lease file with no grown `firstSeenAt` stretches to the attempt span of its slug, at most seven days either side, then clips at the next lease of that session; the chain hook keeps a previous `updatedAt` as the window start.
46
+ - **Smaller joins.** `retry_scheduled.nextAgent` projects as the attempt `agent` when no `agent` is present, and the learning ledger accepts the `exemplar` kind without the rule improver turning it into a rule.
47
+ - **Tests.** The schema, projector, and concurrency suites cover the migration, the view labels, the join, and the `nextAgent` fallback.
48
+
49
+ ### `team-db` — `serve` and `schedule` reload a newer schema
50
+
51
+ - **The cached module is not the file.** `serve` and `schedule` kept the `team-db-schema.mjs` they loaded at startup, so a version raised on disk by another process made every cached open fail with `E_SCHEMA_NEWER` until a restart. A request and an idle scheduler tick now re-import the file when its mtime is newer and its `SCHEMA_VERSION` is higher; the scheduler waits for in-flight drains and logs `reloaded schema vN`. A database newer than the file on disk still fails closed.
52
+
53
+ ### `team` — a runner `cwd` resolves against `team/`
54
+
55
+ - **Relative to the declaring file.** `runner.json` `cwd` resolved against the repository root, so the seeded `../..` pointed above it. It now resolves against `team/`, an absolute path is taken as is, and either form is refused with `E_VALIDATION` when it leaves the repository root.
56
+
57
+ ### `preset` — the self-review gate covers every loop module
58
+
59
+ - **One child-process pattern.** `check-preset-self-review-contract.sh` exempted `lock.mjs` from `CHILD_PROCESS_PATTERNS` and listed neither `run-compact.mjs` nor `rr-scheduler-start.mjs`, which spawn the command they wrap. The pattern now covers every loop module, both spawners are named, and a fixture asserts that a spawn in `lock.mjs` fails the gate.
60
+
61
+ ### `preset` — install and closure upkeep
62
+
63
+ - **Shipped aggregator path.** `aggregate-agent-task-metrics.mjs` leaves `scripts/` and ships from `presets/_shared/ai-local/scripts/`; `files` points at the copy that already exists, and the metrics hook fixtures follow the move.
64
+ - **`zcode` in the wrappers.** `close-agent-task-human-gate.mjs` accepts `--platform zcode`, and the PR checklist lists `sync-dogfood-zcode.sh` beside the other dogfood scripts.
65
+ - **Claude rules block.** `fix-generated.mjs` runs `inject-claude-agent-rules-block.mjs`, the repair arm for `check-claude-agent-blocks.mjs`, because the Claude agents are hand-maintained.
66
+ - **Structure fixtures.** `check-preset-structure.sh` runs `test-preset-token-budget-baseline.mjs` and `test-close-agent-task-human-gate.mjs`.
67
+
3
68
  ## 0.2.74
4
69
 
5
70
  ### `team` — per-task agent action telemetry
package/README.md CHANGED
@@ -25,7 +25,7 @@ Run `init` from the **app root** (`--cwd` if needed). Default `--preset` is `nex
25
25
  | Root agents | `REPO_AGENTS.md` → `AGENTS.md` (same file on all five; ZCode loads it natively) | | | | |
26
26
  | `/task` artifacts | **`.ai.local/team/`** (shared; templates refreshed; `tasks/<slug>/` never overwritten) | | | |
27
27
  | Template drift | **`.ai.local/.template-base.json`** (shared; one record per tree of files that hold a shipped template byte; `update` prints one drift line, `update --merge-ai-local` fast-forwards a file only when its recorded base still matches and reports the rest) | | | |
28
- | Self-learning engine | **`.ai.local/scripts/`** (shared; twenty-seven published scripts — the six self-learning engine modules, `manifest.mjs`, `dump-output.mjs`, the eight `team-db*.mjs` modules, `action-signals.mjs`, `actions-report.mjs`, `check-write-scope.mjs`, `aggregate-agent-task-metrics.mjs`, `record-usage.mjs`, `verification.mjs`, `incidents.mjs`, `processes.mjs`, `process-lease.mjs`, `rr-scheduler-start.mjs`, and `tracker-planned-drain.mjs`; existing files never overwritten. The repository-only `upstream-research.mjs` is not published) | | | |
28
+ | Self-learning engine | **`.ai.local/scripts/`** (shared; twenty-eight published scripts — the six self-learning engine modules, `manifest.mjs`, `dump-output.mjs`, `run-compact.mjs`, the eight `team-db*.mjs` modules, `action-signals.mjs`, `actions-report.mjs`, `check-write-scope.mjs`, `aggregate-agent-task-metrics.mjs`, `record-usage.mjs`, `verification.mjs`, `incidents.mjs`, `processes.mjs`, `process-lease.mjs`, `rr-scheduler-start.mjs`, and `tracker-planned-drain.mjs`; existing files never overwritten. The repository-only `upstream-research.mjs` is not published) | | | |
29
29
  | Specs seed | `docs/specs/` copied only if the directory is **absent** | | | |
30
30
 
31
31
  OpenCode also ships **`.opencode/plugins/task-status/`**, a TUI sidebar for the active `/task` run (slug, state, elapsed time, step, remaining-time estimate, soft-stop). OpenCode auto-loads it; it needs no `opencode.json` entry, is refreshed by `update`, and is a viewer only — the chain hook stays manual.
@@ -244,7 +244,7 @@ Every installed preset ships requestable `anti-hallucination-contract` (not alwa
244
244
  - Overlay: [`docs/LOCAL-OVERLAY.md`](docs/LOCAL-OVERLAY.md)
245
245
  - MCP setup: [`docs/MCP-SETUP.md`](docs/MCP-SETUP.md)
246
246
  - MCP catalog: [`docs/MCP-CATALOG.md`](docs/MCP-CATALOG.md)
247
- - Dogfood: [`scripts/sync-dogfood-cursor.sh`](scripts/sync-dogfood-cursor.sh), [`scripts/sync-dogfood-claude.sh`](scripts/sync-dogfood-claude.sh), [`scripts/sync-dogfood-mavis.sh`](scripts/sync-dogfood-mavis.sh), [`scripts/sync-dogfood-opencode.sh`](scripts/sync-dogfood-opencode.sh) — seeds `.ai.local/team`, preserves slugs
247
+ - Dogfood: [`scripts/sync-dogfood-cursor.sh`](scripts/sync-dogfood-cursor.sh), [`scripts/sync-dogfood-claude.sh`](scripts/sync-dogfood-claude.sh), [`scripts/sync-dogfood-mavis.sh`](scripts/sync-dogfood-mavis.sh), [`scripts/sync-dogfood-opencode.sh`](scripts/sync-dogfood-opencode.sh), [`scripts/sync-dogfood-zcode.sh`](scripts/sync-dogfood-zcode.sh) — seeds `.ai.local/team`, preserves slugs
248
248
  - Gates: loop `yarn check:task <slug>` (or `yarn check:changed` on a clean tree) + the gates it names; release `yarn release:gate`
249
249
 
250
250
  `_shared` is not an installable `--preset`.
@@ -41,6 +41,10 @@ const ENGINE_SCRIPTS = [
41
41
  // `.ai.local/team/tasks/<slug>/outputs/` file plus a head, so a large dump
42
42
  // never enters the context window. Reads no network and spawns nothing.
43
43
  'dump-output.mjs',
44
+ // Spawns an eligible command, stores the combined output through dump-output,
45
+ // prints failure lines when the payload exceeds 4096 bytes, and exits with
46
+ // the child status.
47
+ 'run-compact.mjs',
44
48
  'team-db.mjs',
45
49
  'team-db-tracker.mjs',
46
50
  'team-db-task-runner.mjs',
package/docs/TEAM-DB.md CHANGED
@@ -296,6 +296,11 @@ or `metrics.json`. The seeded config is:
296
296
  Replace `runner` only when the host CLI differs; the argv array may use `{promptFile}`,
297
297
  `{taskSlug}` or `{teamRoot}`, never a shell string.
298
298
 
299
+ A relative `cwd` resolves against `team/` — the directory that holds the file — so the
300
+ seeded `../..` is the repository root. An absolute path is taken as is; either way the
301
+ resolved directory must stay inside the repository root, or the start is refused with
302
+ `E_VALIDATION`.
303
+
299
304
  **Import envelope (D-8).** `tracker import --file <path|->` reads a versioned envelope
300
305
  `{ schemaVersion: 1, source: { task, generatedAt }, items: [...] }`, validates every item
301
306
  as one transaction (a failure writes nothing), upserts by id, writes nothing on `--dry-run`,
@@ -520,6 +525,11 @@ gains ten columns (`intent`, `agent`, `parent_session_id`, `duration_ms`, `gap_m
520
525
  file opens and migrates in place without a row copy; a v6 file is refused by a v5 binary with
521
526
  `E_SCHEMA_NEWER`. There is no downgrade SQL: delete `team.db*` and run `sync`.
522
527
 
528
+ `serve` and `schedule` keep the schema module they loaded at startup. When `team-db-schema.mjs`
529
+ on disk is replaced by a higher `SCHEMA_VERSION`, the next request and the next idle scheduler
530
+ tick re-import that file and open with it. A database newer than the file on disk still fails
531
+ closed with `E_SCHEMA_NEWER`; the running process does not rebuild it.
532
+
523
533
  Attribution is now a four-rung ladder, and the rung is stored on the row. A session lease
524
534
  carries `firstSeenAt` and a refreshed `updatedAt`, and the projector maps a row observed at `t`
525
535
  in session `s` as `lease` when `t` falls in `[first, last + 30 min]` clipped at the next lease
@@ -53,6 +53,7 @@ Example run, 2026-11-13; file lists elided; task bytes move as a task grows.
53
53
  "outputGuard": {
54
54
  "present": true,
55
55
  "file": ".ai.local/team/output-guard/stats.jsonl",
56
+ "scope": "replaced",
56
57
  "events": 10,
57
58
  "invalid": 0,
58
59
  "beforeBytes": 113996,
@@ -69,21 +70,22 @@ Example run, 2026-11-13; file lists elided; task bytes move as a task grows.
69
70
 
70
71
  `tasks` sums every file under `.ai.local/team/tasks/<slug>`, `archive/` included. A missing team directory returns `tasks: []`.
71
72
 
72
- `outputGuard` reads `.ai.local/team/output-guard/stats.jsonl`, written by the OpenCode output guard. Rows are deduped by `path` because a plugin reload re-records a historical result. `savedRatio` is the byte saving on the replaced tool results, not a session-token claim; `invalid` counts unreadable rows. A missing file returns `present: false` and zeros.
73
+ `outputGuard` reads `.ai.local/team/output-guard/stats.jsonl`, written by the OpenCode output guard. Rows are deduped by `path` because a plugin reload re-records a historical result. `stats.jsonl` holds **only the outputs the guard rewrote**, so `savedRatio` is the compression of that replaced subset, printed as "of replaced bytes" — never a share of all tool traffic; `invalid` counts unreadable rows (or the absence of one); a missing file returns `present: false` and zeros.
73
74
 
74
75
  ## Effectiveness (separate report)
75
76
 
76
77
  This report measures **fixed inputs**. It does not measure a session. The output guard writes two more ledgers under `.ai.local/team/output-guard/`:
77
78
 
78
- - `results.jsonl` — every tool result, replaced or not (the denominator);
79
- - `usage.jsonl` — one row per assistant step, from the OpenCode `ctx.session.context` tokens and cost.
79
+ - `results.jsonl` — every tool result, replaced or not (the denominator), rotated at 8 MiB into `results.1.jsonl` and `results.2.jsonl`;
80
+ - `usage.jsonl` — one row per assistant step, from the OpenCode `ctx.session.context` tokens and cost, rotated the same way.
80
81
 
81
- `report-efficiency.mjs` reads both and prints measured tool bytes, input/output/reasoning/cache tokens, cost, turns, and quality. `bench-efficiency.mjs` runs an A/B (guard off/on) through `opencode run --standalone` with a deterministic oracle and writes `efficiency.json`; `report-efficiency --bench <file>` merges it. The byte percentage is always labelled as tool-result bytes, never as a token saving.
82
+ `report-efficiency.mjs` reads **every generation** of both ledgers (`results*.jsonl`, `usage*.jsonl`), oldest archive first, so rotation is not a lost window; rows dedupe by `(sessionID, callID)` and `(sessionID, messageID)`. It prints two byte ratios because they answer different questions: `all calls` — what a session pays over every tool result — and `replaced only` — the guard's candidate set, the ratio `report-context-cost.mjs` prints from `stats.jsonl`. Both ratios share the same numerator: every saved byte comes from a replaced call. Session tokens are input + cache read + cache write + output + reasoning. The bench median and tokenDelta use that sum. Prompt growth per turn stays input + cache read + cache write. A flat tokenDelta still adopts; the reason line says flat, and a flat delta is not a saving. A bench file whose `schemaVersion` is below 2 keeps the old token column titles and a line that those totals exclude cache. `bench-efficiency.mjs` runs an A/B (guard off/on) through `opencode run --standalone` with a deterministic oracle and writes `efficiency.json`; `report-efficiency --bench <file>` merges it. Bench bytes use one instrument: `rawBytes` from the run stream, `returnedBytes` = that stream total minus the ledger's measured savings; the ledger alone undercounts (it never sees a tool result produced after the last `context` hook). A cell that replaced nothing is `inconclusive` whatever its token delta. `bench-efficiency --rescore <run-dir>` rebuilds a matrix from `runs/<run>/run.json` plus each run's ledger, so a pre-`replaced` artifact gains its real replacement count. The byte percentage is always labelled as tool-result bytes, never as a token saving.
82
83
 
83
84
  ```bash
84
85
  yarn report:efficiency
85
86
  yarn report:efficiency --html /tmp/efficiency.html
86
87
  yarn bench:efficiency --model <provider/model> --runs 3
88
+ yarn bench:efficiency --rescore bench/runs/20261117T070906Z
87
89
  ```
88
90
 
89
91
  The A/B needs `--runs 5` for a verdict; `--runs 1` is a smoke. Each run starts a private server, so the arm env (`AI_RULES_OUTPUT_GUARD=0|1`) applies without touching the shared server.
@@ -109,4 +111,15 @@ Re-run the command for the current tree; these numbers move with any rule edit.
109
111
 
110
112
  ## Next steps
111
113
 
112
- WP2…WP5 — externalize and search, prompt byte cap, PreToolUse size deny, `focus.md` pointer budget — are planned in `.ai.local/team/tasks/context-mode-token-economy/archive/2026-11-13/architecture.md` §4.
114
+ Results over 20 KB take the flat replacement. Its `grep` term comes from the bytes between the head and the tail, the same rule as the 8–20 KB band. The trigger stays 8192 bytes. The preview stays 2048 bytes of head and 1024 bytes of tail.
115
+
116
+ `focus.md` lists at most five incomplete entries (`MAX_FOCUS_ENTRIES = 5` in `chain-team-phases.sh`).
117
+
118
+ Kept out on purpose:
119
+
120
+ - The trigger stays 8192. It does not drop to 4096.
121
+ - The preview stays a head and a tail. It does not drop to a 96-byte return.
122
+ - Whole-file `Read` is not denied at 16 KiB. Source the agent reads is larger than that.
123
+ - Tool output is not indexed in FTS, and there is no sandboxed `ctx_execute`.
124
+
125
+ The bench task `middle-token` places the secret after the 2048-byte head and before the 1024-byte tail of a payload over 20 KB. A retrieval that inlines the matching line, or a `Read` deny, waits on that task failing with the guard on.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bonesofspring/ai-rules",
3
- "version": "0.2.74",
3
+ "version": "0.2.76",
4
4
  "description": "Presets of Cursor, Claude, Mavis, OpenCode, and ZCode rules/commands for Revy Ross personal use",
5
5
  "license": "MIT",
6
6
  "author": "Revy Ross",
@@ -34,7 +34,7 @@
34
34
  "!presets/*/next/team/upstream/**",
35
35
  "presets/_shared/ai-local/scripts/check-write-scope.mjs",
36
36
  "scripts/check-product-specs.sh",
37
- "scripts/aggregate-agent-task-metrics.mjs",
37
+ "presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs",
38
38
  "scripts/close-agent-task-human-gate.mjs",
39
39
  "scripts/report-context-cost.mjs"
40
40
  ],
@@ -23,7 +23,12 @@
23
23
  * 2. `--base <ref>` — a committed change-set.
24
24
  * 3. The step baseline written by `--save-baseline` (agents never commit, so
25
25
  * `HEAD` alone would attribute every earlier step to the current one).
26
- * 4. `HEAD` — the whole uncommitted change-set, reported with a notice.
26
+ * 4. No step baseline — the whole uncommitted change-set cannot be attributed to
27
+ * this step, so the audit skips (exit `3`) and reports the change-set as
28
+ * suspects; an empty change-set reconciles to a pass.
29
+ *
30
+ * Automatic selection only considers steps with an `id`, because the baseline
31
+ * file is keyed by it; a scoped step without an id is a `no-step-ids` skip.
27
32
  *
28
33
  * A step baseline records every dirty path with its content hash; the audit
29
34
  * keeps a path only when it is new since the baseline or when its content
@@ -55,8 +60,9 @@ const BASELINE_PREFIX = `${BASELINE_DIRECTORY.split(path.sep).join('/')}/`;
55
60
 
56
61
  const SKIP_HINTS = {
57
62
  'no-steps': 'pipeline.json has no steps; write the plan with task-router before auditing',
58
- 'no-step-ids': 'pipeline.json predates step ids; backfill them with "team-db.mjs migrate-tasks" and pass --step',
63
+ 'no-step-ids': 'pipeline.json predates step ids and the baseline is keyed by id; re-run the task-router to regenerate pipeline.json with steps[].id, then resume via /task-continue <slug>',
59
64
  'no-write-scopes': 'pipeline.json predates writeScopes; only task-router can declare a step write surface, so this step is not auditable',
65
+ 'no-baseline': 'the step wrote without a saved baseline, so no path can be attributed to it; the orchestrator saves it before the step writes (--step <id> --save-baseline), or pass the step paths (--paths a,b), then re-run',
60
66
  };
61
67
 
62
68
  const DERIVED_RULES = [
@@ -139,6 +145,10 @@ const skipResult = (reason, step = null) => ({ skip: { reason, step } });
139
145
  * Pick the audited step. A legacy pipeline is a **skip**, not a failure: the
140
146
  * audit cannot invent an id or a write surface, and a mandatory gate must not
141
147
  * become unsatisfiable for work that predates the schema.
148
+ *
149
+ * A step baseline is keyed by `id`, so a step without one is never selected:
150
+ * selecting it made `--save-baseline` a usage error and left the whole
151
+ * uncommitted change-set unattributed.
142
152
  */
143
153
  function chooseStep(pipeline, requested) {
144
154
  const steps = Array.isArray(pipeline.steps) ? pipeline.steps : [];
@@ -150,12 +160,14 @@ function chooseStep(pipeline, requested) {
150
160
  if (identified.length === 0) return skipResult('no-step-ids');
151
161
  fail(`unknown step "${requested}" (available: ${identified.map((item) => item.id).join(', ')})`);
152
162
  }
153
- const implementation = steps.find((item) => hasWriteScopes(item)
154
- && agentsOf(item).some((agent) => /feature-developer|debugger|ci-investigator/i.test(agent)));
163
+ const scoped = identified.filter(hasWriteScopes);
164
+ const implementation = scoped.find((item) => agentsOf(item)
165
+ .some((agent) => /feature-developer|debugger|ci-investigator/i.test(agent)));
155
166
  if (implementation) return { step: implementation };
156
- const scoped = steps.filter(hasWriteScopes);
157
167
  if (scoped.length === 1) return { step: scoped[0] };
158
- if (scoped.length === 0) return skipResult('no-write-scopes');
168
+ if (scoped.length === 0) {
169
+ return steps.some(hasWriteScopes) ? skipResult('no-step-ids') : skipResult('no-write-scopes');
170
+ }
159
171
  fail('cannot choose a step; pass --step <id>');
160
172
  return null;
161
173
  }
@@ -220,18 +232,19 @@ function classify(changed, writeScopes, slug) {
220
232
  });
221
233
  }
222
234
 
223
- function renderReport({ slug, step, base, baseline, notice, verdict, rows }) {
224
- const counts = {
225
- declared: rows.filter((row) => row.classification === 'declared').length,
226
- derived: rows.filter((row) => row.classification === 'derived').length,
227
- outOfScope: rows.filter((row) => row.classification === 'out-of-scope').length,
228
- };
235
+ const countRows = (rows) => ({
236
+ declared: rows.filter((row) => row.classification === 'declared').length,
237
+ derived: rows.filter((row) => row.classification === 'derived').length,
238
+ outOfScope: rows.filter((row) => row.classification === 'out-of-scope').length,
239
+ });
240
+
241
+ function renderReport({ slug, step, base, baseline, verdict, rows }) {
242
+ const counts = countRows(rows);
229
243
  const lines = [
230
244
  `Write-scope reconciliation — slug ${slug}, step ${step?.id ?? '(no id)'} (${agentsOf(step).join(', ')})`,
231
245
  `base: ${base}${base === 'HEAD' ? ' (uncommitted change-set)' : ''}`,
232
246
  ];
233
247
  if (baseline) lines.push(`baseline: ${baseline}`);
234
- if (notice) lines.push(`notice: ${notice}`);
235
248
  lines.push(`paths: ${rows.length} — declared ${counts.declared}, derived ${counts.derived}, out-of-scope ${counts.outOfScope}`);
236
249
  for (const row of rows) {
237
250
  lines.push(` ${row.classification.padEnd(12)} ${row.path} — ${row.source}`);
@@ -240,31 +253,38 @@ function renderReport({ slug, step, base, baseline, notice, verdict, rows }) {
240
253
  return { counts, text: `${lines.join('\n')}\n` };
241
254
  }
242
255
 
243
- function reportSkip({ slug, skip, asJson }) {
256
+ function reportSkip({ slug, skip, asJson, rows = [], writeScopes = [] }) {
244
257
  const hint = SKIP_HINTS[skip.reason] ?? 'the pipeline does not declare a write surface for this step';
245
258
  const step = skip.step;
259
+ const counts = countRows(rows);
246
260
  if (asJson) {
247
261
  console.log(JSON.stringify({
248
262
  schemaVersion: 1,
249
263
  slug,
250
- step: { id: step?.id ?? null, agent: step?.agent ?? null, writeScopes: [] },
264
+ step: { id: step?.id ?? null, agent: step?.agent ?? null, writeScopes },
251
265
  base: null,
252
266
  baseline: null,
253
267
  verdict: 'skip',
254
268
  skipped: true,
255
269
  skipReason: skip.reason,
256
270
  hint,
257
- counts: { declared: 0, derived: 0, outOfScope: 0 },
258
- paths: [],
271
+ counts,
272
+ paths: rows,
259
273
  }, null, 2));
260
274
  } else {
261
- process.stdout.write([
275
+ const lines = [
262
276
  `Write-scope reconciliation — slug ${slug}, step ${step?.id ?? '(no id)'} (${agentsOf(step).join(', ')})`,
263
277
  `skip: ${skip.reason}`,
264
278
  `hint: ${hint}`,
265
- 'verdict: SKIP',
266
- '',
267
- ].join('\n'));
279
+ ];
280
+ if (rows.length > 0) {
281
+ lines.push(`paths: ${rows.length} — declared ${counts.declared}, derived ${counts.derived}, out-of-scope ${counts.outOfScope} (unattributed: the whole uncommitted change-set)`);
282
+ for (const row of rows) {
283
+ lines.push(` ${row.classification.padEnd(12)} ${row.path} — ${row.source}`);
284
+ }
285
+ }
286
+ lines.push('verdict: SKIP', '');
287
+ process.stdout.write(lines.join('\n'));
268
288
  }
269
289
  process.exit(EXIT_SKIP);
270
290
  }
@@ -313,7 +333,6 @@ function main() {
313
333
 
314
334
  let base = args.base ?? 'HEAD';
315
335
  let baseline = null;
316
- let notice = null;
317
336
  let changed;
318
337
  if (args.paths !== undefined) {
319
338
  changed = String(args.paths).split(',').map(normalizePath).filter(Boolean);
@@ -327,8 +346,20 @@ function main() {
327
346
  baseline = path.relative(root, file).replace(/\\/g, '/');
328
347
  changed = baselineDelta(root, saved, base);
329
348
  } else {
330
- changed = gitChangedPaths(root, base);
331
- notice = `no baseline saved for step ${step.id ?? '(no id)'}; auditing the whole uncommitted change-set, which may include earlier steps`;
349
+ // No step baseline: the whole change-set may carry earlier steps and other
350
+ // tasks, so no path can be attributed to this step. The audit skips instead
351
+ // of failing a step on writes it cannot own.
352
+ const wholeTree = gitChangedPaths(root, base);
353
+ if (wholeTree.length > 0) {
354
+ reportSkip({
355
+ slug: args.slug,
356
+ skip: { reason: 'no-baseline', step },
357
+ asJson: args.json,
358
+ rows: classify(wholeTree, writeScopes, args.slug),
359
+ writeScopes,
360
+ });
361
+ }
362
+ changed = wholeTree;
332
363
  }
333
364
  }
334
365
 
@@ -336,7 +367,7 @@ function main() {
336
367
  const outOfScope = rows.filter((row) => row.classification === 'out-of-scope');
337
368
  const advisory = agentsOf(step).some((agent) => REVIEW_AGENT_RE.test(agent));
338
369
  const verdict = outOfScope.length === 0 ? 'pass' : advisory ? 'advisory' : 'fail';
339
- const { counts, text } = renderReport({ slug: args.slug, step, base, baseline, notice, verdict, rows });
370
+ const { counts, text } = renderReport({ slug: args.slug, step, base, baseline, verdict, rows });
340
371
 
341
372
  if (args.json) {
342
373
  console.log(JSON.stringify({
@@ -347,7 +378,6 @@ function main() {
347
378
  baseline,
348
379
  verdict,
349
380
  skipped: false,
350
- ...(notice ? { notice } : {}),
351
381
  counts,
352
382
  paths: rows,
353
383
  }, null, 2));
@@ -10,6 +10,11 @@
10
10
  * inside an atomic `<lock>.d.reclaim` guard. The guard serialises the decision
11
11
  * and the owner is re-read inside it, so a contender that judged the lock stale
12
12
  * a moment earlier cannot delete the directory another process created since.
13
+ * The guard directory names its own owner. A contender removes a guard only
14
+ * when that pid is dead, or when the guard has no owner and has aged out; the
15
+ * removal renames that directory aside and deletes it only if the renamed
16
+ * inode and owner are the ones just evaluated. Age alone never drops a guard
17
+ * a live pid still holds.
13
18
  *
14
19
  * `releaseLock` only drops a lock this process acquired. A token from another
15
20
  * process is ignored.
@@ -84,32 +89,86 @@ function removeOwnedDir(directory, token) {
84
89
  }
85
90
  }
86
91
 
92
+ /** dev/ino plus the owner record. `null` when the directory is already gone. */
93
+ function directoryIdentity(directory) {
94
+ let stat;
95
+ try {
96
+ stat = fs.statSync(directory, { bigint: true });
97
+ } catch {
98
+ return null;
99
+ }
100
+ return {
101
+ dev: stat.dev,
102
+ ino: stat.ino,
103
+ mtimeMs: Number(stat.mtimeMs),
104
+ owner: readOwner(directory),
105
+ };
106
+ }
107
+
87
108
  /**
88
- * A guard left behind by a killed reclaimer only delays the next one, so it is
89
- * dropped once it ages past the stale window.
109
+ * The renamed directory is the one we evaluated. A path-only delete can move
110
+ * a guard another live reclaimer created after the age check.
90
111
  */
91
- function removeStaleGuard(guard) {
112
+ function sameInstance(observed, renamed) {
113
+ if (!observed || !renamed) return false;
114
+ if (observed.dev !== renamed.dev || observed.ino !== renamed.ino) return false;
115
+ const left = observed.owner;
116
+ const right = renamed.owner;
117
+ if (!left && !right) return true;
118
+ if (!left || !right) return false;
119
+ if (typeof left.token === 'string' || typeof right.token === 'string') {
120
+ return left.token === right.token;
121
+ }
122
+ return left.pid === right.pid;
123
+ }
124
+
125
+ function compareAndRemove(directory, observed) {
126
+ if (!observed) return false;
127
+ const trash = `${directory}.dead-${crypto.randomBytes(4).toString('hex')}`;
92
128
  try {
93
- if (Date.now() - fs.statSync(guard).mtimeMs <= DEFAULT_STALE_MS) return false;
94
- fs.rmSync(guard, { recursive: true, force: true });
129
+ fs.renameSync(directory, trash);
130
+ } catch (error) {
131
+ return Boolean(error && error.code === 'ENOENT');
132
+ }
133
+ if (!sameInstance(observed, directoryIdentity(trash))) {
134
+ try { fs.renameSync(trash, directory); } catch { /* the path belongs to a successor */ }
135
+ return false;
136
+ }
137
+ try {
138
+ fs.rmSync(trash, { recursive: true, force: true });
95
139
  return true;
96
140
  } catch {
97
141
  return false;
98
142
  }
99
143
  }
100
144
 
101
- function ownerIsGone(directory) {
102
- const owner = readOwner(directory);
145
+ /**
146
+ * A live owner pid holds the guard however old it is. A dead pid is abandoned
147
+ * immediately. An owner-less guard is the mkdir → owner.json window and is
148
+ * abandoned only after the stale window.
149
+ */
150
+ function guardIsAbandoned(identity) {
151
+ if (!identity) return false;
152
+ const owner = identity.owner;
153
+ if (owner && Number.isInteger(owner.pid) && owner.pid > 0) {
154
+ return !isPidAlive(owner.pid);
155
+ }
156
+ return Date.now() - identity.mtimeMs > DEFAULT_STALE_MS;
157
+ }
158
+
159
+ function lockIdentityIsGone(identity) {
160
+ if (!identity) return false;
161
+ const owner = identity.owner;
103
162
  if (owner) {
104
163
  return Number.isInteger(owner.pid) && owner.pid > 0 && !isPidAlive(owner.pid);
105
164
  }
106
- // A live writer holds this window between `mkdir` and its owner write, so an
107
- // owner-less directory is abandoned only after the stale window.
108
- try {
109
- return Date.now() - fs.statSync(directory).mtimeMs > DEFAULT_STALE_MS;
110
- } catch {
111
- return false;
112
- }
165
+ return Date.now() - identity.mtimeMs > DEFAULT_STALE_MS;
166
+ }
167
+
168
+ function releaseOwnGuard(guard, token) {
169
+ const identity = directoryIdentity(guard);
170
+ if (!identity || !identity.owner || identity.owner.token !== token) return;
171
+ compareAndRemove(guard, identity);
113
172
  }
114
173
 
115
174
  /**
@@ -117,28 +176,42 @@ function ownerIsGone(directory) {
117
176
  * serialisation point: only the winner judges and removes, and it re-reads the
118
177
  * owner after taking the guard. A contender that decided "stale" before the
119
178
  * winner re-created the directory therefore sees the new, live owner and backs
120
- * off instead of deleting it.
179
+ * off instead of deleting it. An abandoned guard is removed and taken inside
180
+ * this call, so the decision and the delete stay on one guard instance.
121
181
  */
122
182
  function reclaimStaleDir(directory) {
123
183
  const guard = reclaimGuardDirectory(directory);
124
- try {
125
- fs.mkdirSync(guard);
126
- } catch (error) {
127
- if (error.code !== 'EEXIST') throw error;
128
- removeStaleGuard(guard);
129
- return false;
130
- }
131
- try {
132
- if (!ownerIsGone(directory)) return false;
184
+ for (let attempt = 0; attempt < 2; attempt += 1) {
133
185
  try {
134
- fs.rmSync(directory, { recursive: true, force: true });
135
- } catch {
136
- return false;
186
+ fs.mkdirSync(guard);
187
+ } catch (error) {
188
+ if (error.code !== 'EEXIST') throw error;
189
+ const identity = directoryIdentity(guard);
190
+ if (!guardIsAbandoned(identity) || !compareAndRemove(guard, identity)) return false;
191
+ continue;
192
+ }
193
+ const token = newToken();
194
+ let wrote = false;
195
+ try {
196
+ fs.writeFileSync(
197
+ ownerFile(guard),
198
+ `${JSON.stringify({ pid: process.pid, token, at: new Date().toISOString() })}\n`,
199
+ { encoding: 'utf8', mode: 0o600 },
200
+ );
201
+ wrote = true;
202
+ const identity = directoryIdentity(directory);
203
+ if (!lockIdentityIsGone(identity)) return false;
204
+ return compareAndRemove(directory, identity);
205
+ } catch (error) {
206
+ if (!wrote) {
207
+ try { fs.rmSync(guard, { recursive: true, force: true }); } catch { /* best effort */ }
208
+ }
209
+ throw error;
210
+ } finally {
211
+ if (wrote) releaseOwnGuard(guard, token);
137
212
  }
138
- return true;
139
- } finally {
140
- try { fs.rmSync(guard, { recursive: true, force: true }); } catch { /* best effort */ }
141
213
  }
214
+ return false;
142
215
  }
143
216
 
144
217
  function enterDirectoryLock(lockPath, deadline, busyWaitMs) {
@@ -1887,6 +1887,10 @@ export function runImprover(options = {}) {
1887
1887
  const visiblePending = [];
1888
1888
 
1889
1889
  for (const group of enrichGroups(grouped.groups, signalsPath, canonical)) {
1890
+ if (typeof group.signature === 'string' && group.signature.startsWith('exemplar:')) {
1891
+ skipped.push({ signature: group.signature, reason: 'research exemplar' });
1892
+ continue;
1893
+ }
1890
1894
  if (group.distinctSlugCount < 2) continue;
1891
1895
  let decision;
1892
1896
  try {