@bonesofspring/ai-rules 0.2.56 → 0.2.60

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 (572) hide show
  1. package/CHANGELOG.md +116 -1
  2. package/README.md +68 -3
  3. package/bin/cli.js +399 -27
  4. package/bin/lib/engine-scripts.js +3 -0
  5. package/bin/lib/mcp/catalog.js +97 -0
  6. package/bin/lib/mcp/clients.js +35 -2
  7. package/bin/lib/mcp/credentials.js +85 -1
  8. package/bin/lib/mcp/doctor.js +93 -17
  9. package/bin/lib/mcp/registry.js +10 -4
  10. package/bin/lib/seed-ai-local-team.js +8 -5
  11. package/docs/MCP-CATALOG.md +56 -0
  12. package/docs/MCP-SETUP.md +38 -6
  13. package/docs/PRESET-CONTRIBUTION.md +14 -1
  14. package/docs/TEAM-DB.md +34 -1
  15. package/docs/openapi/team-db.v1.json +17 -2
  16. package/mcp/github-proxy.mjs +133 -0
  17. package/mcp/lib/github.mjs +187 -0
  18. package/mcp/lib/streamable-http.mjs +185 -0
  19. package/mcp/lib/yandex.mjs +16 -137
  20. package/package.json +4 -1
  21. package/presets/_shared/ai-local/scripts/check-write-scope.mjs +212 -0
  22. package/presets/_shared/ai-local/scripts/rule-improver.mjs +674 -74
  23. package/presets/_shared/ai-local/scripts/run.mjs +143 -9
  24. package/presets/_shared/ai-local/scripts/team-db-api.mjs +1 -0
  25. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +6 -1
  26. package/presets/_shared/ai-local/scripts/team-db-project.mjs +1 -1
  27. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +79 -9
  28. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +29 -6
  29. package/presets/_shared/core/quality/self-review-and-context-hygiene.md +3 -1
  30. package/presets/_shared/core/review/code-review-mr.md +10 -0
  31. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +163 -16
  32. package/presets/claude/android-kotlin/agents/build-verifier.md +1 -1
  33. package/presets/claude/android-kotlin/agents/code-reviewer.md +1 -1
  34. package/presets/claude/android-kotlin/agents/debugger.md +1 -1
  35. package/presets/claude/android-kotlin/agents/feature-developer.md +1 -1
  36. package/presets/claude/android-kotlin/agents/task-analyst.md +1 -1
  37. package/presets/claude/android-kotlin/commands/update.md +1 -0
  38. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +163 -16
  39. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  40. package/presets/claude/android-kotlin/rules/tooling-and-review/code-review.md +10 -0
  41. package/presets/claude/go/agents/build-verifier.md +1 -1
  42. package/presets/claude/go/agents/code-reviewer.md +1 -1
  43. package/presets/claude/go/agents/debugger.md +1 -1
  44. package/presets/claude/go/agents/feature-developer.md +1 -1
  45. package/presets/claude/go/agents/task-analyst.md +1 -1
  46. package/presets/claude/go/commands/update.md +1 -0
  47. package/presets/claude/go/hooks/chain-team-phases.sh +163 -16
  48. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  49. package/presets/claude/go/rules/tooling-and-review/code-review.md +10 -0
  50. package/presets/claude/ios-swift/agents/build-verifier.md +1 -1
  51. package/presets/claude/ios-swift/agents/code-reviewer.md +1 -1
  52. package/presets/claude/ios-swift/agents/debugger.md +1 -1
  53. package/presets/claude/ios-swift/agents/feature-developer.md +1 -1
  54. package/presets/claude/ios-swift/agents/task-analyst.md +1 -1
  55. package/presets/claude/ios-swift/commands/update.md +1 -0
  56. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +163 -16
  57. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  58. package/presets/claude/ios-swift/rules/tooling-and-review/code-review.md +10 -0
  59. package/presets/claude/java/agents/build-verifier.md +1 -1
  60. package/presets/claude/java/agents/code-reviewer.md +1 -1
  61. package/presets/claude/java/agents/debugger.md +1 -1
  62. package/presets/claude/java/agents/feature-developer.md +1 -1
  63. package/presets/claude/java/agents/task-analyst.md +1 -1
  64. package/presets/claude/java/commands/update.md +1 -0
  65. package/presets/claude/java/hooks/chain-team-phases.sh +163 -16
  66. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  67. package/presets/claude/java/rules/tooling-and-review/code-review.md +10 -0
  68. package/presets/claude/mcp-ts/agents/build-verifier.md +1 -1
  69. package/presets/claude/mcp-ts/agents/feature-developer.md +1 -1
  70. package/presets/claude/mcp-ts/agents/task-analyst.md +1 -1
  71. package/presets/claude/mcp-ts/commands/update.md +1 -0
  72. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +163 -16
  73. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  74. package/presets/claude/mcp-ts/rules/tooling-and-review/code-review.md +10 -0
  75. package/presets/claude/mol/agents/build-verifier.md +1 -1
  76. package/presets/claude/mol/agents/code-reviewer.md +1 -1
  77. package/presets/claude/mol/agents/debugger.md +1 -1
  78. package/presets/claude/mol/agents/feature-developer.md +1 -1
  79. package/presets/claude/mol/agents/task-analyst.md +1 -1
  80. package/presets/claude/mol/commands/update.md +1 -0
  81. package/presets/claude/mol/hooks/chain-team-phases.sh +163 -16
  82. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  83. package/presets/claude/mol/rules/tooling-and-review/code-review-mr.md +10 -0
  84. package/presets/claude/next/agents/build-verifier.md +18 -1
  85. package/presets/claude/next/agents/code-reviewer.md +9 -1
  86. package/presets/claude/next/agents/debugger.md +1 -1
  87. package/presets/claude/next/agents/feature-developer.md +13 -1
  88. package/presets/claude/next/agents/task-analyst.md +1 -1
  89. package/presets/claude/next/agents/task-router.md +10 -0
  90. package/presets/claude/next/commands/task-continue.md +3 -1
  91. package/presets/claude/next/commands/update.md +1 -0
  92. package/presets/claude/next/hooks/chain-team-phases.sh +163 -16
  93. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  94. package/presets/claude/next/rules/tooling-and-review/code-review-mr.md +12 -1
  95. package/presets/claude/nuxt/agents/build-verifier.md +1 -1
  96. package/presets/claude/nuxt/agents/code-reviewer.md +1 -1
  97. package/presets/claude/nuxt/agents/debugger.md +1 -1
  98. package/presets/claude/nuxt/agents/feature-developer.md +1 -1
  99. package/presets/claude/nuxt/agents/task-analyst.md +1 -1
  100. package/presets/claude/nuxt/commands/update.md +1 -0
  101. package/presets/claude/nuxt/hooks/chain-team-phases.sh +163 -16
  102. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  103. package/presets/claude/nuxt/rules/tooling-and-review/code-review-mr.md +10 -0
  104. package/presets/claude/php-hexagonal/agents/build-verifier.md +1 -1
  105. package/presets/claude/php-hexagonal/agents/code-reviewer.md +1 -1
  106. package/presets/claude/php-hexagonal/agents/debugger.md +1 -1
  107. package/presets/claude/php-hexagonal/agents/feature-developer.md +1 -1
  108. package/presets/claude/php-hexagonal/agents/task-analyst.md +1 -1
  109. package/presets/claude/php-hexagonal/commands/update.md +1 -0
  110. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +163 -16
  111. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  112. package/presets/claude/php-hexagonal/rules/tooling-and-review/code-review.md +10 -0
  113. package/presets/claude/php-laravel/agents/build-verifier.md +1 -1
  114. package/presets/claude/php-laravel/agents/code-reviewer.md +1 -1
  115. package/presets/claude/php-laravel/agents/debugger.md +1 -1
  116. package/presets/claude/php-laravel/agents/feature-developer.md +1 -1
  117. package/presets/claude/php-laravel/agents/task-analyst.md +1 -1
  118. package/presets/claude/php-laravel/commands/update.md +1 -0
  119. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +163 -16
  120. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  121. package/presets/claude/php-laravel/rules/tooling-and-review/code-review.md +10 -0
  122. package/presets/claude/svelte/agents/build-verifier.md +1 -1
  123. package/presets/claude/svelte/agents/code-reviewer.md +1 -1
  124. package/presets/claude/svelte/agents/debugger.md +1 -1
  125. package/presets/claude/svelte/agents/feature-developer.md +1 -1
  126. package/presets/claude/svelte/agents/task-analyst.md +1 -1
  127. package/presets/claude/svelte/commands/update.md +1 -0
  128. package/presets/claude/svelte/hooks/chain-team-phases.sh +163 -16
  129. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +29 -6
  130. package/presets/claude/svelte/rules/tooling-and-review/code-review-mr.md +10 -0
  131. package/presets/cursor/android-kotlin/agents/build-verifier.md +1 -1
  132. package/presets/cursor/android-kotlin/agents/code-reviewer.md +1 -1
  133. package/presets/cursor/android-kotlin/agents/debugger.md +1 -1
  134. package/presets/cursor/android-kotlin/agents/feature-developer.md +1 -1
  135. package/presets/cursor/android-kotlin/agents/task-analyst.md +1 -1
  136. package/presets/cursor/android-kotlin/commands/update.md +1 -0
  137. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +163 -16
  138. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +1 -1
  139. package/presets/cursor/android-kotlin/rules/code-review-mr.mdc +10 -0
  140. package/presets/cursor/go/agents/build-verifier.md +1 -1
  141. package/presets/cursor/go/agents/code-reviewer.md +1 -1
  142. package/presets/cursor/go/agents/debugger.md +1 -1
  143. package/presets/cursor/go/agents/feature-developer.md +1 -1
  144. package/presets/cursor/go/agents/task-analyst.md +1 -1
  145. package/presets/cursor/go/commands/update.md +1 -0
  146. package/presets/cursor/go/hooks/chain-team-phases.sh +163 -16
  147. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +1 -1
  148. package/presets/cursor/go/rules/code-review-mr.mdc +10 -0
  149. package/presets/cursor/ios-swift/agents/build-verifier.md +1 -1
  150. package/presets/cursor/ios-swift/agents/code-reviewer.md +1 -1
  151. package/presets/cursor/ios-swift/agents/debugger.md +1 -1
  152. package/presets/cursor/ios-swift/agents/feature-developer.md +1 -1
  153. package/presets/cursor/ios-swift/agents/task-analyst.md +1 -1
  154. package/presets/cursor/ios-swift/commands/update.md +1 -0
  155. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +163 -16
  156. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +1 -1
  157. package/presets/cursor/ios-swift/rules/code-review-mr.mdc +10 -0
  158. package/presets/cursor/java/agents/build-verifier.md +1 -1
  159. package/presets/cursor/java/agents/code-reviewer.md +1 -1
  160. package/presets/cursor/java/agents/debugger.md +1 -1
  161. package/presets/cursor/java/agents/feature-developer.md +1 -1
  162. package/presets/cursor/java/agents/task-analyst.md +1 -1
  163. package/presets/cursor/java/commands/update.md +1 -0
  164. package/presets/cursor/java/hooks/chain-team-phases.sh +163 -16
  165. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +1 -1
  166. package/presets/cursor/java/rules/code-review-mr.mdc +10 -0
  167. package/presets/cursor/mcp-ts/agents/build-verifier.md +1 -1
  168. package/presets/cursor/mcp-ts/agents/feature-developer.md +1 -1
  169. package/presets/cursor/mcp-ts/agents/task-analyst.md +1 -1
  170. package/presets/cursor/mcp-ts/commands/update.md +1 -0
  171. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +163 -16
  172. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +1 -1
  173. package/presets/cursor/mcp-ts/rules/code-review-mr.mdc +10 -0
  174. package/presets/cursor/mol/MCP.md +4 -3
  175. package/presets/cursor/mol/agents/build-verifier.md +1 -1
  176. package/presets/cursor/mol/agents/code-reviewer.md +1 -1
  177. package/presets/cursor/mol/agents/debugger.md +1 -1
  178. package/presets/cursor/mol/agents/feature-developer.md +1 -1
  179. package/presets/cursor/mol/agents/task-analyst.md +1 -1
  180. package/presets/cursor/mol/commands/update.md +1 -0
  181. package/presets/cursor/mol/hooks/chain-team-phases.sh +163 -16
  182. package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +1 -1
  183. package/presets/cursor/mol/rules/code-review-mr.mdc +10 -0
  184. package/presets/cursor/next/MCP.md +4 -3
  185. package/presets/cursor/next/agents/README.md +2 -0
  186. package/presets/cursor/next/agents/build-verifier.md +18 -1
  187. package/presets/cursor/next/agents/code-reviewer.md +9 -1
  188. package/presets/cursor/next/agents/debugger.md +1 -1
  189. package/presets/cursor/next/agents/feature-developer.md +13 -1
  190. package/presets/cursor/next/agents/task-analyst.md +1 -1
  191. package/presets/cursor/next/agents/task-router.md +10 -0
  192. package/presets/cursor/next/commands/task-continue.md +3 -1
  193. package/presets/cursor/next/commands/update.md +1 -0
  194. package/presets/cursor/next/hooks/chain-team-phases.sh +163 -16
  195. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +1 -1
  196. package/presets/cursor/next/rules/code-review-mr.mdc +12 -1
  197. package/presets/cursor/next/team/fixtures/feature-l2-lite.json +27 -0
  198. package/presets/cursor/nuxt/agents/build-verifier.md +1 -1
  199. package/presets/cursor/nuxt/agents/code-reviewer.md +1 -1
  200. package/presets/cursor/nuxt/agents/debugger.md +1 -1
  201. package/presets/cursor/nuxt/agents/feature-developer.md +1 -1
  202. package/presets/cursor/nuxt/agents/task-analyst.md +1 -1
  203. package/presets/cursor/nuxt/commands/update.md +1 -0
  204. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +163 -16
  205. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  206. package/presets/cursor/nuxt/rules/code-review-mr.mdc +10 -0
  207. package/presets/cursor/php-hexagonal/agents/build-verifier.md +1 -1
  208. package/presets/cursor/php-hexagonal/agents/code-reviewer.md +1 -1
  209. package/presets/cursor/php-hexagonal/agents/debugger.md +1 -1
  210. package/presets/cursor/php-hexagonal/agents/feature-developer.md +1 -1
  211. package/presets/cursor/php-hexagonal/agents/task-analyst.md +1 -1
  212. package/presets/cursor/php-hexagonal/commands/update.md +1 -0
  213. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +163 -16
  214. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +1 -1
  215. package/presets/cursor/php-hexagonal/rules/code-review-mr.mdc +10 -0
  216. package/presets/cursor/php-laravel/agents/build-verifier.md +1 -1
  217. package/presets/cursor/php-laravel/agents/code-reviewer.md +1 -1
  218. package/presets/cursor/php-laravel/agents/debugger.md +1 -1
  219. package/presets/cursor/php-laravel/agents/feature-developer.md +1 -1
  220. package/presets/cursor/php-laravel/agents/task-analyst.md +1 -1
  221. package/presets/cursor/php-laravel/commands/update.md +1 -0
  222. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +163 -16
  223. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +1 -1
  224. package/presets/cursor/php-laravel/rules/code-review-mr.mdc +10 -0
  225. package/presets/cursor/svelte/agents/build-verifier.md +1 -1
  226. package/presets/cursor/svelte/agents/code-reviewer.md +1 -1
  227. package/presets/cursor/svelte/agents/debugger.md +1 -1
  228. package/presets/cursor/svelte/agents/feature-developer.md +1 -1
  229. package/presets/cursor/svelte/agents/task-analyst.md +1 -1
  230. package/presets/cursor/svelte/commands/update.md +1 -0
  231. package/presets/cursor/svelte/hooks/chain-team-phases.sh +163 -16
  232. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  233. package/presets/cursor/svelte/rules/code-review-mr.mdc +10 -0
  234. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  235. package/presets/mavis/android-kotlin/agents/build-verifier.md +1 -1
  236. package/presets/mavis/android-kotlin/agents/code-reviewer.md +1 -1
  237. package/presets/mavis/android-kotlin/agents/debugger.md +1 -1
  238. package/presets/mavis/android-kotlin/agents/feature-developer.md +1 -1
  239. package/presets/mavis/android-kotlin/agents/task-analyst.md +1 -1
  240. package/presets/mavis/android-kotlin/commands/update.md +1 -0
  241. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +163 -16
  242. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +29 -6
  243. package/presets/mavis/android-kotlin/rules/code-review-mr.md +10 -0
  244. package/presets/mavis/go/adapter-map.json +1 -1
  245. package/presets/mavis/go/agents/build-verifier.md +1 -1
  246. package/presets/mavis/go/agents/code-reviewer.md +1 -1
  247. package/presets/mavis/go/agents/debugger.md +1 -1
  248. package/presets/mavis/go/agents/feature-developer.md +1 -1
  249. package/presets/mavis/go/agents/task-analyst.md +1 -1
  250. package/presets/mavis/go/commands/update.md +1 -0
  251. package/presets/mavis/go/hooks/chain-team-phases.sh +163 -16
  252. package/presets/mavis/go/rules/agent-team-orchestrator.md +29 -6
  253. package/presets/mavis/go/rules/code-review-mr.md +10 -0
  254. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  255. package/presets/mavis/ios-swift/agents/build-verifier.md +1 -1
  256. package/presets/mavis/ios-swift/agents/code-reviewer.md +1 -1
  257. package/presets/mavis/ios-swift/agents/debugger.md +1 -1
  258. package/presets/mavis/ios-swift/agents/feature-developer.md +1 -1
  259. package/presets/mavis/ios-swift/agents/task-analyst.md +1 -1
  260. package/presets/mavis/ios-swift/commands/update.md +1 -0
  261. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +163 -16
  262. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +29 -6
  263. package/presets/mavis/ios-swift/rules/code-review-mr.md +10 -0
  264. package/presets/mavis/java/adapter-map.json +1 -1
  265. package/presets/mavis/java/agents/build-verifier.md +1 -1
  266. package/presets/mavis/java/agents/code-reviewer.md +1 -1
  267. package/presets/mavis/java/agents/debugger.md +1 -1
  268. package/presets/mavis/java/agents/feature-developer.md +1 -1
  269. package/presets/mavis/java/agents/task-analyst.md +1 -1
  270. package/presets/mavis/java/commands/update.md +1 -0
  271. package/presets/mavis/java/hooks/chain-team-phases.sh +163 -16
  272. package/presets/mavis/java/rules/agent-team-orchestrator.md +29 -6
  273. package/presets/mavis/java/rules/code-review-mr.md +10 -0
  274. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  275. package/presets/mavis/mcp-ts/agents/build-verifier.md +1 -1
  276. package/presets/mavis/mcp-ts/agents/feature-developer.md +1 -1
  277. package/presets/mavis/mcp-ts/agents/task-analyst.md +1 -1
  278. package/presets/mavis/mcp-ts/commands/update.md +1 -0
  279. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +163 -16
  280. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +29 -6
  281. package/presets/mavis/mcp-ts/rules/code-review-mr.md +10 -0
  282. package/presets/mavis/mol/MCP.md +4 -3
  283. package/presets/mavis/mol/adapter-map.json +1 -1
  284. package/presets/mavis/mol/agents/build-verifier.md +1 -1
  285. package/presets/mavis/mol/agents/code-reviewer.md +1 -1
  286. package/presets/mavis/mol/agents/debugger.md +1 -1
  287. package/presets/mavis/mol/agents/feature-developer.md +1 -1
  288. package/presets/mavis/mol/agents/task-analyst.md +1 -1
  289. package/presets/mavis/mol/commands/update.md +1 -0
  290. package/presets/mavis/mol/hooks/chain-team-phases.sh +163 -16
  291. package/presets/mavis/mol/rules/agent-team-orchestrator.md +29 -6
  292. package/presets/mavis/mol/rules/code-review-mr.md +10 -0
  293. package/presets/mavis/next/MCP.md +4 -3
  294. package/presets/mavis/next/adapter-map.json +9 -1
  295. package/presets/mavis/next/agents/build-verifier.md +18 -1
  296. package/presets/mavis/next/agents/code-reviewer.md +9 -1
  297. package/presets/mavis/next/agents/debugger.md +1 -1
  298. package/presets/mavis/next/agents/feature-developer.md +13 -1
  299. package/presets/mavis/next/agents/task-analyst.md +1 -1
  300. package/presets/mavis/next/agents/task-router.md +10 -0
  301. package/presets/mavis/next/commands/task-continue.md +3 -1
  302. package/presets/mavis/next/commands/update.md +1 -0
  303. package/presets/mavis/next/hooks/chain-team-phases.sh +163 -16
  304. package/presets/mavis/next/rules/agent-team-orchestrator.md +29 -6
  305. package/presets/mavis/next/rules/code-review-mr.md +12 -1
  306. package/presets/mavis/next/team/fixtures/feature-l2-lite.json +27 -0
  307. package/presets/mavis/nuxt/adapter-map.json +1 -1
  308. package/presets/mavis/nuxt/agents/build-verifier.md +1 -1
  309. package/presets/mavis/nuxt/agents/code-reviewer.md +1 -1
  310. package/presets/mavis/nuxt/agents/debugger.md +1 -1
  311. package/presets/mavis/nuxt/agents/feature-developer.md +1 -1
  312. package/presets/mavis/nuxt/agents/task-analyst.md +1 -1
  313. package/presets/mavis/nuxt/commands/update.md +1 -0
  314. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +163 -16
  315. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +29 -6
  316. package/presets/mavis/nuxt/rules/code-review-mr.md +10 -0
  317. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  318. package/presets/mavis/php-hexagonal/agents/build-verifier.md +1 -1
  319. package/presets/mavis/php-hexagonal/agents/code-reviewer.md +1 -1
  320. package/presets/mavis/php-hexagonal/agents/debugger.md +1 -1
  321. package/presets/mavis/php-hexagonal/agents/feature-developer.md +1 -1
  322. package/presets/mavis/php-hexagonal/agents/task-analyst.md +1 -1
  323. package/presets/mavis/php-hexagonal/commands/update.md +1 -0
  324. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +163 -16
  325. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +29 -6
  326. package/presets/mavis/php-hexagonal/rules/code-review-mr.md +10 -0
  327. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  328. package/presets/mavis/php-laravel/agents/build-verifier.md +1 -1
  329. package/presets/mavis/php-laravel/agents/code-reviewer.md +1 -1
  330. package/presets/mavis/php-laravel/agents/debugger.md +1 -1
  331. package/presets/mavis/php-laravel/agents/feature-developer.md +1 -1
  332. package/presets/mavis/php-laravel/agents/task-analyst.md +1 -1
  333. package/presets/mavis/php-laravel/commands/update.md +1 -0
  334. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +163 -16
  335. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +29 -6
  336. package/presets/mavis/php-laravel/rules/code-review-mr.md +10 -0
  337. package/presets/mavis/svelte/adapter-map.json +1 -1
  338. package/presets/mavis/svelte/agents/build-verifier.md +1 -1
  339. package/presets/mavis/svelte/agents/code-reviewer.md +1 -1
  340. package/presets/mavis/svelte/agents/debugger.md +1 -1
  341. package/presets/mavis/svelte/agents/feature-developer.md +1 -1
  342. package/presets/mavis/svelte/agents/task-analyst.md +1 -1
  343. package/presets/mavis/svelte/commands/update.md +1 -0
  344. package/presets/mavis/svelte/hooks/chain-team-phases.sh +163 -16
  345. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +29 -6
  346. package/presets/mavis/svelte/rules/code-review-mr.md +10 -0
  347. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  348. package/presets/opencode/android-kotlin/agents/build-verifier.md +1 -1
  349. package/presets/opencode/android-kotlin/agents/code-reviewer.md +1 -1
  350. package/presets/opencode/android-kotlin/agents/debugger.md +1 -1
  351. package/presets/opencode/android-kotlin/agents/feature-developer.md +1 -1
  352. package/presets/opencode/android-kotlin/agents/task-analyst.md +1 -1
  353. package/presets/opencode/android-kotlin/commands/update.md +1 -0
  354. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +163 -16
  355. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +29 -6
  356. package/presets/opencode/android-kotlin/rules/code-review-mr.md +10 -0
  357. package/presets/opencode/go/adapter-map.json +1 -1
  358. package/presets/opencode/go/agents/build-verifier.md +1 -1
  359. package/presets/opencode/go/agents/code-reviewer.md +1 -1
  360. package/presets/opencode/go/agents/debugger.md +1 -1
  361. package/presets/opencode/go/agents/feature-developer.md +1 -1
  362. package/presets/opencode/go/agents/task-analyst.md +1 -1
  363. package/presets/opencode/go/commands/update.md +1 -0
  364. package/presets/opencode/go/hooks/chain-team-phases.sh +163 -16
  365. package/presets/opencode/go/rules/agent-team-orchestrator.md +29 -6
  366. package/presets/opencode/go/rules/code-review-mr.md +10 -0
  367. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  368. package/presets/opencode/ios-swift/agents/build-verifier.md +1 -1
  369. package/presets/opencode/ios-swift/agents/code-reviewer.md +1 -1
  370. package/presets/opencode/ios-swift/agents/debugger.md +1 -1
  371. package/presets/opencode/ios-swift/agents/feature-developer.md +1 -1
  372. package/presets/opencode/ios-swift/agents/task-analyst.md +1 -1
  373. package/presets/opencode/ios-swift/commands/update.md +1 -0
  374. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +163 -16
  375. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +29 -6
  376. package/presets/opencode/ios-swift/rules/code-review-mr.md +10 -0
  377. package/presets/opencode/java/adapter-map.json +1 -1
  378. package/presets/opencode/java/agents/build-verifier.md +1 -1
  379. package/presets/opencode/java/agents/code-reviewer.md +1 -1
  380. package/presets/opencode/java/agents/debugger.md +1 -1
  381. package/presets/opencode/java/agents/feature-developer.md +1 -1
  382. package/presets/opencode/java/agents/task-analyst.md +1 -1
  383. package/presets/opencode/java/commands/update.md +1 -0
  384. package/presets/opencode/java/hooks/chain-team-phases.sh +163 -16
  385. package/presets/opencode/java/rules/agent-team-orchestrator.md +29 -6
  386. package/presets/opencode/java/rules/code-review-mr.md +10 -0
  387. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  388. package/presets/opencode/mcp-ts/agents/build-verifier.md +1 -1
  389. package/presets/opencode/mcp-ts/agents/feature-developer.md +1 -1
  390. package/presets/opencode/mcp-ts/agents/task-analyst.md +1 -1
  391. package/presets/opencode/mcp-ts/commands/update.md +1 -0
  392. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +163 -16
  393. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +29 -6
  394. package/presets/opencode/mcp-ts/rules/code-review-mr.md +10 -0
  395. package/presets/opencode/mol/MCP.md +4 -3
  396. package/presets/opencode/mol/adapter-map.json +1 -1
  397. package/presets/opencode/mol/agents/build-verifier.md +1 -1
  398. package/presets/opencode/mol/agents/code-reviewer.md +1 -1
  399. package/presets/opencode/mol/agents/debugger.md +1 -1
  400. package/presets/opencode/mol/agents/feature-developer.md +1 -1
  401. package/presets/opencode/mol/agents/task-analyst.md +1 -1
  402. package/presets/opencode/mol/commands/update.md +1 -0
  403. package/presets/opencode/mol/hooks/chain-team-phases.sh +163 -16
  404. package/presets/opencode/mol/rules/agent-team-orchestrator.md +29 -6
  405. package/presets/opencode/mol/rules/code-review-mr.md +10 -0
  406. package/presets/opencode/next/MCP.md +4 -3
  407. package/presets/opencode/next/adapter-map.json +9 -1
  408. package/presets/opencode/next/agents/build-verifier.md +18 -1
  409. package/presets/opencode/next/agents/code-reviewer.md +9 -1
  410. package/presets/opencode/next/agents/debugger.md +1 -1
  411. package/presets/opencode/next/agents/feature-developer.md +13 -1
  412. package/presets/opencode/next/agents/task-analyst.md +1 -1
  413. package/presets/opencode/next/agents/task-router.md +10 -0
  414. package/presets/opencode/next/commands/task-continue.md +3 -1
  415. package/presets/opencode/next/commands/update.md +1 -0
  416. package/presets/opencode/next/hooks/chain-team-phases.sh +163 -16
  417. package/presets/opencode/next/rules/agent-team-orchestrator.md +29 -6
  418. package/presets/opencode/next/rules/code-review-mr.md +12 -1
  419. package/presets/opencode/next/team/fixtures/feature-l2-lite.json +27 -0
  420. package/presets/opencode/nuxt/adapter-map.json +1 -1
  421. package/presets/opencode/nuxt/agents/build-verifier.md +1 -1
  422. package/presets/opencode/nuxt/agents/code-reviewer.md +1 -1
  423. package/presets/opencode/nuxt/agents/debugger.md +1 -1
  424. package/presets/opencode/nuxt/agents/feature-developer.md +1 -1
  425. package/presets/opencode/nuxt/agents/task-analyst.md +1 -1
  426. package/presets/opencode/nuxt/commands/update.md +1 -0
  427. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +163 -16
  428. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +29 -6
  429. package/presets/opencode/nuxt/rules/code-review-mr.md +10 -0
  430. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  431. package/presets/opencode/php-hexagonal/agents/build-verifier.md +1 -1
  432. package/presets/opencode/php-hexagonal/agents/code-reviewer.md +1 -1
  433. package/presets/opencode/php-hexagonal/agents/debugger.md +1 -1
  434. package/presets/opencode/php-hexagonal/agents/feature-developer.md +1 -1
  435. package/presets/opencode/php-hexagonal/agents/task-analyst.md +1 -1
  436. package/presets/opencode/php-hexagonal/commands/update.md +1 -0
  437. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +163 -16
  438. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +29 -6
  439. package/presets/opencode/php-hexagonal/rules/code-review-mr.md +10 -0
  440. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  441. package/presets/opencode/php-laravel/agents/build-verifier.md +1 -1
  442. package/presets/opencode/php-laravel/agents/code-reviewer.md +1 -1
  443. package/presets/opencode/php-laravel/agents/debugger.md +1 -1
  444. package/presets/opencode/php-laravel/agents/feature-developer.md +1 -1
  445. package/presets/opencode/php-laravel/agents/task-analyst.md +1 -1
  446. package/presets/opencode/php-laravel/commands/update.md +1 -0
  447. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +163 -16
  448. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +29 -6
  449. package/presets/opencode/php-laravel/rules/code-review-mr.md +10 -0
  450. package/presets/opencode/svelte/adapter-map.json +1 -1
  451. package/presets/opencode/svelte/agents/build-verifier.md +1 -1
  452. package/presets/opencode/svelte/agents/code-reviewer.md +1 -1
  453. package/presets/opencode/svelte/agents/debugger.md +1 -1
  454. package/presets/opencode/svelte/agents/feature-developer.md +1 -1
  455. package/presets/opencode/svelte/agents/task-analyst.md +1 -1
  456. package/presets/opencode/svelte/commands/update.md +1 -0
  457. package/presets/opencode/svelte/hooks/chain-team-phases.sh +163 -16
  458. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +29 -6
  459. package/presets/opencode/svelte/rules/code-review-mr.md +10 -0
  460. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  461. package/presets/zcode/android-kotlin/agents/build-verifier.md +1 -1
  462. package/presets/zcode/android-kotlin/agents/code-reviewer.md +1 -1
  463. package/presets/zcode/android-kotlin/agents/debugger.md +1 -1
  464. package/presets/zcode/android-kotlin/agents/feature-developer.md +1 -1
  465. package/presets/zcode/android-kotlin/agents/task-analyst.md +1 -1
  466. package/presets/zcode/android-kotlin/commands/update.md +1 -0
  467. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +163 -16
  468. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +29 -6
  469. package/presets/zcode/android-kotlin/rules/code-review-mr.md +10 -0
  470. package/presets/zcode/go/adapter-map.json +1 -1
  471. package/presets/zcode/go/agents/build-verifier.md +1 -1
  472. package/presets/zcode/go/agents/code-reviewer.md +1 -1
  473. package/presets/zcode/go/agents/debugger.md +1 -1
  474. package/presets/zcode/go/agents/feature-developer.md +1 -1
  475. package/presets/zcode/go/agents/task-analyst.md +1 -1
  476. package/presets/zcode/go/commands/update.md +1 -0
  477. package/presets/zcode/go/hooks/chain-team-phases.sh +163 -16
  478. package/presets/zcode/go/rules/agent-team-orchestrator.md +29 -6
  479. package/presets/zcode/go/rules/code-review-mr.md +10 -0
  480. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  481. package/presets/zcode/ios-swift/agents/build-verifier.md +1 -1
  482. package/presets/zcode/ios-swift/agents/code-reviewer.md +1 -1
  483. package/presets/zcode/ios-swift/agents/debugger.md +1 -1
  484. package/presets/zcode/ios-swift/agents/feature-developer.md +1 -1
  485. package/presets/zcode/ios-swift/agents/task-analyst.md +1 -1
  486. package/presets/zcode/ios-swift/commands/update.md +1 -0
  487. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +163 -16
  488. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +29 -6
  489. package/presets/zcode/ios-swift/rules/code-review-mr.md +10 -0
  490. package/presets/zcode/java/adapter-map.json +1 -1
  491. package/presets/zcode/java/agents/build-verifier.md +1 -1
  492. package/presets/zcode/java/agents/code-reviewer.md +1 -1
  493. package/presets/zcode/java/agents/debugger.md +1 -1
  494. package/presets/zcode/java/agents/feature-developer.md +1 -1
  495. package/presets/zcode/java/agents/task-analyst.md +1 -1
  496. package/presets/zcode/java/commands/update.md +1 -0
  497. package/presets/zcode/java/hooks/chain-team-phases.sh +163 -16
  498. package/presets/zcode/java/rules/agent-team-orchestrator.md +29 -6
  499. package/presets/zcode/java/rules/code-review-mr.md +10 -0
  500. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  501. package/presets/zcode/mcp-ts/agents/build-verifier.md +1 -1
  502. package/presets/zcode/mcp-ts/agents/feature-developer.md +1 -1
  503. package/presets/zcode/mcp-ts/agents/task-analyst.md +1 -1
  504. package/presets/zcode/mcp-ts/commands/update.md +1 -0
  505. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +163 -16
  506. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +29 -6
  507. package/presets/zcode/mcp-ts/rules/code-review-mr.md +10 -0
  508. package/presets/zcode/mol/MCP.md +4 -3
  509. package/presets/zcode/mol/adapter-map.json +1 -1
  510. package/presets/zcode/mol/agents/build-verifier.md +1 -1
  511. package/presets/zcode/mol/agents/code-reviewer.md +1 -1
  512. package/presets/zcode/mol/agents/debugger.md +1 -1
  513. package/presets/zcode/mol/agents/feature-developer.md +1 -1
  514. package/presets/zcode/mol/agents/task-analyst.md +1 -1
  515. package/presets/zcode/mol/commands/update.md +1 -0
  516. package/presets/zcode/mol/hooks/chain-team-phases.sh +163 -16
  517. package/presets/zcode/mol/rules/agent-team-orchestrator.md +29 -6
  518. package/presets/zcode/mol/rules/code-review-mr.md +10 -0
  519. package/presets/zcode/next/MCP.md +4 -3
  520. package/presets/zcode/next/adapter-map.json +9 -1
  521. package/presets/zcode/next/agents/build-verifier.md +18 -1
  522. package/presets/zcode/next/agents/code-reviewer.md +9 -1
  523. package/presets/zcode/next/agents/debugger.md +1 -1
  524. package/presets/zcode/next/agents/feature-developer.md +13 -1
  525. package/presets/zcode/next/agents/task-analyst.md +1 -1
  526. package/presets/zcode/next/agents/task-router.md +10 -0
  527. package/presets/zcode/next/commands/task-continue.md +3 -1
  528. package/presets/zcode/next/commands/update.md +1 -0
  529. package/presets/zcode/next/hooks/chain-team-phases.sh +163 -16
  530. package/presets/zcode/next/rules/agent-team-orchestrator.md +29 -6
  531. package/presets/zcode/next/rules/code-review-mr.md +12 -1
  532. package/presets/zcode/next/team/fixtures/feature-l2-lite.json +27 -0
  533. package/presets/zcode/nuxt/adapter-map.json +1 -1
  534. package/presets/zcode/nuxt/agents/build-verifier.md +1 -1
  535. package/presets/zcode/nuxt/agents/code-reviewer.md +1 -1
  536. package/presets/zcode/nuxt/agents/debugger.md +1 -1
  537. package/presets/zcode/nuxt/agents/feature-developer.md +1 -1
  538. package/presets/zcode/nuxt/agents/task-analyst.md +1 -1
  539. package/presets/zcode/nuxt/commands/update.md +1 -0
  540. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +163 -16
  541. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +29 -6
  542. package/presets/zcode/nuxt/rules/code-review-mr.md +10 -0
  543. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  544. package/presets/zcode/php-hexagonal/agents/build-verifier.md +1 -1
  545. package/presets/zcode/php-hexagonal/agents/code-reviewer.md +1 -1
  546. package/presets/zcode/php-hexagonal/agents/debugger.md +1 -1
  547. package/presets/zcode/php-hexagonal/agents/feature-developer.md +1 -1
  548. package/presets/zcode/php-hexagonal/agents/task-analyst.md +1 -1
  549. package/presets/zcode/php-hexagonal/commands/update.md +1 -0
  550. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +163 -16
  551. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +29 -6
  552. package/presets/zcode/php-hexagonal/rules/code-review-mr.md +10 -0
  553. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  554. package/presets/zcode/php-laravel/agents/build-verifier.md +1 -1
  555. package/presets/zcode/php-laravel/agents/code-reviewer.md +1 -1
  556. package/presets/zcode/php-laravel/agents/debugger.md +1 -1
  557. package/presets/zcode/php-laravel/agents/feature-developer.md +1 -1
  558. package/presets/zcode/php-laravel/agents/task-analyst.md +1 -1
  559. package/presets/zcode/php-laravel/commands/update.md +1 -0
  560. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +163 -16
  561. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +29 -6
  562. package/presets/zcode/php-laravel/rules/code-review-mr.md +10 -0
  563. package/presets/zcode/svelte/adapter-map.json +1 -1
  564. package/presets/zcode/svelte/agents/build-verifier.md +1 -1
  565. package/presets/zcode/svelte/agents/code-reviewer.md +1 -1
  566. package/presets/zcode/svelte/agents/debugger.md +1 -1
  567. package/presets/zcode/svelte/agents/feature-developer.md +1 -1
  568. package/presets/zcode/svelte/agents/task-analyst.md +1 -1
  569. package/presets/zcode/svelte/commands/update.md +1 -0
  570. package/presets/zcode/svelte/hooks/chain-team-phases.sh +163 -16
  571. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +29 -6
  572. package/presets/zcode/svelte/rules/code-review-mr.md +10 -0
@@ -28,9 +28,28 @@ import {
28
28
  } from './signals.mjs';
29
29
  import { acquireLock, releaseLock } from './lock.mjs';
30
30
 
31
- // --- Envelope caps (architecture.md §3) -------------------------------------
31
+ // --- Envelope caps (architecture.md §3, ADR 0001 guard 2) --------------------
32
+ // Two stores, two budgets:
33
+ // human store — `.ai.local/rules/**` ≤ MAX_ACTIVE_RULES files, ≤ MAX_RULE_LINES lines
34
+ // machine store — `.ai.local/conventions.md` ≤ MAX_CONVENTION_LINES lines
35
+ // The combined envelope stays 200 non-empty lines; only its distribution moves.
36
+ // A saturated store refuses its own writes and never another store's.
32
37
  export const MAX_ACTIVE_RULES = 5;
33
- export const MAX_TOTAL_LINES = 200;
38
+ export const MAX_RULE_LINES = 170;
39
+ export const MAX_CONVENTION_LINES = 30;
40
+
41
+ /**
42
+ * Back-compat alias for the pre-split single-pool engine.
43
+ *
44
+ * A consumer seeded before the per-store split keeps its old `run.mjs`
45
+ * (seeding is skip-if-exists), and that module imports `MAX_TOTAL_LINES`.
46
+ * The alias keeps the import resolvable, so a stale sibling module still
47
+ * loads instead of dying with a `SyntaxError`.
48
+ *
49
+ * @deprecated Use MAX_RULE_LINES / MAX_CONVENTION_LINES. The per-store caps
50
+ * are the single source of truth; this alias is derived from them.
51
+ */
52
+ export const MAX_TOTAL_LINES = MAX_RULE_LINES + MAX_CONVENTION_LINES;
34
53
 
35
54
  // --- Denylist (architecture.md §5.3) ----------------------------------------
36
55
  export const DENYLIST = [
@@ -181,6 +200,77 @@ export function resolveLedgerTarget(target, roots) {
181
200
  return fromRepo;
182
201
  }
183
202
 
203
+ /**
204
+ * The overlay root a rollback may write inside: the directory holding
205
+ * `rule-changes.jsonl` (normally `.ai.local`) or its nearest ancestor named
206
+ * `.ai.local` when a legacy ledger sits deeper. The repo root is never a
207
+ * rollback write surface.
208
+ */
209
+ function overlayRootFor(ledgerPath) {
210
+ const ledgerDirectory = path.dirname(path.resolve(ledgerPath));
211
+ let directory = ledgerDirectory;
212
+ for (;;) {
213
+ if (path.basename(directory) === '.ai.local') return directory;
214
+ const parent = path.dirname(directory);
215
+ if (parent === directory) return ledgerDirectory;
216
+ directory = parent;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Realpath of a target that may not exist yet: resolve the deepest existing
222
+ * ancestor, then append the missing suffix. `realpathSync` rejects a missing
223
+ * path, and a rollback target is often a file this entry is about to create.
224
+ */
225
+ function realpathNearest(target) {
226
+ let existing = path.resolve(target);
227
+ const missing = [];
228
+ for (;;) {
229
+ try {
230
+ return path.join(fs.realpathSync.native(existing), ...missing);
231
+ } catch (error) {
232
+ if (!error || (error.code !== 'ENOENT' && error.code !== 'ENOTDIR')) throw error;
233
+ const parent = path.dirname(existing);
234
+ if (parent === existing) throw error;
235
+ missing.unshift(path.basename(existing));
236
+ existing = parent;
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * A rollback write must land inside the ledger's `.ai.local` overlay. The
243
+ * lexical check alone lets a directory symlink inside the overlay redirect the
244
+ * write outside it, so every existing component below the root is rejected when
245
+ * it is a symlink, and the real paths must agree as well.
246
+ */
247
+ function assertInsideOverlay(target, ledgerPath) {
248
+ const root = overlayRootFor(ledgerPath);
249
+ const resolvedTarget = path.resolve(target);
250
+ const relative = path.relative(root, resolvedTarget);
251
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
252
+ throw new Error(`ledger target escapes the .ai.local overlay: ${target}`);
253
+ }
254
+ let current = root;
255
+ for (const part of relative.split(path.sep)) {
256
+ current = path.join(current, part);
257
+ let stat;
258
+ try {
259
+ stat = fs.lstatSync(current);
260
+ } catch (error) {
261
+ if (error && error.code === 'ENOENT') break;
262
+ throw error;
263
+ }
264
+ if (stat.isSymbolicLink()) {
265
+ throw new Error(`ledger target traverses a symlink: ${current}`);
266
+ }
267
+ }
268
+ const realRelative = path.relative(realpathNearest(root), realpathNearest(resolvedTarget));
269
+ if (realRelative === '' || realRelative.startsWith('..') || path.isAbsolute(realRelative)) {
270
+ throw new Error(`ledger target escapes the .ai.local overlay: ${target}`);
271
+ }
272
+ }
273
+
184
274
  function appendLedgerLine(ledgerPath, entry, roots) {
185
275
  const root = typeof roots === 'string' ? roots : roots.repo;
186
276
  const normalized = {
@@ -249,12 +339,21 @@ export function recoverPendingCommit(ledgerPath, roots) {
249
339
  const current = target == null ? null : readExisting(target);
250
340
  const landed = content === null ? current === null : current === content;
251
341
  if (landed && entry.action) {
342
+ // A promotion intent carries the ledger row separately: the row's `before`
343
+ // is the reviewed snapshot, while the intent's `before` is the rule file's
344
+ // previous content.
345
+ const row = payload.ledgerEntry ?? entry;
252
346
  const existing = parseLedger(readExisting(ledgerPath) ?? '');
253
- const recorded = existing.some((row) => row
254
- && row.action === entry.action
255
- && row.signature === entry.signature
256
- && row.at === entry.at);
257
- if (!recorded) appendLedgerLine(ledgerPath, entry, resolved);
347
+ const recorded = existing.some((item) => item
348
+ && item.action === row.action
349
+ && item.signature === row.signature
350
+ && item.at === row.at);
351
+ if (!recorded) appendLedgerLine(ledgerPath, row, resolved);
352
+ for (const removal of payload.removeTargets ?? []) {
353
+ try { fs.unlinkSync(removal); } catch (error) {
354
+ if (!error || error.code !== 'ENOENT') throw error;
355
+ }
356
+ }
258
357
  clearIntent(ledgerPath);
259
358
  return { recovered: 'committed', entry };
260
359
  }
@@ -314,6 +413,37 @@ function commitWrite({ ledgerPath, target, content, entry, roots }) {
314
413
  clearIntent(ledgerPath);
315
414
  }
316
415
 
416
+ /**
417
+ * Promotion commit: the rule file, then the seed removal, then the ledger row.
418
+ *
419
+ * The intent carries the ledger row separately. The row's `before` is the
420
+ * reviewed snapshot (the contract's binding); the intent's `before` is the rule
421
+ * file's previous content (null — a promotion creates the rule). A failure
422
+ * leaves the intent in place: `recoverPendingCommit` finishes a landed rule or
423
+ * drops an attempt that never wrote it, so a ledger error cannot silently lose
424
+ * the seed or leave an unrecorded rule.
425
+ */
426
+ function commitPromotion({ ledgerPath, ruleTarget, ruleContent, seedTarget, entry, roots }) {
427
+ const resolved = typeof roots === 'string' ? { project: roots, repo: roots } : roots;
428
+ const ledgerRow = {
429
+ ...entry,
430
+ target: entry.target == null ? null : toLedgerTarget(entry.target, resolved.repo),
431
+ };
432
+ writeIntent(ledgerPath, {
433
+ entry: { ...ledgerRow, before: null },
434
+ ledgerEntry: ledgerRow,
435
+ content: ruleContent,
436
+ removeTargets: [seedTarget],
437
+ roots: resolved,
438
+ });
439
+ writeFileAtomic(ruleTarget, ruleContent);
440
+ try { fs.unlinkSync(seedTarget); } catch (error) {
441
+ if (!error || error.code !== 'ENOENT') throw error;
442
+ }
443
+ appendLedgerLine(ledgerPath, ledgerRow, resolved);
444
+ clearIntent(ledgerPath);
445
+ }
446
+
317
447
  // --- Signature parsing + template re-derivation ------------------------------
318
448
 
319
449
  export function parseSignature(signature) {
@@ -610,6 +740,56 @@ function deriveSeedText({ stem, kind, issue, paths, command }) {
610
740
  return `glob: always\n\n## Body\n\n${deriveRuleText({ stem, kind, issue, paths, command })}`;
611
741
  }
612
742
 
743
+ // --- Provenance footer (ADR 0001 guard 1) -------------------------------------
744
+
745
+ // The footer states the authorship of a staged seed. Its four fields are all
746
+ // machine-derived and bounded — a validated signature, a timestamp, a validated
747
+ // slug and a fixed state token — so no task or spec prose can reach it (guard 1:
748
+ // rule text is re-derived from the signature, never copied from prose).
749
+ export const PROVENANCE_STATE = 'awaiting-human-promotion';
750
+ const PROVENANCE_RE = /^<!--\s*ai-local-provenance:\s*(\{.*\})\s*-->$/;
751
+ const KEBAB_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
752
+
753
+ /** The footer line for a staged seed. */
754
+ export function provenanceFooter({ signature, stagedAt, sourceSlug }) {
755
+ if (!SIGNATURE_RE.test(signature)) {
756
+ throw new Error(`invalid signature "${signature}"`);
757
+ }
758
+ if (!KEBAB_SLUG_RE.test(sourceSlug)) {
759
+ throw new Error(`invalid source slug "${sourceSlug}"`);
760
+ }
761
+ const payload = { signature, stagedAt, sourceSlug, state: PROVENANCE_STATE };
762
+ return `<!-- ai-local-provenance: ${JSON.stringify(payload)} -->`;
763
+ }
764
+
765
+ /** The seed file content: the reviewed body plus the trailing provenance line. */
766
+ export function withProvenanceFooter(body, provenance) {
767
+ return `${body.replace(/\n+$/, '')}\n${provenanceFooter(provenance)}\n`;
768
+ }
769
+
770
+ /** The parsed footer of a seed file, or null when it carries none. */
771
+ export function parseProvenanceFooter(content) {
772
+ const lines = content.split('\n');
773
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
774
+ const match = PROVENANCE_RE.exec(lines[i].trim());
775
+ if (!match) continue;
776
+ try {
777
+ return { payload: JSON.parse(match[1]), index: i };
778
+ } catch {
779
+ return null;
780
+ }
781
+ }
782
+ return null;
783
+ }
784
+
785
+ /** The reviewed content: the seed body without every provenance line. */
786
+ export function stripProvenanceFooter(content) {
787
+ const lines = content.split('\n');
788
+ const kept = lines.filter((line) => !PROVENANCE_RE.test(line.trim()));
789
+ if (kept.length === lines.length) return content;
790
+ return `${kept.join('\n').replace(/\n+$/, '')}\n`;
791
+ }
792
+
613
793
  /** Read-only `--status` lesson line: `lesson: pending` or `lesson: app/src [lint:js]`. */
614
794
  export function formatLessonStatus(lesson) {
615
795
  if (lesson === null) return 'lesson: pending';
@@ -692,21 +872,46 @@ export function thresholdAction(distinctSlugCount) {
692
872
 
693
873
  // --- Authoring envelope ------------------------------------------------------
694
874
 
695
- export function evaluateEnvelope({ ruleCount, lineCount, newRuleCount = 0, newLineCount = 0 }) {
696
- const nextRules = ruleCount + newRuleCount;
697
- const nextLines = lineCount + newLineCount;
698
- if (nextRules > MAX_ACTIVE_RULES) {
699
- return { ok: false, reason: `rule cap: ${nextRules} active rules would exceed ${MAX_ACTIVE_RULES}` };
875
+ /**
876
+ * One store's envelope. Each store is checked against its own caps, so a
877
+ * saturated `rules/` store never blocks a `conventions.md` write and a
878
+ * saturated `conventions.md` never blocks a promotion.
879
+ */
880
+ export function evaluateEnvelope({
881
+ store = 'rules',
882
+ ruleCount = 0,
883
+ lineCount = 0,
884
+ newRuleCount = 0,
885
+ newLineCount = 0,
886
+ }) {
887
+ if (store === 'rules') {
888
+ const nextRules = ruleCount + newRuleCount;
889
+ const nextLines = lineCount + newLineCount;
890
+ if (nextRules > MAX_ACTIVE_RULES) {
891
+ return { ok: false, reason: `rule cap: ${nextRules} active rules would exceed ${MAX_ACTIVE_RULES}` };
892
+ }
893
+ if (nextLines > MAX_RULE_LINES) {
894
+ return { ok: false, reason: `rule line cap: ${nextLines} nonempty lines would exceed ${MAX_RULE_LINES}` };
895
+ }
896
+ return { ok: true, reason: 'within envelope' };
700
897
  }
701
- if (nextLines > MAX_TOTAL_LINES) {
702
- return { ok: false, reason: `line cap: ${nextLines} nonempty lines would exceed ${MAX_TOTAL_LINES}` };
898
+ if (store === 'conventions') {
899
+ const nextLines = lineCount + newLineCount;
900
+ if (nextLines > MAX_CONVENTION_LINES) {
901
+ return { ok: false, reason: `conventions line cap: ${nextLines} nonempty lines would exceed ${MAX_CONVENTION_LINES}` };
902
+ }
903
+ return { ok: true, reason: 'within envelope' };
703
904
  }
704
- return { ok: true, reason: 'within envelope' };
905
+ throw new Error(`unknown envelope store "${store}"`);
705
906
  }
706
907
 
908
+ /**
909
+ * The two stores, counted separately: the human-promoted `rules/` files and
910
+ * the machine-written `conventions.md` bullets.
911
+ */
707
912
  export function countRulesAndLines({ rulesDir, conventionsPath }) {
708
913
  let ruleCount = 0;
709
- let lineCount = 0;
914
+ let ruleLineCount = 0;
710
915
  let names = [];
711
916
  try { names = fs.readdirSync(rulesDir); } catch (error) {
712
917
  if (!error || error.code !== 'ENOENT') throw error;
@@ -715,23 +920,27 @@ export function countRulesAndLines({ rulesDir, conventionsPath }) {
715
920
  if (!name.endsWith('.md')) continue;
716
921
  ruleCount += 1;
717
922
  try {
718
- lineCount += countNonEmptyLines(fs.readFileSync(path.join(rulesDir, name), 'utf8'));
923
+ ruleLineCount += countNonEmptyLines(fs.readFileSync(path.join(rulesDir, name), 'utf8'));
719
924
  } catch (error) {
720
925
  if (!error || error.code !== 'ENOENT') {
721
926
  throw new Error(`unreadable rule ${name}: ${error.message}`);
722
927
  }
723
928
  }
724
929
  }
930
+ let conventionLineCount = 0;
725
931
  if (conventionsPath) {
726
932
  try {
727
- lineCount += countNonEmptyLines(fs.readFileSync(conventionsPath, 'utf8'));
933
+ conventionLineCount = countNonEmptyLines(fs.readFileSync(conventionsPath, 'utf8'));
728
934
  } catch (error) {
729
935
  if (!error || error.code !== 'ENOENT') {
730
936
  throw new Error(`unreadable conventions: ${error.message}`);
731
937
  }
732
938
  }
733
939
  }
734
- return { ruleCount, lineCount };
940
+ return {
941
+ rules: { ruleCount, lineCount: ruleLineCount },
942
+ conventions: { lineCount: conventionLineCount },
943
+ };
735
944
  }
736
945
 
737
946
  // --- Conventions edit --------------------------------------------------------
@@ -846,10 +1055,12 @@ function tryUnloadOne({
846
1055
  prior,
847
1056
  signalsPath,
848
1057
  conventionsPath,
849
- ledgerPath,
850
1058
  now,
851
1059
  canonical,
852
1060
  roots,
1061
+ read = readExisting,
1062
+ writeTarget,
1063
+ dryRun = false,
853
1064
  }) {
854
1065
  const candidates = [...latestConventionsAddedBySignature(prior).entries()]
855
1066
  .sort(([a], [b]) => a.localeCompare(b));
@@ -857,7 +1068,7 @@ function tryUnloadOne({
857
1068
  const line = addedLine(appliedEntry.before, appliedEntry.after);
858
1069
  if (line === null) continue;
859
1070
  const target = resolveLedgerTarget(appliedEntry.target, roots);
860
- const current = readExisting(target);
1071
+ const current = read(target);
861
1072
  if (current === null || !conventionsFileHasTrimmedLine(current, line)) continue;
862
1073
  const signals = readSignalsForSignature(signalsPath, signature, canonical);
863
1074
  if (recurrenceSlugs({ signals, appliedAt: appliedEntry.at }).length < 2) continue;
@@ -873,9 +1084,9 @@ function tryUnloadOne({
873
1084
  agent: appliedEntry.agent,
874
1085
  slug: appliedEntry.slug,
875
1086
  };
876
- commitWrite({ ledgerPath, target, content: after, entry, roots });
1087
+ writeTarget({ target, content: after, entry });
877
1088
  prior.push(entry);
878
- markSignalsRolledBack(signature, { signalsPath, canonical });
1089
+ if (!dryRun) markSignalsRolledBack(signature, { signalsPath, canonical });
879
1090
  return { signature, target: appliedEntry.target };
880
1091
  }
881
1092
  return null;
@@ -906,6 +1117,7 @@ export function rollbackInverse(entry, options = {}) {
906
1117
  // not overwrite the intent file and lose the pending change.
907
1118
  recoverPendingCommit(ledgerPath, roots);
908
1119
  const target = resolveLedgerTarget(entry.target, roots);
1120
+ assertInsideOverlay(target, ledgerPath);
909
1121
  commitWrite({ ledgerPath, target, content: inverse.after ?? null, entry: inverse, roots });
910
1122
  return inverse;
911
1123
  } finally {
@@ -913,7 +1125,155 @@ export function rollbackInverse(entry, options = {}) {
913
1125
  }
914
1126
  }
915
1127
 
916
- // --- Engine ------------------------------------------------------------------
1128
+ // --- Rollback CLI ------------------------------------------------------------
1129
+
1130
+ const ISO_REF_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
1131
+
1132
+ function hasLaterRollback(entries, index, entry) {
1133
+ for (let later = index + 1; later < entries.length; later += 1) {
1134
+ const row = entries[later];
1135
+ if (!row || row.action !== 'rollback') continue;
1136
+ if (row.signature === entry.signature && row.target === entry.target) return true;
1137
+ }
1138
+ return false;
1139
+ }
1140
+
1141
+ function describeContent(content) {
1142
+ if (content == null) return '(absent)';
1143
+ const lines = String(content).split('\n');
1144
+ const first = lines.find((line) => line.trim() !== '') ?? '';
1145
+ return `${lines.length} line(s): ${first.trim().slice(0, 100)}`;
1146
+ }
1147
+
1148
+ /**
1149
+ * Resolve the newest invertible ledger entry. A ref is an exact ISO timestamp,
1150
+ * a target path (repo-relative or absolute), or a signature. A later `rollback`
1151
+ * row closes its entry, so a second rollback of the same row is a refusal.
1152
+ */
1153
+ export function resolveRollbackEntry({ ref, ledgerPath, roots }) {
1154
+ const wanted = typeof ref === 'string' ? ref.trim() : '';
1155
+ if (!wanted) return { ok: false, reason: 'no rollback reference given' };
1156
+ const entries = parseLedger(readExisting(ledgerPath) ?? '');
1157
+ const byTimestamp = ISO_REF_RE.test(wanted);
1158
+ const wantedTargets = [];
1159
+ if (!byTimestamp && (wanted.includes('/') || /\.md$/.test(wanted))) {
1160
+ // Ledger rows are repo-relative. A nested overlay's project-relative ref
1161
+ // must also resolve, so try the repo root and the project root.
1162
+ for (const root of [roots.repo, roots.project]) {
1163
+ try {
1164
+ const value = toLedgerTarget(path.isAbsolute(wanted) ? wanted : path.resolve(root, wanted), roots.repo);
1165
+ if (!wantedTargets.includes(value)) wantedTargets.push(value);
1166
+ } catch { /* try the other root */ }
1167
+ }
1168
+ if (wantedTargets.length === 0) wantedTargets.push(wanted);
1169
+ }
1170
+ const candidates = [];
1171
+ for (let index = 0; index < entries.length; index += 1) {
1172
+ const entry = entries[index];
1173
+ if (!entry || typeof entry !== 'object') continue;
1174
+ if (typeof entry.target !== 'string' || entry.target === '') continue;
1175
+ if (entry.action === 'rollback') continue;
1176
+ if (!('before' in entry) || !('after' in entry)) continue;
1177
+ if (hasLaterRollback(entries, index, entry)) continue;
1178
+ const matches = byTimestamp
1179
+ ? entry.at === wanted
1180
+ : wantedTargets.length > 0
1181
+ ? wantedTargets.includes(entry.target)
1182
+ : entry.signature === wanted;
1183
+ if (matches) candidates.push({ entry, index });
1184
+ }
1185
+ if (candidates.length === 0) {
1186
+ return { ok: false, reason: `no invertible ledger entry matches "${wanted}"` };
1187
+ }
1188
+ candidates.sort((left, right) => {
1189
+ const delta = (Date.parse(right.entry.at) || 0) - (Date.parse(left.entry.at) || 0);
1190
+ return delta !== 0 ? delta : right.index - left.index;
1191
+ });
1192
+ const newest = candidates[0];
1193
+ const sameInstant = candidates.filter((candidate) => candidate.entry.at === newest.entry.at);
1194
+ if (sameInstant.some((candidate) => candidate.entry.target !== newest.entry.target
1195
+ || candidate.entry.signature !== newest.entry.signature)) {
1196
+ return {
1197
+ ok: false,
1198
+ reason: `ambiguous: ${sameInstant.length} ledger entries share timestamp ${newest.entry.at}`,
1199
+ };
1200
+ }
1201
+ return {
1202
+ ok: true,
1203
+ entry: newest.entry,
1204
+ resolvedBy: byTimestamp ? 'timestamp' : wantedTargets.length > 0 ? 'target' : 'signature',
1205
+ };
1206
+ }
1207
+
1208
+ /**
1209
+ * Undo one ledger entry through `rollbackInverse`, fail closed.
1210
+ *
1211
+ * Pre-checks the target still holds the entry's `after` state, so a file edited
1212
+ * since the entry is never overwritten, and refuses a target outside the
1213
+ * ledger's `.ai.local` root. The inverse is itself a ledger row
1214
+ * (`action: "rollback"`), which is the safety row this command prints.
1215
+ */
1216
+ export function runRollback(options = {}) {
1217
+ const ref = options.ref;
1218
+ const baseDir = options.baseDir ?? path.join(process.cwd(), '.ai.local');
1219
+ const ledgerPath = options.ledgerPath ?? path.join(baseDir, 'rule-changes.jsonl');
1220
+ const lockPath = options.lockPath ?? path.join(baseDir, '.rules.lock');
1221
+ const now = options.now ?? (() => new Date().toISOString());
1222
+ const roots = resolveRoots(ledgerPath, options);
1223
+ const refuse = (reason) => ({
1224
+ ok: false,
1225
+ ref,
1226
+ reason,
1227
+ report: `Rollback\nref: ${ref}\nrefused: ${reason}. Nothing was written.\n`,
1228
+ });
1229
+
1230
+ const resolution = resolveRollbackEntry({ ref, ledgerPath, roots });
1231
+ if (!resolution.ok) return refuse(resolution.reason);
1232
+ const entry = resolution.entry;
1233
+ const target = resolveLedgerTarget(entry.target, roots);
1234
+ const current = readExisting(target);
1235
+ const expected = entry.after ?? null;
1236
+ const unchanged = expected === null ? current === null : current === expected;
1237
+ if (!unchanged) {
1238
+ return refuse(`target ${entry.target} changed since the ledger entry`);
1239
+ }
1240
+ try {
1241
+ assertInsideOverlay(target, ledgerPath);
1242
+ } catch (error) {
1243
+ return refuse(error instanceof Error ? error.message : String(error));
1244
+ }
1245
+
1246
+ let inverse;
1247
+ try {
1248
+ inverse = rollbackInverse(entry, {
1249
+ ledgerPath,
1250
+ lockPath,
1251
+ now,
1252
+ projectRoot: roots.project,
1253
+ repoRoot: roots.repo,
1254
+ });
1255
+ } catch (error) {
1256
+ return refuse(`the rollback write failed: ${error instanceof Error ? error.message : String(error)}`);
1257
+ }
1258
+
1259
+ const lines = [
1260
+ 'Rollback',
1261
+ `ref: ${ref} (resolved by ${resolution.resolvedBy})`,
1262
+ `entry: ${entry.signature} ${entry.action} → ${entry.target} at ${entry.at}`,
1263
+ `before: ${describeContent(entry.before)}`,
1264
+ `after: ${describeContent(entry.after)}`,
1265
+ `inverse: ${inverse.action} → ${inverse.target} at ${inverse.at}`,
1266
+ `safety row: ${JSON.stringify(inverse)}`,
1267
+ ];
1268
+ return {
1269
+ ok: true,
1270
+ ref,
1271
+ entry,
1272
+ inverse,
1273
+ report: `${lines.join('\n')}\n`,
1274
+ };
1275
+ }
1276
+
917
1277
 
918
1278
  function enrichGroups(groups, signalsPath, canonical = (signature) => signature) {
919
1279
  const bySignature = new Map(
@@ -1023,7 +1383,7 @@ function planConventions(ctx, decision) {
1023
1383
  const target = ctx.conventionsPath;
1024
1384
  const section = KIND_SECTION[decision.kind] ?? 'Patterns';
1025
1385
  const entry = decision.conventionsEntry ?? imperativeSentence(decision.kind, decision.phrase);
1026
- const before = readExisting(target) ?? '';
1386
+ const before = ctx.read(target) ?? '';
1027
1387
  if (conventionsEntryExists(before, entry)) {
1028
1388
  return { type: 'skipped', reason: 'dedup: identical entry already present', target };
1029
1389
  }
@@ -1038,8 +1398,8 @@ function planConventions(ctx, decision) {
1038
1398
  };
1039
1399
  }
1040
1400
  const envelope = evaluateEnvelope({
1041
- ruleCount: ctx.envelope.ruleCount,
1042
- lineCount: ctx.envelope.lineCount,
1401
+ store: 'conventions',
1402
+ lineCount: ctx.envelope.conventions.lineCount,
1043
1403
  newLineCount: addedLines,
1044
1404
  });
1045
1405
  if (!envelope.ok) return { type: 'blocked', reason: envelope.reason, action: 'conventions-added' };
@@ -1091,13 +1451,14 @@ function hasOpenStage(entries, signature) {
1091
1451
  || entry.action === 'rule-created'
1092
1452
  || entry.action === 'applied'
1093
1453
  || entry.action === 'rejected'
1454
+ || entry.action === 'seed-promoted'
1094
1455
  ) open = false;
1095
1456
  }
1096
1457
  return open;
1097
1458
  }
1098
1459
 
1099
1460
  function proposedConventions(ctx, decision) {
1100
- const before = readExisting(ctx.conventionsPath);
1461
+ const before = ctx.read(ctx.conventionsPath);
1101
1462
  if (before === null) return { before, after: null };
1102
1463
  const section = KIND_SECTION[decision.kind] ?? 'Patterns';
1103
1464
  const bullet = decision.conventionsEntry ?? imperativeSentence(decision.kind, decision.phrase);
@@ -1108,17 +1469,17 @@ function proposedConventions(ctx, decision) {
1108
1469
  }
1109
1470
  }
1110
1471
 
1111
- function appendStage({ prior, ledgerPath, decision, action, target, before, after, now, staged, reason, roots }) {
1472
+ function appendStage({ prior, appendLedger, decision, action, target, before, after, now, staged, reason }) {
1112
1473
  staged.push({ signature: decision.signature, target, reason });
1113
1474
  if (hasOpenStage(prior, decision.signature)) return;
1114
1475
  const entry = ledgerEntry(decision, action, target, before, after, now);
1115
- appendLedgerLine(ledgerPath, entry, roots);
1476
+ appendLedger(entry);
1116
1477
  prior.push(entry);
1117
1478
  }
1118
1479
 
1119
- function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir, roots }) {
1480
+ function stageNewRule({ decision, ctx, prior, now, staged, rulesDir, appendLedger, writeTarget }) {
1120
1481
  const rulePath = path.join(rulesDir, `${decision.stem}.md`);
1121
- const editsExisting = fs.existsSync(rulePath);
1482
+ const editsExisting = ctx.read(rulePath) !== null;
1122
1483
  const band = classifyBand({
1123
1484
  denied: false,
1124
1485
  compliance: Boolean(decision.compliance),
@@ -1130,44 +1491,68 @@ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir,
1130
1491
  if (editsExisting) {
1131
1492
  appendStage({
1132
1493
  prior,
1133
- ledgerPath,
1494
+ appendLedger,
1134
1495
  decision,
1135
1496
  action: 'staged',
1136
1497
  target: rulePath,
1137
- before: readExisting(rulePath),
1498
+ before: ctx.read(rulePath),
1138
1499
  after: decision.ruleText,
1139
1500
  now,
1140
1501
  staged,
1141
1502
  reason: band.reason,
1142
- roots,
1143
1503
  });
1144
1504
  return;
1145
1505
  }
1146
1506
  const seed = planSeed(ctx, decision);
1147
- const existing = readExisting(seed.target);
1507
+ const existing = ctx.read(seed.target);
1148
1508
  if (existing !== null) {
1509
+ // The reviewed snapshot is the seed body without its provenance line, so
1510
+ // the ledger row and the file never disagree about what was reviewed.
1511
+ // An existing seed is left byte-for-byte alone: a file the engine never
1512
+ // wrote (an `init`-seeded template copy) must not carry a machine-authorship
1513
+ // claim.
1514
+ const reviewed = stripProvenanceFooter(existing);
1149
1515
  appendStage({
1150
1516
  prior,
1151
- ledgerPath,
1517
+ appendLedger,
1152
1518
  decision,
1153
1519
  action: 'seed-staged',
1154
1520
  target: seed.target,
1155
1521
  before: existing,
1156
- after: existing,
1522
+ after: reviewed,
1157
1523
  now,
1158
1524
  staged,
1159
1525
  reason: 'seed already staged',
1160
- roots,
1161
1526
  });
1162
1527
  return;
1163
1528
  }
1164
1529
  const reason = decision.compliance ?? (band.verdict === 'stage' ? band.reason : 'new rule staged for human promote');
1530
+ // The engine writes the provenance footer; the ledger row keeps the reviewed
1531
+ // body, so the footer can never make the row and the file disagree.
1532
+ const stagedAt = now();
1533
+ const seedFile = withProvenanceFooter(seed.content, {
1534
+ signature: decision.signature,
1535
+ stagedAt,
1536
+ sourceSlug: sourceSlugFor(decision),
1537
+ });
1165
1538
  const entry = ledgerEntry(decision, 'seed-staged', seed.target, null, seed.content, now);
1166
- commitWrite({ ledgerPath, target: seed.target, content: seed.content, entry, roots });
1539
+ writeTarget({ target: seed.target, content: seedFile, entry });
1167
1540
  prior.push(entry);
1168
1541
  staged.push({ signature: decision.signature, target: seed.target, reason });
1169
1542
  }
1170
1543
 
1544
+ /**
1545
+ * The task slug the seed came from. The signal store validates it as
1546
+ * kebab-case, so the footer's slug field stays bounded (guard 1).
1547
+ */
1548
+ function sourceSlugFor(decision) {
1549
+ for (const slug of decision.slugs ?? []) {
1550
+ if (typeof slug === 'string' && KEBAB_SLUG_RE.test(slug)) return slug;
1551
+ }
1552
+ if (KEBAB_SLUG_RE.test(decision.slug)) return decision.slug;
1553
+ return decision.stem;
1554
+ }
1555
+
1171
1556
  function entrySlugs(entry) {
1172
1557
  const slugs = [];
1173
1558
  if (Array.isArray(entry?.slugs)) {
@@ -1216,6 +1601,7 @@ function hasOpenPendingLesson(entries, signature) {
1216
1601
  else if (
1217
1602
  entry.action === 'staged'
1218
1603
  || entry.action === 'seed-staged'
1604
+ || entry.action === 'seed-promoted'
1219
1605
  || entry.action === 'conventions-added'
1220
1606
  || entry.action === 'rollback'
1221
1607
  ) open = false;
@@ -1240,13 +1626,55 @@ function applyDecisionsUnderLock({
1240
1626
  canonical,
1241
1627
  rootDir,
1242
1628
  roots,
1629
+ dryRun = false,
1630
+ writes = [],
1243
1631
  }) {
1244
- const token = acquireLock(lockPath);
1632
+ // A dry run takes no lock and creates no `.lock`/`.intent` file: it must be
1633
+ // byte-free on disk. The decision path below is the one the real run uses.
1634
+ const token = dryRun ? null : acquireLock(lockPath);
1635
+ const virtual = new Map();
1636
+ const read = dryRun
1637
+ ? (target) => (virtual.has(target) ? virtual.get(target) : readExisting(target))
1638
+ : readExisting;
1639
+ const recordLedger = (entry) => {
1640
+ if (!dryRun) {
1641
+ appendLedgerLine(ledgerPath, entry, roots);
1642
+ return;
1643
+ }
1644
+ let target = entry.target;
1645
+ if (typeof target === 'string') {
1646
+ try { target = toLedgerTarget(target, roots.repo); } catch { /* keep the raw target in the preview */ }
1647
+ }
1648
+ writes.push({ kind: 'ledger', entry: { ...entry, target } });
1649
+ };
1650
+ const writeTarget = ({ target, content, entry }) => {
1651
+ if (!dryRun) {
1652
+ commitWrite({ ledgerPath, target, content, entry, roots });
1653
+ return;
1654
+ }
1655
+ writes.push({ kind: 'file', target, before: read(target), after: content ?? null, entry });
1656
+ recordLedger(entry);
1657
+ virtual.set(target, content ?? null);
1658
+ };
1659
+ const appendLedger = (entry) => recordLedger(entry);
1245
1660
  try {
1246
- const recovery = recoverPendingCommit(ledgerPath, roots);
1661
+ const recovery = dryRun ? null : recoverPendingCommit(ledgerPath, roots);
1247
1662
  let envelope = countRulesAndLines({ rulesDir, conventionsPath });
1248
1663
  const prior = parseLedger(readExisting(ledgerPath) ?? '');
1249
- const ctx = { rulesDir, libraryDir, conventionsPath, envelope };
1664
+ const ctx = { rulesDir, libraryDir, conventionsPath, envelope, read };
1665
+ const refreshEnvelope = () => {
1666
+ if (!dryRun) {
1667
+ envelope = countRulesAndLines({ rulesDir, conventionsPath });
1668
+ ctx.envelope = envelope;
1669
+ return;
1670
+ }
1671
+ // Seeds live in `rules-library/`, so only the machine store moves here.
1672
+ envelope = {
1673
+ ...envelope,
1674
+ conventions: { lineCount: countNonEmptyLines(read(conventionsPath) ?? '') },
1675
+ };
1676
+ ctx.envelope = envelope;
1677
+ };
1250
1678
  const applied = [];
1251
1679
  const staged = [];
1252
1680
  const skipped = [];
@@ -1277,7 +1705,7 @@ function applyDecisionsUnderLock({
1277
1705
  slugs: Array.isArray(item.decision.slugs) ? [...item.decision.slugs] : [],
1278
1706
  reason: item.reason,
1279
1707
  };
1280
- appendLedgerLine(ledgerPath, entry, roots);
1708
+ appendLedger(entry);
1281
1709
  prior.push(entry);
1282
1710
  staged.push({
1283
1711
  signature: item.decision.signature,
@@ -1290,24 +1718,24 @@ function applyDecisionsUnderLock({
1290
1718
  prior,
1291
1719
  signalsPath,
1292
1720
  conventionsPath,
1293
- ledgerPath,
1294
1721
  now,
1295
1722
  canonical,
1296
1723
  roots,
1724
+ read,
1725
+ writeTarget,
1726
+ dryRun,
1297
1727
  });
1298
1728
  let decisionsToApply = decisions;
1299
1729
  if (unloadedOne) {
1300
1730
  unloaded.push(unloadedOne);
1301
- envelope = countRulesAndLines({ rulesDir, conventionsPath });
1302
- ctx.envelope = envelope;
1731
+ refreshEnvelope();
1303
1732
  decisionsToApply = decisions.filter((item) => item.signature !== unloadedOne.signature);
1304
1733
  }
1305
1734
 
1306
1735
  for (const decision of decisionsToApply) {
1307
1736
  if (decision.tier.action === 'create') {
1308
- stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir, roots });
1309
- envelope = countRulesAndLines({ rulesDir, conventionsPath });
1310
- ctx.envelope = envelope;
1737
+ stageNewRule({ decision, ctx, prior, now, staged, rulesDir, appendLedger, writeTarget });
1738
+ refreshEnvelope();
1311
1739
  continue;
1312
1740
  }
1313
1741
  if (decision.tier.action !== 'edit') continue;
@@ -1324,7 +1752,7 @@ function applyDecisionsUnderLock({
1324
1752
  const proposed = proposedConventions(ctx, decision);
1325
1753
  appendStage({
1326
1754
  prior,
1327
- ledgerPath,
1755
+ appendLedger,
1328
1756
  decision,
1329
1757
  action: 'staged',
1330
1758
  target: conventionsPath,
@@ -1333,7 +1761,6 @@ function applyDecisionsUnderLock({
1333
1761
  now,
1334
1762
  staged,
1335
1763
  reason: decision.compliance ?? band.reason,
1336
- roots,
1337
1764
  });
1338
1765
  continue;
1339
1766
  }
@@ -1347,7 +1774,7 @@ function applyDecisionsUnderLock({
1347
1774
  const proposed = proposedConventions(ctx, decision);
1348
1775
  appendStage({
1349
1776
  prior,
1350
- ledgerPath,
1777
+ appendLedger,
1351
1778
  decision,
1352
1779
  action: 'staged',
1353
1780
  target: plan.target,
@@ -1356,7 +1783,6 @@ function applyDecisionsUnderLock({
1356
1783
  now,
1357
1784
  staged,
1358
1785
  reason: plan.reason,
1359
- roots,
1360
1786
  });
1361
1787
  continue;
1362
1788
  }
@@ -1369,7 +1795,7 @@ function applyDecisionsUnderLock({
1369
1795
  const proposed = proposedConventions(ctx, decision);
1370
1796
  appendStage({
1371
1797
  prior,
1372
- ledgerPath,
1798
+ appendLedger,
1373
1799
  decision,
1374
1800
  action: 'staged',
1375
1801
  target: plan.target,
@@ -1380,36 +1806,36 @@ function applyDecisionsUnderLock({
1380
1806
  reason: decisionSlugs.length === 0
1381
1807
  ? 'rate limit: no contributing slug to spend'
1382
1808
  : 'rate limit: ≤1 applied rule per task',
1383
- roots,
1384
1809
  });
1385
1810
  continue;
1386
1811
  }
1387
1812
 
1388
- const before = readExisting(plan.target);
1813
+ const before = read(plan.target);
1389
1814
  const after = addConventionsEntry(before ?? '', plan.section, plan.entry);
1390
1815
  const entry = ledgerEntry(decision, plan.action, plan.target, before, after, now);
1391
- commitWrite({ ledgerPath, target: plan.target, content: after, entry, roots });
1816
+ writeTarget({ target: plan.target, content: after, entry });
1392
1817
  prior.push(entry);
1393
1818
  for (const slug of decisionSlugs) appliedSlugs.add(slug);
1394
1819
  applied.push({ signature: decision.signature, target: plan.target });
1395
- envelope = countRulesAndLines({ rulesDir, conventionsPath });
1396
- ctx.envelope = envelope;
1820
+ refreshEnvelope();
1397
1821
  }
1398
1822
 
1399
- for (const item of applied) {
1400
- try {
1401
- markSignalsApplied(item.signature, { signalsPath, canonical });
1402
- } catch (error) {
1403
- errors.push({
1404
- signature: item.signature,
1405
- reason: error instanceof Error ? error.message : String(error),
1406
- });
1823
+ if (!dryRun) {
1824
+ for (const item of applied) {
1825
+ try {
1826
+ markSignalsApplied(item.signature, { signalsPath, canonical });
1827
+ } catch (error) {
1828
+ errors.push({
1829
+ signature: item.signature,
1830
+ reason: error instanceof Error ? error.message : String(error),
1831
+ });
1832
+ }
1407
1833
  }
1408
1834
  }
1409
1835
 
1410
- return { applied, staged, skipped, unloaded, envelope, errors };
1836
+ return { applied, staged, skipped, unloaded, envelope, errors, writes };
1411
1837
  } finally {
1412
- releaseLock(lockPath, token);
1838
+ if (!dryRun) releaseLock(lockPath, token);
1413
1839
  }
1414
1840
  }
1415
1841
 
@@ -1432,6 +1858,7 @@ export function runImprover(options = {}) {
1432
1858
  const aliasPath = options.aliasPath ?? path.join(baseDir, 'signature-aliases.json');
1433
1859
  const catalogPath = options.catalogPath ?? path.join(baseDir, 'signature-catalog.json');
1434
1860
  const now = options.now ?? (() => new Date().toISOString());
1861
+ const dryRun = options.dryRun === true;
1435
1862
 
1436
1863
  const errors = [];
1437
1864
  const aliasLoad = loadAliasMap(aliasPath);
@@ -1502,9 +1929,10 @@ export function runImprover(options = {}) {
1502
1929
  let applySkipped = [];
1503
1930
  let unloaded = [];
1504
1931
  let applyErrors = [];
1505
- let envelope = { ruleCount: 0, lineCount: 0 };
1932
+ let writes = [];
1933
+ let envelope = { rules: { ruleCount: 0, lineCount: 0 }, conventions: { lineCount: 0 } };
1506
1934
  try {
1507
- ({ applied, staged, skipped: applySkipped, unloaded, envelope, errors: applyErrors } = applyDecisionsUnderLock({
1935
+ ({ applied, staged, skipped: applySkipped, unloaded, envelope, errors: applyErrors, writes } = applyDecisionsUnderLock({
1508
1936
  decisions,
1509
1937
  visiblePending,
1510
1938
  rulesDir,
@@ -1517,6 +1945,7 @@ export function runImprover(options = {}) {
1517
1945
  canonical,
1518
1946
  rootDir,
1519
1947
  roots,
1948
+ dryRun,
1520
1949
  }));
1521
1950
  errors.push(...applyErrors);
1522
1951
  } catch (error) {
@@ -1535,6 +1964,14 @@ export function runImprover(options = {}) {
1535
1964
  rejected,
1536
1965
  errors,
1537
1966
  envelope,
1967
+ dryRun,
1968
+ writes,
1969
+ decisions: decisions.map((decision) => ({
1970
+ signature: decision.signature,
1971
+ tier: decision.tier,
1972
+ target: null,
1973
+ action: decision.tier.action,
1974
+ })),
1538
1975
  report: renderReport({
1539
1976
  applied,
1540
1977
  staged,
@@ -1549,6 +1986,15 @@ export function runImprover(options = {}) {
1549
1986
  };
1550
1987
  }
1551
1988
 
1989
+ /**
1990
+ * The read-only twin of `runImprover`: the same decision path, no lock, no
1991
+ * intent, no file, no signal mutation, no ledger row. `writes` is the exact
1992
+ * ordered write plan (`file` and `ledger` operations) the real run would use.
1993
+ */
1994
+ export function previewImprover(options = {}) {
1995
+ return runImprover({ ...options, dryRun: true });
1996
+ }
1997
+
1552
1998
  function renderTarget(target, roots) {
1553
1999
  if (target == null) return '(no file)';
1554
2000
  if (typeof target !== 'string') return String(target);
@@ -1559,6 +2005,138 @@ function renderTarget(target, roots) {
1559
2005
  }
1560
2006
  }
1561
2007
 
2008
+ /**
2009
+ * The open `seed-staged` row of a staged seed, or null when the seed has no
2010
+ * open stage row (a seed without a row was never reviewed by the engine).
2011
+ */
2012
+ function findOpenSeedStage(entries, seedPath, roots) {
2013
+ const wanted = toLedgerTarget(seedPath, roots.repo);
2014
+ let found = null;
2015
+ for (const entry of entries) {
2016
+ if (!entry || entry.action !== 'seed-staged') continue;
2017
+ if (entry.target !== wanted) continue;
2018
+ found = entry;
2019
+ }
2020
+ if (!found) return null;
2021
+ if (!hasOpenStage(entries, found.signature)) return null;
2022
+ return found;
2023
+ }
2024
+
2025
+ /**
2026
+ * Promote a staged seed into `.ai.local/rules/`.
2027
+ *
2028
+ * The promotion is one auditable operation: locate the seed and its open
2029
+ * `seed-staged` row, strip the provenance footer, write the rule, remove the
2030
+ * seed and append the `seed-promoted` row. The row binds the promoted file to
2031
+ * the reviewed snapshot (the `seed-staged` row's `after`); a seed edited
2032
+ * between staging and promotion is recorded as a divergence, not refused.
2033
+ */
2034
+ export function runPromotion(options = {}) {
2035
+ const stem = options.stem;
2036
+ const baseDir = options.baseDir ?? path.join(process.cwd(), '.ai.local');
2037
+ const rulesDir = options.rulesDir ?? path.join(baseDir, 'rules');
2038
+ const libraryDir = options.libraryDir ?? path.join(baseDir, 'rules-library');
2039
+ const ledgerPath = options.ledgerPath ?? path.join(baseDir, 'rule-changes.jsonl');
2040
+ const lockPath = options.lockPath ?? path.join(baseDir, '.rules.lock');
2041
+ const now = options.now ?? (() => new Date().toISOString());
2042
+ const roots = resolveRoots(ledgerPath, options);
2043
+
2044
+ const refuse = (reason) => ({
2045
+ ok: false,
2046
+ stem,
2047
+ reason,
2048
+ report: `Seed promotion\nstem: ${stem}\nrefused: ${reason}\n`,
2049
+ });
2050
+
2051
+ if (typeof stem !== 'string' || stem === '') return refuse('no stem given');
2052
+ try {
2053
+ validateStem(stem);
2054
+ } catch (error) {
2055
+ return refuse(error instanceof Error ? error.message : String(error));
2056
+ }
2057
+
2058
+ const seedPath = path.join(libraryDir, `${stem}.md`);
2059
+ const rulePath = path.join(rulesDir, `${stem}.md`);
2060
+ const token = acquireLock(lockPath);
2061
+ try {
2062
+ const recovery = recoverPendingCommit(ledgerPath, roots);
2063
+ if (recovery?.recovered === 'conflict') {
2064
+ return refuse('a previous commit intent matches neither the previous nor the written file');
2065
+ }
2066
+ const seedContent = readExisting(seedPath);
2067
+ if (seedContent === null) return refuse(`no staged seed at ${renderTarget(seedPath, roots)}`);
2068
+ const promoted = stripProvenanceFooter(seedContent);
2069
+ const prior = parseLedger(readExisting(ledgerPath) ?? '');
2070
+ const stageRow = findOpenSeedStage(prior, seedPath, roots);
2071
+ if (!stageRow) return refuse(`no open seed-staged ledger row for "${stem}"`);
2072
+ if (readExisting(rulePath) !== null) return refuse(`a rule named "${stem}" is already active`);
2073
+
2074
+ const counts = countRulesAndLines({ rulesDir, conventionsPath: null });
2075
+ const envelope = evaluateEnvelope({
2076
+ store: 'rules',
2077
+ ruleCount: counts.rules.ruleCount,
2078
+ lineCount: counts.rules.lineCount,
2079
+ newRuleCount: 1,
2080
+ newLineCount: countNonEmptyLines(promoted),
2081
+ });
2082
+ if (!envelope.ok) return refuse(envelope.reason);
2083
+
2084
+ const reviewed = typeof stageRow.after === 'string' ? stageRow.after : promoted;
2085
+ const divergence = reviewed !== promoted;
2086
+ const entry = {
2087
+ signature: stageRow.signature,
2088
+ action: 'seed-promoted',
2089
+ target: rulePath,
2090
+ before: reviewed,
2091
+ after: promoted,
2092
+ at: now(),
2093
+ agent: stageRow.agent,
2094
+ slug: stageRow.slug,
2095
+ slugs: Array.isArray(stageRow.slugs) ? [...stageRow.slugs] : [],
2096
+ };
2097
+ try {
2098
+ commitPromotion({
2099
+ ledgerPath,
2100
+ ruleTarget: rulePath,
2101
+ ruleContent: promoted,
2102
+ seedTarget: seedPath,
2103
+ entry,
2104
+ roots,
2105
+ });
2106
+ } catch (error) {
2107
+ const reason = error instanceof Error ? error.message : String(error);
2108
+ return refuse(
2109
+ `the promotion write failed: ${reason}. The commit intent is retained; ` +
2110
+ 'run `node .ai.local/scripts/run.mjs` to finish or drop it',
2111
+ );
2112
+ }
2113
+
2114
+ const lines = [
2115
+ 'Seed promotion',
2116
+ `stem: ${stem}`,
2117
+ `promoted: ${renderTarget(rulePath, roots)}`,
2118
+ `seed removed: ${renderTarget(seedPath, roots)}`,
2119
+ `ledger: seed-promoted (${stageRow.signature})`,
2120
+ divergence
2121
+ ? 'divergence: the seed changed between staging and promotion — recorded in the ledger row'
2122
+ : 'divergence: none',
2123
+ ];
2124
+ return {
2125
+ ok: true,
2126
+ stem,
2127
+ signature: stageRow.signature,
2128
+ target: rulePath,
2129
+ seedTarget: seedPath,
2130
+ reviewed,
2131
+ promoted,
2132
+ divergence,
2133
+ report: `${lines.join('\n')}\n`,
2134
+ };
2135
+ } finally {
2136
+ releaseLock(lockPath, token);
2137
+ }
2138
+ }
2139
+
1562
2140
  function appendSkipGroup(lines, items, heading) {
1563
2141
  if (items.length === 0) return;
1564
2142
  lines.push('', heading);
@@ -1568,7 +2146,8 @@ function appendSkipGroup(lines, items, heading) {
1568
2146
  function renderReport({ applied, staged, skipped, rejected, unloaded = [], errors, envelope, roots }) {
1569
2147
  const lines = [
1570
2148
  'Self-learning rule improver',
1571
- `envelope: ${envelope.ruleCount}/${MAX_ACTIVE_RULES} rules, ${envelope.lineCount}/${MAX_TOTAL_LINES} lines`,
2149
+ `rules envelope: ${envelope.rules.lineCount}/${MAX_RULE_LINES} lines, ${envelope.rules.ruleCount}/${MAX_ACTIVE_RULES} rules`,
2150
+ `conventions envelope: ${envelope.conventions.lineCount}/${MAX_CONVENTION_LINES} lines`,
1572
2151
  '',
1573
2152
  `applied (${applied.length}) — auto, low-risk, reversible`,
1574
2153
  ];
@@ -1598,6 +2177,27 @@ function renderReport({ applied, staged, skipped, rejected, unloaded = [], error
1598
2177
  }
1599
2178
 
1600
2179
  // CLI entry: run directly (node rule-improver.mjs) and print the report.
2180
+ // `--promote <stem>` promotes a staged seed into `.ai.local/rules/`.
2181
+ // `--rollback <ref>` undoes one ledger entry; ref = target path, signature, or
2182
+ // ISO timestamp. Fail-closed: a changed target or an ambiguous ref writes nothing.
1601
2183
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
1602
- process.stdout.write(runImprover().report);
2184
+ const rollbackIndex = process.argv.indexOf('--rollback');
2185
+ const promoteIndex = process.argv.indexOf('--promote');
2186
+ if (rollbackIndex !== -1) {
2187
+ const ref = process.argv[rollbackIndex + 1];
2188
+ if (!ref || ref.startsWith('-')) {
2189
+ process.stderr.write('Usage: node .ai.local/scripts/rule-improver.mjs --rollback <target|signature|ISO timestamp>\n');
2190
+ process.exitCode = 2;
2191
+ } else {
2192
+ const result = runRollback({ ref });
2193
+ process.stdout.write(result.report);
2194
+ if (!result.ok) process.exitCode = 1;
2195
+ }
2196
+ } else if (promoteIndex !== -1) {
2197
+ const result = runPromotion({ stem: process.argv[promoteIndex + 1] });
2198
+ process.stdout.write(result.report);
2199
+ if (!result.ok) process.exitCode = 1;
2200
+ } else {
2201
+ process.stdout.write(runImprover().report);
2202
+ }
1603
2203
  }