@bonesofspring/ai-rules 0.2.50 → 0.2.52

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 (400) hide show
  1. package/CHANGELOG.md +122 -1
  2. package/README.md +3 -1
  3. package/bin/cli.js +65 -13
  4. package/bin/lib/ai-local-drift.js +706 -0
  5. package/bin/lib/seed-ai-local-team.js +169 -40
  6. package/bin/mavis-install.js +8 -0
  7. package/bin/opencode-install.js +15 -2
  8. package/docs/LOCAL-OVERLAY.md +77 -1
  9. package/docs/PRESET-CONTRIBUTION.md +11 -9
  10. package/package.json +5 -1
  11. package/presets/_shared/ai-local/scripts/efficacy-oracle.mjs +1 -1
  12. package/presets/_shared/ai-local/scripts/manifest.mjs +13 -3
  13. package/presets/_shared/ai-local/scripts/rule-improver.mjs +872 -99
  14. package/presets/_shared/ai-local/scripts/run.mjs +76 -3
  15. package/presets/_shared/ai-local/scripts/signals.mjs +123 -7
  16. package/presets/_shared/core/meta/preset-pr-checklist.md +1 -1
  17. package/presets/_shared/core/quality/anti-hallucination-contract.md +2 -0
  18. package/presets/_shared/core/quality/interactive-questions.md +8 -8
  19. package/presets/_shared/core/review/code-review-mr.md +20 -1
  20. package/presets/_shared/core/review/receiving-code-review.md +7 -0
  21. package/presets/claude/android-kotlin/agents/code-reviewer.md +15 -0
  22. package/presets/claude/android-kotlin/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  23. package/presets/claude/android-kotlin/rules/tooling-and-review/code-review.md +20 -1
  24. package/presets/claude/android-kotlin/rules/tooling-and-review/interactive-questions.md +8 -8
  25. package/presets/claude/android-kotlin/rules/tooling-and-review/language-policy.md +1 -1
  26. package/presets/claude/android-kotlin/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  27. package/presets/claude/android-kotlin/skills/code-review/SKILL.md +11 -1
  28. package/presets/claude/go/agents/code-reviewer.md +37 -2
  29. package/presets/claude/go/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  30. package/presets/claude/go/rules/tooling-and-review/code-review.md +20 -1
  31. package/presets/claude/go/rules/tooling-and-review/interactive-questions.md +8 -8
  32. package/presets/claude/go/rules/tooling-and-review/language-policy.md +1 -1
  33. package/presets/claude/go/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  34. package/presets/claude/go/skills/code-review/SKILL.md +10 -1
  35. package/presets/claude/ios-swift/agents/code-reviewer.md +15 -0
  36. package/presets/claude/ios-swift/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  37. package/presets/claude/ios-swift/rules/tooling-and-review/code-review.md +20 -1
  38. package/presets/claude/ios-swift/rules/tooling-and-review/interactive-questions.md +8 -8
  39. package/presets/claude/ios-swift/rules/tooling-and-review/language-policy.md +1 -1
  40. package/presets/claude/ios-swift/rules/tooling-and-review/post-change-build.md +1 -1
  41. package/presets/claude/ios-swift/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  42. package/presets/claude/ios-swift/skills/code-review/SKILL.md +11 -1
  43. package/presets/claude/java/agents/code-reviewer.md +37 -2
  44. package/presets/claude/java/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  45. package/presets/claude/java/rules/tooling-and-review/code-review.md +20 -1
  46. package/presets/claude/java/rules/tooling-and-review/interactive-questions.md +8 -8
  47. package/presets/claude/java/rules/tooling-and-review/language-policy.md +1 -1
  48. package/presets/claude/java/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  49. package/presets/claude/java/skills/code-review/SKILL.md +10 -1
  50. package/presets/claude/mcp-ts/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  51. package/presets/claude/mcp-ts/rules/tooling-and-review/code-review.md +20 -1
  52. package/presets/claude/mcp-ts/rules/tooling-and-review/interactive-questions.md +8 -8
  53. package/presets/claude/mcp-ts/rules/tooling-and-review/language-policy.md +1 -1
  54. package/presets/claude/mcp-ts/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  55. package/presets/claude/mcp-ts/skills/code-review/SKILL.md +8 -0
  56. package/presets/claude/next/MCP.md +7 -0
  57. package/presets/claude/next/README.md +1 -1
  58. package/presets/claude/next/REPO_AGENTS.md +1 -1
  59. package/presets/claude/next/agents/README.md +3 -3
  60. package/presets/claude/next/agents/build-verifier.md +9 -3
  61. package/presets/claude/next/agents/code-reviewer.md +16 -1
  62. package/presets/claude/next/agents/codebase-analyzer.md +1 -1
  63. package/presets/claude/next/agents/feature-developer.md +18 -8
  64. package/presets/claude/next/agents/openspec-author.md +1 -1
  65. package/presets/claude/next/agents/playwright-test-generator.md +22 -68
  66. package/presets/claude/next/agents/playwright-test-healer.md +27 -54
  67. package/presets/claude/next/agents/playwright-test-planner.md +18 -51
  68. package/presets/claude/next/agents/task-analyst.md +25 -9
  69. package/presets/claude/next/agents/task-router.md +1 -1
  70. package/presets/claude/next/agents/tech-writer.md +1 -1
  71. package/presets/claude/next/mcp.json +3 -3
  72. package/presets/claude/next/rules/anti-hallucination/react-next-anti-hallucination.md +1 -1
  73. package/presets/claude/next/rules/architecture/layer-barrel-exports.md +1 -1
  74. package/presets/claude/next/rules/architecture/reference-features.md +1 -1
  75. package/presets/claude/next/rules/stack/navigation-router-ui.md +1 -1
  76. package/presets/claude/next/rules/stack/navigation-router.md +14 -0
  77. package/presets/claude/next/rules/stack/next-app-core.md +19 -17
  78. package/presets/claude/next/rules/stack/next-app-router.md +5 -17
  79. package/presets/claude/next/rules/stack/next-static-export.md +1 -1
  80. package/presets/claude/next/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  81. package/presets/claude/next/rules/tooling-and-review/code-review-mr.md +20 -1
  82. package/presets/claude/next/rules/tooling-and-review/interactive-questions.md +8 -8
  83. package/presets/claude/next/rules/tooling-and-review/language-policy.md +1 -1
  84. package/presets/claude/next/rules/tooling-and-review/post-change-lint.md +1 -1
  85. package/presets/claude/next/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  86. package/presets/claude/next/rules/tooling-and-review/preset-token-budget.md +1 -1
  87. package/presets/claude/next/rules/tooling-and-review/security-next.md +28 -3
  88. package/presets/claude/next/rules/ui-and-accessibility/css-property-order.md +1 -1
  89. package/presets/claude/next/rules/ui-and-accessibility/design-tokens-binding.md +4 -4
  90. package/presets/claude/next/rules/ui-and-accessibility/forms-validation.md +2 -2
  91. package/presets/claude/next/skills/code-review/SKILL.md +12 -2
  92. package/presets/claude/next/team/README.md +11 -0
  93. package/presets/claude/next/team/fixtures/feature-with-figma-url.json +10 -0
  94. package/presets/claude/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  95. package/presets/claude/next/team/fixtures/mockup-review-standalone.json +9 -0
  96. package/presets/claude/next/team/fixtures/ux-design-standalone.json +9 -0
  97. package/presets/claude/nuxt/agents/code-reviewer.md +15 -0
  98. package/presets/claude/nuxt/rules/architecture/layer-barrel-exports.md +1 -1
  99. package/presets/claude/nuxt/rules/stack/navigation-router-ui.md +1 -1
  100. package/presets/claude/nuxt/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  101. package/presets/claude/nuxt/rules/tooling-and-review/code-review-mr.md +20 -1
  102. package/presets/claude/nuxt/rules/tooling-and-review/interactive-questions.md +8 -8
  103. package/presets/claude/nuxt/rules/tooling-and-review/language-policy.md +1 -1
  104. package/presets/claude/nuxt/rules/tooling-and-review/post-change-lint.md +1 -1
  105. package/presets/claude/nuxt/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  106. package/presets/claude/nuxt/skills/code-review/SKILL.md +11 -1
  107. package/presets/claude/php-hexagonal/agents/code-reviewer.md +37 -2
  108. package/presets/claude/php-hexagonal/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  109. package/presets/claude/php-hexagonal/rules/tooling-and-review/code-review.md +20 -1
  110. package/presets/claude/php-hexagonal/rules/tooling-and-review/interactive-questions.md +8 -8
  111. package/presets/claude/php-hexagonal/rules/tooling-and-review/language-policy.md +1 -1
  112. package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  113. package/presets/claude/php-hexagonal/skills/code-review/SKILL.md +10 -1
  114. package/presets/claude/php-laravel/agents/code-reviewer.md +37 -2
  115. package/presets/claude/php-laravel/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  116. package/presets/claude/php-laravel/rules/tooling-and-review/code-review.md +20 -1
  117. package/presets/claude/php-laravel/rules/tooling-and-review/interactive-questions.md +8 -8
  118. package/presets/claude/php-laravel/rules/tooling-and-review/language-policy.md +1 -1
  119. package/presets/claude/php-laravel/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  120. package/presets/claude/php-laravel/skills/code-review/SKILL.md +10 -1
  121. package/presets/claude/svelte/agents/code-reviewer.md +15 -0
  122. package/presets/claude/svelte/rules/architecture/layer-barrel-exports.md +1 -1
  123. package/presets/claude/svelte/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  124. package/presets/claude/svelte/rules/tooling-and-review/code-review-mr.md +20 -1
  125. package/presets/claude/svelte/rules/tooling-and-review/interactive-questions.md +8 -8
  126. package/presets/claude/svelte/rules/tooling-and-review/language-policy.md +1 -1
  127. package/presets/claude/svelte/rules/tooling-and-review/post-change-lint.md +1 -1
  128. package/presets/claude/svelte/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  129. package/presets/claude/svelte/skills/code-review/SKILL.md +11 -1
  130. package/presets/cursor/android-kotlin/agents/code-reviewer.md +15 -0
  131. package/presets/cursor/android-kotlin/rules/README.md +1 -0
  132. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +3 -3
  133. package/presets/cursor/android-kotlin/rules/anti-hallucination-contract.mdc +2 -0
  134. package/presets/cursor/android-kotlin/rules/code-review-mr.mdc +20 -1
  135. package/presets/cursor/android-kotlin/rules/interactive-questions.mdc +8 -8
  136. package/presets/cursor/android-kotlin/rules/preset-pr-checklist.mdc +1 -1
  137. package/presets/cursor/android-kotlin/skills/code-review/SKILL.md +11 -1
  138. package/presets/cursor/go/agents/code-reviewer.md +37 -2
  139. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +2 -2
  140. package/presets/cursor/go/rules/anti-hallucination-contract.mdc +2 -0
  141. package/presets/cursor/go/rules/code-review-mr.mdc +20 -1
  142. package/presets/cursor/go/rules/interactive-questions.mdc +8 -8
  143. package/presets/cursor/go/rules/preset-pr-checklist.mdc +1 -1
  144. package/presets/cursor/go/skills/code-review/SKILL.md +10 -1
  145. package/presets/cursor/ios-swift/agents/code-reviewer.md +15 -0
  146. package/presets/cursor/ios-swift/rules/README.md +1 -0
  147. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +3 -3
  148. package/presets/cursor/ios-swift/rules/anti-hallucination-contract.mdc +2 -0
  149. package/presets/cursor/ios-swift/rules/code-review-mr.mdc +20 -1
  150. package/presets/cursor/ios-swift/rules/interactive-questions.mdc +8 -8
  151. package/presets/cursor/ios-swift/rules/preset-pr-checklist.mdc +1 -1
  152. package/presets/cursor/ios-swift/skills/code-review/SKILL.md +11 -1
  153. package/presets/cursor/java/agents/code-reviewer.md +37 -2
  154. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +2 -2
  155. package/presets/cursor/java/rules/anti-hallucination-contract.mdc +2 -0
  156. package/presets/cursor/java/rules/code-review-mr.mdc +20 -1
  157. package/presets/cursor/java/rules/interactive-questions.mdc +8 -8
  158. package/presets/cursor/java/rules/preset-pr-checklist.mdc +1 -1
  159. package/presets/cursor/java/skills/code-review/SKILL.md +10 -1
  160. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +2 -2
  161. package/presets/cursor/mcp-ts/rules/anti-hallucination-contract.mdc +2 -0
  162. package/presets/cursor/mcp-ts/rules/code-review-mr.mdc +20 -1
  163. package/presets/cursor/mcp-ts/rules/interactive-questions.mdc +8 -8
  164. package/presets/cursor/mcp-ts/rules/preset-pr-checklist.mdc +1 -1
  165. package/presets/cursor/mcp-ts/skills/code-review/SKILL.md +8 -0
  166. package/presets/cursor/next/MCP.md +7 -0
  167. package/presets/cursor/next/REPO_AGENTS.md +1 -1
  168. package/presets/cursor/next/agents/code-reviewer.md +15 -0
  169. package/presets/cursor/next/agents/playwright-test-healer.md +1 -0
  170. package/presets/cursor/next/ai-local/rules-library/router-pages.md +5 -5
  171. package/presets/cursor/next/mcp.json +3 -3
  172. package/presets/cursor/next/rules/README.md +1 -1
  173. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +1 -1
  174. package/presets/cursor/next/rules/anti-hallucination-contract.mdc +2 -0
  175. package/presets/cursor/next/rules/code-review-mr.mdc +20 -1
  176. package/presets/cursor/next/rules/css-property-order-stylelint.mdc +1 -1
  177. package/presets/cursor/next/rules/design-tokens-binding.mdc +4 -4
  178. package/presets/cursor/next/rules/forms-validation.mdc +2 -2
  179. package/presets/cursor/next/rules/interactive-questions.mdc +8 -8
  180. package/presets/cursor/next/rules/navigation-router-stack.mdc +14 -1
  181. package/presets/cursor/next/rules/next-app-core.mdc +19 -17
  182. package/presets/cursor/next/rules/next-app-router.mdc +5 -17
  183. package/presets/cursor/next/rules/next-static-export.mdc +1 -1
  184. package/presets/cursor/next/rules/preset-pr-checklist.mdc +1 -1
  185. package/presets/cursor/next/rules/preset-token-budget.mdc +1 -1
  186. package/presets/cursor/next/rules/react-next-anti-hallucination.mdc +1 -1
  187. package/presets/cursor/next/rules/reference-features.mdc +1 -1
  188. package/presets/cursor/next/rules/security-next.mdc +28 -3
  189. package/presets/cursor/next/skills/code-review/SKILL.md +12 -2
  190. package/presets/cursor/next/team/README.md +11 -0
  191. package/presets/cursor/next/team/fixtures/feature-with-figma-url.json +10 -0
  192. package/presets/cursor/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  193. package/presets/cursor/next/team/fixtures/mockup-review-standalone.json +9 -0
  194. package/presets/cursor/next/team/fixtures/ux-design-standalone.json +9 -0
  195. package/presets/cursor/nuxt/agents/code-reviewer.md +15 -0
  196. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  197. package/presets/cursor/nuxt/rules/anti-hallucination-contract.mdc +2 -0
  198. package/presets/cursor/nuxt/rules/code-review-mr.mdc +20 -1
  199. package/presets/cursor/nuxt/rules/interactive-questions.mdc +8 -8
  200. package/presets/cursor/nuxt/rules/preset-pr-checklist.mdc +1 -1
  201. package/presets/cursor/nuxt/skills/code-review/SKILL.md +11 -1
  202. package/presets/cursor/php-hexagonal/agents/code-reviewer.md +37 -2
  203. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +2 -2
  204. package/presets/cursor/php-hexagonal/rules/anti-hallucination-contract.mdc +2 -0
  205. package/presets/cursor/php-hexagonal/rules/code-review-mr.mdc +20 -1
  206. package/presets/cursor/php-hexagonal/rules/interactive-questions.mdc +8 -8
  207. package/presets/cursor/php-hexagonal/rules/preset-pr-checklist.mdc +1 -1
  208. package/presets/cursor/php-hexagonal/skills/code-review/SKILL.md +10 -1
  209. package/presets/cursor/php-laravel/agents/code-reviewer.md +37 -2
  210. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +2 -2
  211. package/presets/cursor/php-laravel/rules/anti-hallucination-contract.mdc +2 -0
  212. package/presets/cursor/php-laravel/rules/code-review-mr.mdc +20 -1
  213. package/presets/cursor/php-laravel/rules/interactive-questions.mdc +8 -8
  214. package/presets/cursor/php-laravel/rules/preset-pr-checklist.mdc +1 -1
  215. package/presets/cursor/php-laravel/skills/code-review/SKILL.md +10 -1
  216. package/presets/cursor/svelte/agents/code-reviewer.md +15 -0
  217. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  218. package/presets/cursor/svelte/rules/anti-hallucination-contract.mdc +2 -0
  219. package/presets/cursor/svelte/rules/code-review-mr.mdc +20 -1
  220. package/presets/cursor/svelte/rules/interactive-questions.mdc +8 -8
  221. package/presets/cursor/svelte/rules/preset-pr-checklist.mdc +1 -1
  222. package/presets/cursor/svelte/skills/code-review/SKILL.md +11 -1
  223. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  224. package/presets/mavis/android-kotlin/agents/code-reviewer.md +15 -0
  225. package/presets/mavis/android-kotlin/rules/anti-hallucination-contract.md +2 -0
  226. package/presets/mavis/android-kotlin/rules/code-review-mr.md +20 -1
  227. package/presets/mavis/android-kotlin/rules/interactive-questions.md +8 -8
  228. package/presets/mavis/android-kotlin/rules/preset-pr-checklist.md +1 -1
  229. package/presets/mavis/android-kotlin/skills/code-review/SKILL.md +11 -1
  230. package/presets/mavis/go/adapter-map.json +1 -1
  231. package/presets/mavis/go/agents/code-reviewer.md +37 -2
  232. package/presets/mavis/go/rules/anti-hallucination-contract.md +2 -0
  233. package/presets/mavis/go/rules/code-review-mr.md +20 -1
  234. package/presets/mavis/go/rules/interactive-questions.md +8 -8
  235. package/presets/mavis/go/rules/preset-pr-checklist.md +1 -1
  236. package/presets/mavis/go/skills/code-review/SKILL.md +10 -1
  237. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  238. package/presets/mavis/ios-swift/agents/code-reviewer.md +15 -0
  239. package/presets/mavis/ios-swift/rules/anti-hallucination-contract.md +2 -0
  240. package/presets/mavis/ios-swift/rules/code-review-mr.md +20 -1
  241. package/presets/mavis/ios-swift/rules/interactive-questions.md +8 -8
  242. package/presets/mavis/ios-swift/rules/preset-pr-checklist.md +1 -1
  243. package/presets/mavis/ios-swift/skills/code-review/SKILL.md +11 -1
  244. package/presets/mavis/java/adapter-map.json +1 -1
  245. package/presets/mavis/java/agents/code-reviewer.md +37 -2
  246. package/presets/mavis/java/rules/anti-hallucination-contract.md +2 -0
  247. package/presets/mavis/java/rules/code-review-mr.md +20 -1
  248. package/presets/mavis/java/rules/interactive-questions.md +8 -8
  249. package/presets/mavis/java/rules/preset-pr-checklist.md +1 -1
  250. package/presets/mavis/java/skills/code-review/SKILL.md +10 -1
  251. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  252. package/presets/mavis/mcp-ts/rules/anti-hallucination-contract.md +2 -0
  253. package/presets/mavis/mcp-ts/rules/code-review-mr.md +20 -1
  254. package/presets/mavis/mcp-ts/rules/interactive-questions.md +8 -8
  255. package/presets/mavis/mcp-ts/rules/preset-pr-checklist.md +1 -1
  256. package/presets/mavis/mcp-ts/skills/code-review/SKILL.md +8 -0
  257. package/presets/mavis/next/MCP.md +7 -0
  258. package/presets/mavis/next/REPO_AGENTS.md +1 -1
  259. package/presets/mavis/next/adapter-map.json +1 -1
  260. package/presets/mavis/next/agents/code-reviewer.md +15 -0
  261. package/presets/mavis/next/agents/playwright-test-healer.md +1 -0
  262. package/presets/mavis/next/ai-local/rules-library/router-pages.md +5 -5
  263. package/presets/mavis/next/mcp.json +3 -3
  264. package/presets/mavis/next/rules/anti-hallucination-contract.md +2 -0
  265. package/presets/mavis/next/rules/code-review-mr.md +20 -1
  266. package/presets/mavis/next/rules/css-property-order-stylelint.md +1 -1
  267. package/presets/mavis/next/rules/design-tokens-binding.md +4 -4
  268. package/presets/mavis/next/rules/forms-validation.md +2 -2
  269. package/presets/mavis/next/rules/interactive-questions.md +8 -8
  270. package/presets/mavis/next/rules/navigation-router-stack.md +12 -0
  271. package/presets/mavis/next/rules/next-app-core.md +18 -17
  272. package/presets/mavis/next/rules/next-app-router.md +4 -17
  273. package/presets/mavis/next/rules/next-static-export.md +1 -1
  274. package/presets/mavis/next/rules/preset-pr-checklist.md +1 -1
  275. package/presets/mavis/next/rules/react-next-anti-hallucination.md +1 -1
  276. package/presets/mavis/next/rules/reference-features.md +1 -1
  277. package/presets/mavis/next/rules/security-next.md +24 -3
  278. package/presets/mavis/next/skills/code-review/SKILL.md +12 -2
  279. package/presets/mavis/next/team/README.md +11 -0
  280. package/presets/mavis/next/team/fixtures/feature-with-figma-url.json +10 -0
  281. package/presets/mavis/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  282. package/presets/mavis/next/team/fixtures/mockup-review-standalone.json +9 -0
  283. package/presets/mavis/next/team/fixtures/ux-design-standalone.json +9 -0
  284. package/presets/mavis/nuxt/adapter-map.json +1 -1
  285. package/presets/mavis/nuxt/agents/code-reviewer.md +15 -0
  286. package/presets/mavis/nuxt/rules/anti-hallucination-contract.md +2 -0
  287. package/presets/mavis/nuxt/rules/code-review-mr.md +20 -1
  288. package/presets/mavis/nuxt/rules/interactive-questions.md +8 -8
  289. package/presets/mavis/nuxt/rules/preset-pr-checklist.md +1 -1
  290. package/presets/mavis/nuxt/skills/code-review/SKILL.md +11 -1
  291. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  292. package/presets/mavis/php-hexagonal/agents/code-reviewer.md +37 -2
  293. package/presets/mavis/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
  294. package/presets/mavis/php-hexagonal/rules/code-review-mr.md +20 -1
  295. package/presets/mavis/php-hexagonal/rules/interactive-questions.md +8 -8
  296. package/presets/mavis/php-hexagonal/rules/preset-pr-checklist.md +1 -1
  297. package/presets/mavis/php-hexagonal/skills/code-review/SKILL.md +10 -1
  298. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  299. package/presets/mavis/php-laravel/agents/code-reviewer.md +37 -2
  300. package/presets/mavis/php-laravel/rules/anti-hallucination-contract.md +2 -0
  301. package/presets/mavis/php-laravel/rules/code-review-mr.md +20 -1
  302. package/presets/mavis/php-laravel/rules/interactive-questions.md +8 -8
  303. package/presets/mavis/php-laravel/rules/preset-pr-checklist.md +1 -1
  304. package/presets/mavis/php-laravel/skills/code-review/SKILL.md +10 -1
  305. package/presets/mavis/svelte/adapter-map.json +1 -1
  306. package/presets/mavis/svelte/agents/code-reviewer.md +15 -0
  307. package/presets/mavis/svelte/rules/anti-hallucination-contract.md +2 -0
  308. package/presets/mavis/svelte/rules/code-review-mr.md +20 -1
  309. package/presets/mavis/svelte/rules/interactive-questions.md +8 -8
  310. package/presets/mavis/svelte/rules/preset-pr-checklist.md +1 -1
  311. package/presets/mavis/svelte/skills/code-review/SKILL.md +11 -1
  312. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  313. package/presets/opencode/android-kotlin/agents/code-reviewer.md +15 -0
  314. package/presets/opencode/android-kotlin/rules/anti-hallucination-contract.md +2 -0
  315. package/presets/opencode/android-kotlin/rules/code-review-mr.md +20 -1
  316. package/presets/opencode/android-kotlin/rules/interactive-questions.md +8 -8
  317. package/presets/opencode/android-kotlin/rules/preset-pr-checklist.md +1 -1
  318. package/presets/opencode/android-kotlin/skills/code-review/SKILL.md +11 -1
  319. package/presets/opencode/go/adapter-map.json +1 -1
  320. package/presets/opencode/go/agents/code-reviewer.md +37 -2
  321. package/presets/opencode/go/rules/anti-hallucination-contract.md +2 -0
  322. package/presets/opencode/go/rules/code-review-mr.md +20 -1
  323. package/presets/opencode/go/rules/interactive-questions.md +8 -8
  324. package/presets/opencode/go/rules/preset-pr-checklist.md +1 -1
  325. package/presets/opencode/go/skills/code-review/SKILL.md +10 -1
  326. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  327. package/presets/opencode/ios-swift/agents/code-reviewer.md +15 -0
  328. package/presets/opencode/ios-swift/rules/anti-hallucination-contract.md +2 -0
  329. package/presets/opencode/ios-swift/rules/code-review-mr.md +20 -1
  330. package/presets/opencode/ios-swift/rules/interactive-questions.md +8 -8
  331. package/presets/opencode/ios-swift/rules/preset-pr-checklist.md +1 -1
  332. package/presets/opencode/ios-swift/skills/code-review/SKILL.md +11 -1
  333. package/presets/opencode/java/adapter-map.json +1 -1
  334. package/presets/opencode/java/agents/code-reviewer.md +37 -2
  335. package/presets/opencode/java/rules/anti-hallucination-contract.md +2 -0
  336. package/presets/opencode/java/rules/code-review-mr.md +20 -1
  337. package/presets/opencode/java/rules/interactive-questions.md +8 -8
  338. package/presets/opencode/java/rules/preset-pr-checklist.md +1 -1
  339. package/presets/opencode/java/skills/code-review/SKILL.md +10 -1
  340. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  341. package/presets/opencode/mcp-ts/rules/anti-hallucination-contract.md +2 -0
  342. package/presets/opencode/mcp-ts/rules/code-review-mr.md +20 -1
  343. package/presets/opencode/mcp-ts/rules/interactive-questions.md +8 -8
  344. package/presets/opencode/mcp-ts/rules/preset-pr-checklist.md +1 -1
  345. package/presets/opencode/mcp-ts/skills/code-review/SKILL.md +8 -0
  346. package/presets/opencode/next/MCP.md +7 -0
  347. package/presets/opencode/next/REPO_AGENTS.md +1 -1
  348. package/presets/opencode/next/adapter-map.json +1 -1
  349. package/presets/opencode/next/agents/code-reviewer.md +15 -0
  350. package/presets/opencode/next/agents/playwright-test-healer.md +1 -0
  351. package/presets/opencode/next/ai-local/rules-library/router-pages.md +5 -5
  352. package/presets/opencode/next/opencode.json +3 -3
  353. package/presets/opencode/next/rules/anti-hallucination-contract.md +2 -0
  354. package/presets/opencode/next/rules/code-review-mr.md +20 -1
  355. package/presets/opencode/next/rules/css-property-order-stylelint.md +1 -1
  356. package/presets/opencode/next/rules/design-tokens-binding.md +4 -4
  357. package/presets/opencode/next/rules/forms-validation.md +2 -2
  358. package/presets/opencode/next/rules/interactive-questions.md +8 -8
  359. package/presets/opencode/next/rules/navigation-router-stack.md +12 -0
  360. package/presets/opencode/next/rules/next-app-core.md +18 -17
  361. package/presets/opencode/next/rules/next-app-router.md +4 -17
  362. package/presets/opencode/next/rules/next-static-export.md +1 -1
  363. package/presets/opencode/next/rules/preset-pr-checklist.md +1 -1
  364. package/presets/opencode/next/rules/react-next-anti-hallucination.md +1 -1
  365. package/presets/opencode/next/rules/reference-features.md +1 -1
  366. package/presets/opencode/next/rules/security-next.md +24 -3
  367. package/presets/opencode/next/skills/code-review/SKILL.md +12 -2
  368. package/presets/opencode/next/team/README.md +11 -0
  369. package/presets/opencode/next/team/fixtures/feature-with-figma-url.json +10 -0
  370. package/presets/opencode/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  371. package/presets/opencode/next/team/fixtures/mockup-review-standalone.json +9 -0
  372. package/presets/opencode/next/team/fixtures/ux-design-standalone.json +9 -0
  373. package/presets/opencode/nuxt/adapter-map.json +1 -1
  374. package/presets/opencode/nuxt/agents/code-reviewer.md +15 -0
  375. package/presets/opencode/nuxt/rules/anti-hallucination-contract.md +2 -0
  376. package/presets/opencode/nuxt/rules/code-review-mr.md +20 -1
  377. package/presets/opencode/nuxt/rules/interactive-questions.md +8 -8
  378. package/presets/opencode/nuxt/rules/preset-pr-checklist.md +1 -1
  379. package/presets/opencode/nuxt/skills/code-review/SKILL.md +11 -1
  380. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  381. package/presets/opencode/php-hexagonal/agents/code-reviewer.md +37 -2
  382. package/presets/opencode/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
  383. package/presets/opencode/php-hexagonal/rules/code-review-mr.md +20 -1
  384. package/presets/opencode/php-hexagonal/rules/interactive-questions.md +8 -8
  385. package/presets/opencode/php-hexagonal/rules/preset-pr-checklist.md +1 -1
  386. package/presets/opencode/php-hexagonal/skills/code-review/SKILL.md +10 -1
  387. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  388. package/presets/opencode/php-laravel/agents/code-reviewer.md +37 -2
  389. package/presets/opencode/php-laravel/rules/anti-hallucination-contract.md +2 -0
  390. package/presets/opencode/php-laravel/rules/code-review-mr.md +20 -1
  391. package/presets/opencode/php-laravel/rules/interactive-questions.md +8 -8
  392. package/presets/opencode/php-laravel/rules/preset-pr-checklist.md +1 -1
  393. package/presets/opencode/php-laravel/skills/code-review/SKILL.md +10 -1
  394. package/presets/opencode/svelte/adapter-map.json +1 -1
  395. package/presets/opencode/svelte/agents/code-reviewer.md +15 -0
  396. package/presets/opencode/svelte/rules/anti-hallucination-contract.md +2 -0
  397. package/presets/opencode/svelte/rules/code-review-mr.md +20 -1
  398. package/presets/opencode/svelte/rules/interactive-questions.md +8 -8
  399. package/presets/opencode/svelte/rules/preset-pr-checklist.md +1 -1
  400. package/presets/opencode/svelte/skills/code-review/SKILL.md +11 -1
@@ -16,7 +16,16 @@ import fs from 'node:fs';
16
16
  import path from 'node:path';
17
17
  import { pathToFileURL } from 'node:url';
18
18
 
19
- import { SIGNATURE_RE, ISSUE_BODY_RE, groupSignatures, validateSignal, markSignalsApplied } from './signals.mjs';
19
+ import {
20
+ SIGNATURE_RE,
21
+ ISSUE_BODY_RE,
22
+ groupSignatures,
23
+ validateSignal,
24
+ markSignalsApplied,
25
+ markSignalsRolledBack,
26
+ isRepoRelativePath,
27
+ isScriptCommandName,
28
+ } from './signals.mjs';
20
29
  import { acquireLock, releaseLock } from './lock.mjs';
21
30
 
22
31
  // --- Envelope caps (architecture.md §3) -------------------------------------
@@ -113,7 +122,37 @@ export function projectRootFor(ledgerPath) {
113
122
  return path.dirname(path.dirname(path.resolve(ledgerPath)));
114
123
  }
115
124
 
116
- /** Absolute (or already project-relative) path -> the ledger's repo-relative form. */
125
+ /**
126
+ * Git root when `startDir` sits inside a repository. Without a `.git` parent,
127
+ * the overlay parent stays the root so a fixture tree does not escape itself.
128
+ */
129
+ export function repoRootFor(startDir) {
130
+ let dir = path.resolve(startDir);
131
+ const fallback = dir;
132
+ for (;;) {
133
+ if (fs.existsSync(path.join(dir, '.git'))) return dir;
134
+ const parent = path.dirname(dir);
135
+ if (parent === dir) return fallback;
136
+ dir = parent;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Two roots, one job each.
142
+ *
143
+ * `project` is the overlay's own project root: lesson paths, script names and
144
+ * file I/O live there. `repo` is the git root: the ledger's `target` is
145
+ * repo-relative so the committed file never carries a machine path. A nested
146
+ * overlay (`<git>/packages/foo/.ai.local/`) has two different roots, so one
147
+ * variable cannot serve both.
148
+ */
149
+ export function resolveRoots(ledgerPath, options = {}) {
150
+ const project = options.projectRoot ?? options.rootDir ?? projectRootFor(ledgerPath);
151
+ const repo = options.repoRoot ?? repoRootFor(project);
152
+ return { project, repo };
153
+ }
154
+
155
+ /** Absolute (or already root-relative) path -> the ledger's repo-relative form. */
117
156
  export function toLedgerTarget(target, rootDir) {
118
157
  const absolute = path.isAbsolute(target) ? target : path.resolve(rootDir, target);
119
158
  const relative = path.relative(rootDir, absolute);
@@ -123,13 +162,31 @@ export function toLedgerTarget(target, rootDir) {
123
162
  return relative.split(path.sep).join('/');
124
163
  }
125
164
 
126
- /** Ledger form -> the absolute path file I/O needs; tolerates legacy absolute rows. */
127
- export function resolveLedgerTarget(target, rootDir) {
128
- return path.isAbsolute(target) ? target : path.resolve(rootDir, target);
165
+ /**
166
+ * Ledger form -> the absolute path file I/O needs.
167
+ *
168
+ * Tolerates legacy absolute rows. A legacy project-relative row (written
169
+ * before the ledger became repo-relative) resolves against the project root
170
+ * when that is where the file lives; a current repo-relative row resolves
171
+ * against the repo root.
172
+ */
173
+ export function resolveLedgerTarget(target, roots) {
174
+ if (path.isAbsolute(target)) return target;
175
+ const project = typeof roots === 'string' ? roots : roots.project;
176
+ const repo = typeof roots === 'string' ? roots : (roots.repo ?? project);
177
+ const fromRepo = path.resolve(repo, target);
178
+ const fromProject = path.resolve(project, target);
179
+ if (fromRepo === fromProject) return fromRepo;
180
+ if (fs.existsSync(fromProject) && !fs.existsSync(fromRepo)) return fromProject;
181
+ return fromRepo;
129
182
  }
130
183
 
131
- function appendLedgerLine(ledgerPath, entry) {
132
- const normalized = { ...entry, target: toLedgerTarget(entry.target, projectRootFor(ledgerPath)) };
184
+ function appendLedgerLine(ledgerPath, entry, roots) {
185
+ const root = typeof roots === 'string' ? roots : roots.repo;
186
+ const normalized = {
187
+ ...entry,
188
+ target: entry.target == null ? null : toLedgerTarget(entry.target, root),
189
+ };
133
190
  const existing = readExisting(ledgerPath) ?? '';
134
191
  const temporary = `${ledgerPath}.${process.pid}.${Date.now()}.tmp`;
135
192
  const fd = fs.openSync(temporary, 'w');
@@ -142,6 +199,73 @@ function appendLedgerLine(ledgerPath, entry) {
142
199
  fs.renameSync(temporary, ledgerPath);
143
200
  }
144
201
 
202
+ function intentPathFor(ledgerPath) {
203
+ return `${ledgerPath}.intent`;
204
+ }
205
+
206
+ function writeIntent(ledgerPath, payload) {
207
+ writeFileAtomic(intentPathFor(ledgerPath), `${JSON.stringify(payload)}\n`);
208
+ }
209
+
210
+ function readIntent(ledgerPath) {
211
+ let raw;
212
+ try {
213
+ raw = fs.readFileSync(intentPathFor(ledgerPath), 'utf8');
214
+ } catch (error) {
215
+ if (error && error.code === 'ENOENT') return null;
216
+ throw error;
217
+ }
218
+ try {
219
+ return JSON.parse(raw);
220
+ } catch (error) {
221
+ throw new Error(`unreadable commit intent: ${error.message}`);
222
+ }
223
+ }
224
+
225
+ function clearIntent(ledgerPath) {
226
+ try { fs.unlinkSync(intentPathFor(ledgerPath)); } catch (error) {
227
+ if (!error || error.code !== 'ENOENT') throw error;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Finish or drop a commit that died between the file rename and the ledger
233
+ * line. A landed file gets its ledger row; an untouched file drops the intent.
234
+ * A file that matches neither side stays put and is reported as a conflict.
235
+ */
236
+ export function recoverPendingCommit(ledgerPath, roots) {
237
+ const payload = readIntent(ledgerPath);
238
+ if (!payload || !payload.entry) return null;
239
+ const { entry, content } = payload;
240
+ // An intent written before the two-root split carries a single `rootDir`.
241
+ const fallback = payload.roots ?? { project: payload.rootDir, repo: payload.rootDir };
242
+ const resolved = typeof roots === 'string'
243
+ ? { project: roots, repo: roots }
244
+ : {
245
+ project: roots?.project ?? fallback.project,
246
+ repo: roots?.repo ?? fallback.repo ?? roots?.project,
247
+ };
248
+ const target = typeof entry.target === 'string' ? resolveLedgerTarget(entry.target, resolved) : null;
249
+ const current = target == null ? null : readExisting(target);
250
+ const landed = content === null ? current === null : current === content;
251
+ if (landed && entry.action) {
252
+ 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);
258
+ clearIntent(ledgerPath);
259
+ return { recovered: 'committed', entry };
260
+ }
261
+ const untouched = entry.before == null ? current == null : current === entry.before;
262
+ if (untouched) {
263
+ clearIntent(ledgerPath);
264
+ return { recovered: 'aborted', entry };
265
+ }
266
+ return { recovered: 'conflict', entry };
267
+ }
268
+
145
269
  function restoreText(target, previous) {
146
270
  if (previous === null) {
147
271
  try { fs.unlinkSync(target); } catch (error) {
@@ -152,18 +276,42 @@ function restoreText(target, previous) {
152
276
  writeFileAtomic(target, previous);
153
277
  }
154
278
 
155
- // Ledger intent lands before the file rename so a crash cannot leave a rule with no `before`.
156
- function commitWrite({ ledgerPath, target, content, entry }) {
157
- const previousLedger = readExisting(ledgerPath);
158
- appendLedgerLine(ledgerPath, entry);
279
+ // The intent file lands first, then the target, then the ledger line. A kill
280
+ // between those steps leaves no `applied` row for a write that did not happen;
281
+ // the next lock either finishes the row or drops the intent.
282
+ function commitWrite({ ledgerPath, target, content, entry, roots }) {
283
+ const resolved = typeof roots === 'string' ? { project: roots, repo: roots } : roots;
284
+ const serialized = {
285
+ ...entry,
286
+ target: entry.target == null ? null : toLedgerTarget(entry.target, resolved.repo),
287
+ };
288
+ writeIntent(ledgerPath, { entry: serialized, content, roots: resolved });
289
+ try {
290
+ if (content === null) {
291
+ try { fs.unlinkSync(target); } catch (error) {
292
+ if (!error || error.code !== 'ENOENT') throw error;
293
+ }
294
+ } else {
295
+ writeFileAtomic(target, content);
296
+ }
297
+ } catch (error) {
298
+ try { clearIntent(ledgerPath); } catch (compensateError) {
299
+ error.cause = compensateError;
300
+ }
301
+ throw error;
302
+ }
159
303
  try {
160
- writeFileAtomic(target, content);
304
+ appendLedgerLine(ledgerPath, serialized, resolved);
161
305
  } catch (error) {
162
- try { restoreText(ledgerPath, previousLedger); } catch (compensateError) {
306
+ try {
307
+ restoreText(target, entry.before ?? null);
308
+ clearIntent(ledgerPath);
309
+ } catch (compensateError) {
163
310
  error.cause = compensateError;
164
311
  }
165
312
  throw error;
166
313
  }
314
+ clearIntent(ledgerPath);
167
315
  }
168
316
 
169
317
  // --- Signature parsing + template re-derivation ------------------------------
@@ -202,17 +350,249 @@ export function imperativeSentence(kind, phrase) {
202
350
  return `${KIND_VERB[kind] ?? 'Fix'} ${phrase}.`;
203
351
  }
204
352
 
353
+ function signatureKind(signature) {
354
+ return signature.slice(0, signature.indexOf(':'));
355
+ }
356
+
357
+ export function loadAliasMap(filePath) {
358
+ let raw;
359
+ try {
360
+ raw = fs.readFileSync(filePath, 'utf8');
361
+ } catch (error) {
362
+ if (error && error.code === 'ENOENT') return { aliases: {}, error: null };
363
+ return { aliases: {}, error: error instanceof Error ? error.message : String(error) };
364
+ }
365
+ let data;
366
+ try {
367
+ data = JSON.parse(raw);
368
+ } catch {
369
+ return { aliases: {}, error: 'invalid JSON' };
370
+ }
371
+ if (
372
+ data === null
373
+ || typeof data !== 'object'
374
+ || data.version !== 1
375
+ || typeof data.aliases !== 'object'
376
+ || data.aliases === null
377
+ || Array.isArray(data.aliases)
378
+ ) {
379
+ return { aliases: {}, error: 'malformed alias map' };
380
+ }
381
+ const aliases = {};
382
+ for (const [from, to] of Object.entries(data.aliases)) {
383
+ if (typeof from !== 'string' || typeof to !== 'string' || !SIGNATURE_RE.test(from) || !SIGNATURE_RE.test(to)) {
384
+ return { aliases: {}, error: 'invalid alias entry' };
385
+ }
386
+ if (signatureKind(from) !== signatureKind(to)) {
387
+ return { aliases: {}, error: 'kind mismatch' };
388
+ }
389
+ aliases[from] = to;
390
+ }
391
+ return { aliases, error: null };
392
+ }
393
+
394
+ export function canonicalSignature(signature, aliases) {
395
+ const visited = new Set();
396
+ let current = signature;
397
+ while (Object.prototype.hasOwnProperty.call(aliases, current)) {
398
+ if (visited.has(current)) throw new Error('alias cycle');
399
+ visited.add(current);
400
+ current = aliases[current];
401
+ }
402
+ return current;
403
+ }
404
+
405
+ export function loadCatalog(filePath) {
406
+ let raw;
407
+ try {
408
+ raw = fs.readFileSync(filePath, 'utf8');
409
+ } catch (error) {
410
+ if (error && error.code === 'ENOENT') return { entries: {}, error: null };
411
+ return { entries: {}, error: error instanceof Error ? error.message : String(error) };
412
+ }
413
+ let data;
414
+ try {
415
+ data = JSON.parse(raw);
416
+ } catch {
417
+ return { entries: {}, error: 'invalid JSON' };
418
+ }
419
+ if (
420
+ data === null
421
+ || typeof data !== 'object'
422
+ || data.version !== 1
423
+ || typeof data.entries !== 'object'
424
+ || data.entries === null
425
+ || Array.isArray(data.entries)
426
+ ) {
427
+ return { entries: {}, error: 'malformed catalog' };
428
+ }
429
+ const entries = {};
430
+ for (const [signature, entry] of Object.entries(data.entries)) {
431
+ if (!SIGNATURE_RE.test(signature)) return { entries: {}, error: 'invalid catalog signature' };
432
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
433
+ return { entries: {}, error: 'invalid catalog entry' };
434
+ }
435
+ let normalizedEntry = entry;
436
+ if (normalizedEntry.paths !== undefined) {
437
+ if (!Array.isArray(normalizedEntry.paths)) return { entries: {}, error: 'invalid catalog paths' };
438
+ const paths = [];
439
+ for (const item of normalizedEntry.paths) {
440
+ if (!isRepoRelativePath(item)) {
441
+ return { entries: {}, error: `invalid catalog path "${item}"` };
442
+ }
443
+ paths.push(item);
444
+ }
445
+ normalizedEntry = { ...normalizedEntry, paths };
446
+ }
447
+ if (
448
+ normalizedEntry.command !== undefined
449
+ && normalizedEntry.command !== null
450
+ && typeof normalizedEntry.command !== 'string'
451
+ ) {
452
+ return { entries: {}, error: 'invalid catalog command' };
453
+ }
454
+ entries[signature] = normalizedEntry;
455
+ }
456
+ return { entries, error: null };
457
+ }
458
+
459
+ function readPackageScriptNames(packagePath) {
460
+ let raw;
461
+ try {
462
+ raw = fs.readFileSync(packagePath, 'utf8');
463
+ } catch (error) {
464
+ if (error && error.code === 'ENOENT') return { names: [], error: null };
465
+ return { names: [], error: error.message };
466
+ }
467
+ let data;
468
+ try {
469
+ data = JSON.parse(raw);
470
+ } catch (error) {
471
+ return { names: [], error: error.message };
472
+ }
473
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) {
474
+ return { names: [], error: 'package.json is not an object' };
475
+ }
476
+ if (data.scripts === undefined) return { names: [], error: null };
477
+ if (typeof data.scripts !== 'object' || data.scripts === null || Array.isArray(data.scripts)) {
478
+ return { names: [], error: 'scripts is not an object' };
479
+ }
480
+ return { names: Object.keys(data.scripts), error: null };
481
+ }
482
+
483
+ export function collectScriptReport(rootDir) {
484
+ const names = new Set();
485
+ const errors = [];
486
+ const take = (packagePath) => {
487
+ const result = readPackageScriptNames(packagePath);
488
+ if (result.error) {
489
+ const relative = path.relative(rootDir, packagePath);
490
+ errors.push(`${relative || packagePath}: ${result.error}`);
491
+ }
492
+ for (const name of result.names) names.add(name);
493
+ };
494
+ take(path.join(rootDir, 'package.json'));
495
+ take(path.join(rootDir, 'app', 'package.json'));
496
+ let packageNames = [];
497
+ try {
498
+ packageNames = fs.readdirSync(path.join(rootDir, 'packages'));
499
+ } catch (error) {
500
+ if (!error || error.code !== 'ENOENT') errors.push(`packages: ${error.message}`);
501
+ }
502
+ for (const name of packageNames) {
503
+ take(path.join(rootDir, 'packages', name, 'package.json'));
504
+ }
505
+ return { names, errors };
506
+ }
507
+
508
+ export function collectScriptNames(rootDir) {
509
+ return collectScriptReport(rootDir).names;
510
+ }
511
+
512
+ function repoRelativePathExists(rootDir, relPath) {
513
+ if (!isRepoRelativePath(relPath)) return false;
514
+ const rootAbs = path.resolve(rootDir);
515
+ const abs = path.resolve(rootAbs, relPath);
516
+ const relative = path.relative(rootAbs, abs);
517
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return false;
518
+ try {
519
+ return fs.existsSync(abs);
520
+ } catch {
521
+ return false;
522
+ }
523
+ }
524
+
525
+ function normalizedScriptCommand(command) {
526
+ if (command === undefined || command === null) return null;
527
+ return isScriptCommandName(command) ? command : null;
528
+ }
529
+
530
+ export function resolveLesson({ signals, rootDir, catalogEntry, scriptNames }) {
531
+ const slugsByPath = new Map();
532
+ for (const signal of signals) {
533
+ if (!Array.isArray(signal.paths)) continue;
534
+ for (const item of signal.paths) {
535
+ const slugs = slugsByPath.get(item) ?? new Set();
536
+ slugs.add(signal.slug);
537
+ slugsByPath.set(item, slugs);
538
+ }
539
+ }
540
+ const candidatePaths = new Set();
541
+ for (const [item, slugs] of slugsByPath) {
542
+ if (slugs.size >= 2) candidatePaths.add(item);
543
+ }
544
+ if (catalogEntry?.paths) {
545
+ for (const item of catalogEntry.paths) candidatePaths.add(item);
546
+ }
547
+ const paths = [...candidatePaths].filter((item) => repoRelativePathExists(rootDir, item)).sort();
548
+ if (paths.length === 0) return null;
549
+
550
+ let command = null;
551
+ if (catalogEntry?.command) {
552
+ command = normalizedScriptCommand(catalogEntry.command);
553
+ } else {
554
+ const slugsByCommand = new Map();
555
+ for (const signal of signals) {
556
+ const script = normalizedScriptCommand(signal.command);
557
+ if (script === null) continue;
558
+ const slugs = slugsByCommand.get(script) ?? new Set();
559
+ slugs.add(signal.slug);
560
+ slugsByCommand.set(script, slugs);
561
+ }
562
+ const agreed = [...slugsByCommand.entries()].filter(([, slugs]) => slugs.size >= 2);
563
+ if (agreed.length === 1) command = agreed[0][0];
564
+ }
565
+ if (command !== null && !scriptNames.has(command)) command = null;
566
+ return { paths, command };
567
+ }
568
+
569
+ export function lessonSentence({ kind, issue, paths, command }) {
570
+ if (!Array.isArray(paths) || paths.length === 0) return null;
571
+ const pathLabel = paths.join('`, `');
572
+ const phrase = humanize(issue);
573
+ if (command) {
574
+ return `When editing \`${pathLabel}\`, run \`${command}\` before the receipt (${phrase}).`;
575
+ }
576
+ const first = phrase.split(' ')[0];
577
+ if (DIRECTIVE_PREFIXES.has(first)) return `When editing \`${pathLabel}\`, ${phrase}.`;
578
+ return `When editing \`${pathLabel}\`, ${(KIND_VERB[kind] ?? 'Fix').toLowerCase()} ${phrase}.`;
579
+ }
580
+
205
581
  /**
206
582
  * Re-derive the rule text from the signature via the canonical template
207
583
  * (architecture.md §3). The only free-form input is the already-validated
208
584
  * kebab-case `issue` and `stem`; `kind` comes from the fixed vocabulary, so
209
585
  * no task/spec prose can reach the rule body.
210
586
  */
211
- export function deriveRuleText({ stem, kind, issue, overrideKill = null }) {
587
+ export function deriveRuleText({ stem, kind, issue, overrideKill = null, paths, command = null }) {
212
588
  validateStem(stem);
213
589
  if (!KINDS.includes(kind)) throw new Error(`unknown kind "${kind}"`);
214
590
  const phrase = humanize(issue);
215
- const sentence = imperativeSentence(kind, phrase);
591
+ const lessonPaths = (paths ?? []).filter((item) => isRepoRelativePath(item));
592
+ const lessonCommand = normalizedScriptCommand(command);
593
+ const sentence = lessonPaths.length > 0
594
+ ? lessonSentence({ kind, issue, paths: lessonPaths, command: lessonCommand })
595
+ : imperativeSentence(kind, phrase);
216
596
  const lines = [`# ${stem}`, ''];
217
597
  if (overrideKill !== null) {
218
598
  if (typeof overrideKill !== 'string' || !STEM_RE.test(overrideKill)) {
@@ -226,8 +606,16 @@ export function deriveRuleText({ stem, kind, issue, overrideKill = null }) {
226
606
  return `${lines.join('\n')}\n`;
227
607
  }
228
608
 
229
- function deriveSeedText({ stem, kind, issue }) {
230
- return `glob: always\n\n## Body\n\n${deriveRuleText({ stem, kind, issue })}`;
609
+ function deriveSeedText({ stem, kind, issue, paths, command }) {
610
+ return `glob: always\n\n## Body\n\n${deriveRuleText({ stem, kind, issue, paths, command })}`;
611
+ }
612
+
613
+ /** Read-only `--status` lesson line: `lesson: pending` or `lesson: app/src [lint:js]`. */
614
+ export function formatLessonStatus(lesson) {
615
+ if (lesson === null) return 'lesson: pending';
616
+ const pathLabel = lesson.paths.join(', ');
617
+ if (lesson.command) return `lesson: ${pathLabel} [${lesson.command}]`;
618
+ return `lesson: ${pathLabel}`;
231
619
  }
232
620
 
233
621
  // --- Guards ------------------------------------------------------------------
@@ -326,10 +714,22 @@ export function countRulesAndLines({ rulesDir, conventionsPath }) {
326
714
  for (const name of names) {
327
715
  if (!name.endsWith('.md')) continue;
328
716
  ruleCount += 1;
329
- try { lineCount += countNonEmptyLines(fs.readFileSync(path.join(rulesDir, name), 'utf8')); } catch {}
717
+ try {
718
+ lineCount += countNonEmptyLines(fs.readFileSync(path.join(rulesDir, name), 'utf8'));
719
+ } catch (error) {
720
+ if (!error || error.code !== 'ENOENT') {
721
+ throw new Error(`unreadable rule ${name}: ${error.message}`);
722
+ }
723
+ }
330
724
  }
331
725
  if (conventionsPath) {
332
- try { lineCount += countNonEmptyLines(fs.readFileSync(conventionsPath, 'utf8')); } catch {}
726
+ try {
727
+ lineCount += countNonEmptyLines(fs.readFileSync(conventionsPath, 'utf8'));
728
+ } catch (error) {
729
+ if (!error || error.code !== 'ENOENT') {
730
+ throw new Error(`unreadable conventions: ${error.message}`);
731
+ }
732
+ }
333
733
  }
334
734
  return { ruleCount, lineCount };
335
735
  }
@@ -357,13 +757,130 @@ export function addConventionsEntry(content, section, entry) {
357
757
  const next = content.indexOf('\n## ', headerEnd);
358
758
  const sectionEnd = next === -1 ? content.length : next;
359
759
  const body = content.slice(idx, sectionEnd);
360
- const placeholder = body.match(/^-\s*$/m);
760
+ // Horizontal whitespace only: `\s` would consume the newline and glue the
761
+ // next heading onto the new bullet.
762
+ const placeholder = body.match(/^-[ \t]*$/m);
361
763
  if (placeholder) {
362
- return content.slice(0, idx) + body.replace(/^-\s*$/m, `- ${entry}`) + content.slice(sectionEnd);
764
+ return content.slice(0, idx) + body.replace(/^-[ \t]*$/m, `- ${entry}`) + content.slice(sectionEnd);
363
765
  }
364
766
  return `${content.slice(0, headerEnd)}\n\n- ${entry}${content.slice(headerEnd)}`;
365
767
  }
366
768
 
769
+ export function addedLine(before, after) {
770
+ const prior = new Set(String(before ?? '').split('\n').map((row) => row.trim()).filter((row) => row !== ''));
771
+ const added = String(after ?? '').split('\n').map((row) => row.trim()).filter((row) => row !== '' && !prior.has(row));
772
+ return added.length === 1 ? added[0] : null;
773
+ }
774
+
775
+ export function recurrenceSlugs({ signals, appliedAt }) {
776
+ const appliedMs = Date.parse(appliedAt);
777
+ const bySlug = new Map();
778
+ for (const signal of signals) {
779
+ if (signal.status === 'rejected' || signal.status === 'rolled_back') continue;
780
+ const list = bySlug.get(signal.slug) ?? [];
781
+ list.push(signal);
782
+ bySlug.set(signal.slug, list);
783
+ }
784
+ const recurring = [];
785
+ for (const [slug, rows] of bySlug) {
786
+ const hasAtOrBefore = rows.some((row) => Date.parse(row.at) <= appliedMs);
787
+ if (hasAtOrBefore) continue;
788
+ const hasAfter = rows.some((row) => Date.parse(row.at) > appliedMs);
789
+ if (hasAfter) recurring.push(slug);
790
+ }
791
+ return recurring.sort();
792
+ }
793
+
794
+ function removeTrimmedLineOnce(content, trimmedLine) {
795
+ const lines = content.split('\n');
796
+ let removed = false;
797
+ const next = lines.filter((line) => {
798
+ if (!removed && line.trim() === trimmedLine) {
799
+ removed = true;
800
+ return false;
801
+ }
802
+ return true;
803
+ });
804
+ if (!removed) return null;
805
+ return next.join('\n');
806
+ }
807
+
808
+ function conventionsFileHasTrimmedLine(content, trimmedLine) {
809
+ return content.split('\n').some((line) => line.trim() === trimmedLine);
810
+ }
811
+
812
+ function readSignalsForSignature(signalsPath, signature, canonical) {
813
+ let raw = '';
814
+ try { raw = fs.readFileSync(signalsPath, 'utf8'); } catch (error) {
815
+ if (error && error.code === 'ENOENT') return [];
816
+ throw error;
817
+ }
818
+ const signals = [];
819
+ for (const line of raw.split('\n')) {
820
+ const trimmed = line.trim();
821
+ if (trimmed === '') continue;
822
+ let signal;
823
+ try { signal = JSON.parse(trimmed); validateSignal(signal); } catch { continue; }
824
+ let groupSignature;
825
+ try { groupSignature = canonical(signal.signature); } catch { continue; }
826
+ if (groupSignature !== signature) continue;
827
+ signals.push(signal);
828
+ }
829
+ return signals;
830
+ }
831
+
832
+ function latestConventionsAddedBySignature(entries) {
833
+ const bySignature = new Map();
834
+ for (const entry of entries) {
835
+ if (!entry || typeof entry.signature !== 'string') continue;
836
+ if (entry.action === 'conventions-added') {
837
+ bySignature.set(entry.signature, entry);
838
+ } else if (entry.action === 'unloaded') {
839
+ bySignature.delete(entry.signature);
840
+ }
841
+ }
842
+ return bySignature;
843
+ }
844
+
845
+ function tryUnloadOne({
846
+ prior,
847
+ signalsPath,
848
+ conventionsPath,
849
+ ledgerPath,
850
+ now,
851
+ canonical,
852
+ roots,
853
+ }) {
854
+ const candidates = [...latestConventionsAddedBySignature(prior).entries()]
855
+ .sort(([a], [b]) => a.localeCompare(b));
856
+ for (const [signature, appliedEntry] of candidates) {
857
+ const line = addedLine(appliedEntry.before, appliedEntry.after);
858
+ if (line === null) continue;
859
+ const target = resolveLedgerTarget(appliedEntry.target, roots);
860
+ const current = readExisting(target);
861
+ if (current === null || !conventionsFileHasTrimmedLine(current, line)) continue;
862
+ const signals = readSignalsForSignature(signalsPath, signature, canonical);
863
+ if (recurrenceSlugs({ signals, appliedAt: appliedEntry.at }).length < 2) continue;
864
+ const after = removeTrimmedLineOnce(current, line);
865
+ if (after === null) continue;
866
+ const entry = {
867
+ signature,
868
+ action: 'unloaded',
869
+ target: appliedEntry.target,
870
+ before: current,
871
+ after,
872
+ at: now(),
873
+ agent: appliedEntry.agent,
874
+ slug: appliedEntry.slug,
875
+ };
876
+ commitWrite({ ledgerPath, target, content: after, entry, roots });
877
+ prior.push(entry);
878
+ markSignalsRolledBack(signature, { signalsPath, canonical });
879
+ return { signature, target: appliedEntry.target };
880
+ }
881
+ return null;
882
+ }
883
+
367
884
  // --- Rollback inverse --------------------------------------------------------
368
885
 
369
886
  export function rollbackInverse(entry, options = {}) {
@@ -382,17 +899,14 @@ export function rollbackInverse(entry, options = {}) {
382
899
  after: entry.before,
383
900
  at: now(),
384
901
  };
902
+ const roots = resolveRoots(ledgerPath, options);
385
903
  const token = acquireLock(lockPath);
386
- const target = resolveLedgerTarget(entry.target, projectRootFor(ledgerPath));
387
904
  try {
388
- if (inverse.after == null) {
389
- try { fs.unlinkSync(target); } catch (error) {
390
- if (!error || error.code !== 'ENOENT') throw error;
391
- }
392
- } else {
393
- writeFileAtomic(target, inverse.after);
394
- }
395
- appendLedgerLine(ledgerPath, inverse);
905
+ // An intent left by a killed run is reconciled first: the rollback must
906
+ // not overwrite the intent file and lose the pending change.
907
+ recoverPendingCommit(ledgerPath, roots);
908
+ const target = resolveLedgerTarget(entry.target, roots);
909
+ commitWrite({ ledgerPath, target, content: inverse.after ?? null, entry: inverse, roots });
396
910
  return inverse;
397
911
  } finally {
398
912
  releaseLock(lockPath, token);
@@ -401,8 +915,23 @@ export function rollbackInverse(entry, options = {}) {
401
915
 
402
916
  // --- Engine ------------------------------------------------------------------
403
917
 
404
- function enrichGroups(groups, signalsPath) {
405
- const bySignature = new Map();
918
+ function enrichGroups(groups, signalsPath, canonical = (signature) => signature) {
919
+ const bySignature = new Map(
920
+ groups.map((group) => [group.signature, {
921
+ signature: group.signature,
922
+ distinctSlugCount: group.distinctSlugCount,
923
+ slugs: group.slugs,
924
+ count: group.count,
925
+ signals: [],
926
+ severity: 'low',
927
+ severityRank: 0,
928
+ stem: null,
929
+ stems: [],
930
+ target: null,
931
+ targets: [],
932
+ agent: null,
933
+ }]),
934
+ );
406
935
  let raw = '';
407
936
  try { raw = fs.readFileSync(signalsPath, 'utf8'); } catch (error) {
408
937
  if (error && error.code === 'ENOENT') raw = '';
@@ -414,13 +943,18 @@ function enrichGroups(groups, signalsPath) {
414
943
  let signal;
415
944
  try { signal = JSON.parse(trimmed); validateSignal(signal); } catch { continue; }
416
945
  if (signal.status === 'rejected' || signal.status === 'rolled_back') continue;
417
- const entry = bySignature.get(signal.signature) ?? {
418
- severity: 'low', severityRank: 0, stem: null, stems: [], target: null, targets: [], agent: null,
419
- };
946
+ let groupSignature;
947
+ try {
948
+ groupSignature = canonical(signal.signature);
949
+ } catch {
950
+ continue;
951
+ }
952
+ const entry = bySignature.get(groupSignature);
953
+ if (!entry) continue;
954
+ entry.signals.push(signal);
420
955
  const rank = SEVERITY_RANK[signal.severity] ?? 0;
421
956
  if (rank > entry.severityRank) { entry.severity = signal.severity; entry.severityRank = rank; }
422
957
  if (signal.stem) {
423
- entry.stem = signal.stem;
424
958
  entry.stems.push(signal.stem);
425
959
  }
426
960
  if (signal.target) {
@@ -428,34 +962,32 @@ function enrichGroups(groups, signalsPath) {
428
962
  entry.targets.push(signal.target);
429
963
  }
430
964
  if (!entry.agent) entry.agent = signal.agent;
431
- bySignature.set(signal.signature, entry);
432
965
  }
433
- return groups.map((group) => {
434
- const entry = bySignature.get(group.signature);
435
- return {
436
- signature: group.signature,
437
- distinctSlugCount: group.distinctSlugCount,
438
- slugs: group.slugs,
439
- count: group.count,
440
- severity: entry?.severity ?? 'low',
441
- stem: entry?.stem ?? null,
442
- stems: entry?.stems ?? [],
443
- target: entry?.target ?? null,
444
- targets: entry?.targets ?? [],
445
- agent: entry?.agent ?? 'rule-improver',
446
- };
447
- });
966
+ return [...bySignature.values()];
448
967
  }
449
968
 
450
969
  function guardSurfaces(group, phrase, ruleText) {
451
970
  return [group.signature, phrase, ruleText, ...(group.targets ?? []), ...(group.stems ?? [])];
452
971
  }
453
972
 
454
- function decide(group) {
973
+ function decide(group, { rootDir, catalogEntry, scriptNames }) {
455
974
  const { kind, issue } = parseSignature(group.signature);
456
975
  const phrase = humanize(issue);
457
- const stem = validateStem(group.stem ?? issue);
458
- const ruleText = deriveRuleText({ stem, kind, issue });
976
+ const distinctStems = [...new Set(group.stems ?? [])];
977
+ const deniedByStem = distinctStems.some((text) => isDenied(text));
978
+ if (distinctStems.length > 1 && !deniedByStem) {
979
+ throw new Error(`stem collision on "${group.signature}": ${distinctStems.join(', ')}`);
980
+ }
981
+ const stem = validateStem(distinctStems.length === 1 ? distinctStems[0] : issue);
982
+ const lesson = resolveLesson({
983
+ signals: group.signals,
984
+ rootDir,
985
+ catalogEntry,
986
+ scriptNames,
987
+ });
988
+ const paths = lesson?.paths;
989
+ const command = lesson?.command ?? null;
990
+ const ruleText = deriveRuleText({ stem, kind, issue, paths, command });
459
991
  const surfaces = guardSurfaces(group, phrase, ruleText);
460
992
  const denied = surfaces.some((text) => isDenied(text));
461
993
  let compliance = null;
@@ -464,6 +996,9 @@ function decide(group) {
464
996
  if (compliance) break;
465
997
  }
466
998
  const tier = thresholdAction(group.distinctSlugCount);
999
+ const conventionsEntry = lesson
1000
+ ? lessonSentence({ kind, issue, paths: lesson.paths, command: lesson.command })
1001
+ : null;
467
1002
  return {
468
1003
  signature: group.signature,
469
1004
  kind,
@@ -473,23 +1008,35 @@ function decide(group) {
473
1008
  tier,
474
1009
  denied,
475
1010
  compliance,
1011
+ lesson,
1012
+ conventionsEntry,
476
1013
  ruleText,
477
- seedText: deriveSeedText({ stem, kind, issue }),
1014
+ seedText: deriveSeedText({ stem, kind, issue, paths, command }),
478
1015
  severity: group.severity,
479
1016
  agent: group.agent,
480
1017
  slug: group.slugs[0] ?? group.signature,
1018
+ slugs: group.slugs ?? [],
481
1019
  };
482
1020
  }
483
1021
 
484
1022
  function planConventions(ctx, decision) {
485
1023
  const target = ctx.conventionsPath;
486
1024
  const section = KIND_SECTION[decision.kind] ?? 'Patterns';
487
- const entry = imperativeSentence(decision.kind, decision.phrase);
1025
+ const entry = decision.conventionsEntry ?? imperativeSentence(decision.kind, decision.phrase);
488
1026
  const before = readExisting(target) ?? '';
489
1027
  if (conventionsEntryExists(before, entry)) {
490
1028
  return { type: 'skipped', reason: 'dedup: identical entry already present', target };
491
1029
  }
492
- const addedLines = countNonEmptyLines(addConventionsEntry(before, section, entry)) - countNonEmptyLines(before);
1030
+ let addedLines;
1031
+ try {
1032
+ addedLines = countNonEmptyLines(addConventionsEntry(before, section, entry)) - countNonEmptyLines(before);
1033
+ } catch (error) {
1034
+ return {
1035
+ type: 'skipped',
1036
+ reason: error instanceof Error ? error.message : String(error),
1037
+ target,
1038
+ };
1039
+ }
493
1040
  const envelope = evaluateEnvelope({
494
1041
  ruleCount: ctx.envelope.ruleCount,
495
1042
  lineCount: ctx.envelope.lineCount,
@@ -518,6 +1065,7 @@ function ledgerEntry(decision, action, target, before, after, now) {
518
1065
  at: now(),
519
1066
  agent: decision.agent,
520
1067
  slug: decision.slug,
1068
+ slugs: Array.isArray(decision.slugs) ? [...decision.slugs] : [],
521
1069
  };
522
1070
  }
523
1071
 
@@ -552,7 +1100,7 @@ function proposedConventions(ctx, decision) {
552
1100
  const before = readExisting(ctx.conventionsPath);
553
1101
  if (before === null) return { before, after: null };
554
1102
  const section = KIND_SECTION[decision.kind] ?? 'Patterns';
555
- const bullet = imperativeSentence(decision.kind, decision.phrase);
1103
+ const bullet = decision.conventionsEntry ?? imperativeSentence(decision.kind, decision.phrase);
556
1104
  try {
557
1105
  return { before, after: addConventionsEntry(before, section, bullet) };
558
1106
  } catch {
@@ -560,15 +1108,15 @@ function proposedConventions(ctx, decision) {
560
1108
  }
561
1109
  }
562
1110
 
563
- function appendStage({ prior, ledgerPath, decision, action, target, before, after, now, staged, reason }) {
1111
+ function appendStage({ prior, ledgerPath, decision, action, target, before, after, now, staged, reason, roots }) {
564
1112
  staged.push({ signature: decision.signature, target, reason });
565
1113
  if (hasOpenStage(prior, decision.signature)) return;
566
1114
  const entry = ledgerEntry(decision, action, target, before, after, now);
567
- appendLedgerLine(ledgerPath, entry);
1115
+ appendLedgerLine(ledgerPath, entry, roots);
568
1116
  prior.push(entry);
569
1117
  }
570
1118
 
571
- function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir }) {
1119
+ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir, roots }) {
572
1120
  const rulePath = path.join(rulesDir, `${decision.stem}.md`);
573
1121
  const editsExisting = fs.existsSync(rulePath);
574
1122
  const band = classifyBand({
@@ -591,6 +1139,7 @@ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir
591
1139
  now,
592
1140
  staged,
593
1141
  reason: band.reason,
1142
+ roots,
594
1143
  });
595
1144
  return;
596
1145
  }
@@ -608,34 +1157,155 @@ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir
608
1157
  now,
609
1158
  staged,
610
1159
  reason: 'seed already staged',
1160
+ roots,
611
1161
  });
612
1162
  return;
613
1163
  }
614
1164
  const reason = decision.compliance ?? (band.verdict === 'stage' ? band.reason : 'new rule staged for human promote');
615
1165
  const entry = ledgerEntry(decision, 'seed-staged', seed.target, null, seed.content, now);
616
- commitWrite({ ledgerPath, target: seed.target, content: seed.content, entry });
1166
+ commitWrite({ ledgerPath, target: seed.target, content: seed.content, entry, roots });
617
1167
  prior.push(entry);
618
1168
  staged.push({ signature: decision.signature, target: seed.target, reason });
619
1169
  }
620
1170
 
1171
+ function entrySlugs(entry) {
1172
+ const slugs = [];
1173
+ if (Array.isArray(entry?.slugs)) {
1174
+ for (const slug of entry.slugs) {
1175
+ if (typeof slug === 'string' && slug !== '') slugs.push(slug);
1176
+ }
1177
+ }
1178
+ if (slugs.length === 0 && typeof entry?.slug === 'string' && entry.slug !== '') slugs.push(entry.slug);
1179
+ return slugs;
1180
+ }
1181
+
1182
+ /**
1183
+ * Slugs that already received an auto-apply.
1184
+ *
1185
+ * Every `conventions-added` row for a signature contributes its slugs: a later
1186
+ * row for the same signature must not free the slugs an earlier row spent, or
1187
+ * one task could auto-apply twice. A `rollback` row frees exactly the slugs
1188
+ * it names; an `unloaded` row frees none (ADR 0001 addendum).
1189
+ */
1190
+ function appliedSlugsFromLedger(entries) {
1191
+ const held = new Map();
1192
+ for (const entry of entries) {
1193
+ if (!entry || typeof entry.signature !== 'string') continue;
1194
+ if (entry.action === 'conventions-added') {
1195
+ const spent = held.get(entry.signature) ?? new Set();
1196
+ for (const slug of entrySlugs(entry)) spent.add(slug);
1197
+ held.set(entry.signature, spent);
1198
+ } else if (entry.action === 'rollback') {
1199
+ const spent = held.get(entry.signature);
1200
+ if (!spent) continue;
1201
+ for (const slug of entrySlugs(entry)) spent.delete(slug);
1202
+ }
1203
+ }
1204
+ const applied = new Set();
1205
+ for (const slugs of held.values()) {
1206
+ for (const slug of slugs) applied.add(slug);
1207
+ }
1208
+ return applied;
1209
+ }
1210
+
1211
+ function hasOpenPendingLesson(entries, signature) {
1212
+ let open = false;
1213
+ for (const entry of entries) {
1214
+ if (!entry || entry.signature !== signature) continue;
1215
+ if (entry.action === 'pending-lesson') open = true;
1216
+ else if (
1217
+ entry.action === 'staged'
1218
+ || entry.action === 'seed-staged'
1219
+ || entry.action === 'conventions-added'
1220
+ || entry.action === 'rollback'
1221
+ ) open = false;
1222
+ }
1223
+ return open;
1224
+ }
1225
+
621
1226
  /**
622
- * Cap count, one-apply-per-run, and every write share one lock. The envelope
623
- * and the ledger are read again here — not from the pre-lock snapshot.
1227
+ * Cap count, one auto-apply per contributing task across runs, and every write
1228
+ * share one lock. The envelope and the ledger are read again here.
624
1229
  */
625
- function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsPath, ledgerPath, lockPath, now }) {
1230
+ function applyDecisionsUnderLock({
1231
+ decisions,
1232
+ visiblePending,
1233
+ rulesDir,
1234
+ libraryDir,
1235
+ conventionsPath,
1236
+ ledgerPath,
1237
+ lockPath,
1238
+ signalsPath,
1239
+ now,
1240
+ canonical,
1241
+ rootDir,
1242
+ roots,
1243
+ }) {
626
1244
  const token = acquireLock(lockPath);
627
1245
  try {
1246
+ const recovery = recoverPendingCommit(ledgerPath, roots);
628
1247
  let envelope = countRulesAndLines({ rulesDir, conventionsPath });
629
1248
  const prior = parseLedger(readExisting(ledgerPath) ?? '');
630
1249
  const ctx = { rulesDir, libraryDir, conventionsPath, envelope };
631
1250
  const applied = [];
632
1251
  const staged = [];
633
1252
  const skipped = [];
634
- let appliedThisRun = 0;
1253
+ const unloaded = [];
1254
+ const errors = [];
1255
+ if (recovery?.recovered === 'conflict') {
1256
+ errors.push({
1257
+ signature: recovery.entry?.signature ?? 'commit',
1258
+ reason: 'commit intent matches neither the previous nor the written file',
1259
+ });
1260
+ }
1261
+ const appliedSlugs = appliedSlugsFromLedger(prior);
1262
+
1263
+ for (const item of visiblePending) {
1264
+ if (hasOpenPendingLesson(prior, item.decision.signature)) {
1265
+ skipped.push({ signature: item.decision.signature, reason: 'pending-lesson' });
1266
+ continue;
1267
+ }
1268
+ const entry = {
1269
+ signature: item.decision.signature,
1270
+ action: 'pending-lesson',
1271
+ target: null,
1272
+ before: null,
1273
+ after: null,
1274
+ at: now(),
1275
+ agent: item.decision.agent,
1276
+ slug: item.decision.slug,
1277
+ slugs: Array.isArray(item.decision.slugs) ? [...item.decision.slugs] : [],
1278
+ reason: item.reason,
1279
+ };
1280
+ appendLedgerLine(ledgerPath, entry, roots);
1281
+ prior.push(entry);
1282
+ staged.push({
1283
+ signature: item.decision.signature,
1284
+ target: null,
1285
+ reason: `pending-lesson: ${item.reason}`,
1286
+ });
1287
+ }
1288
+
1289
+ const unloadedOne = tryUnloadOne({
1290
+ prior,
1291
+ signalsPath,
1292
+ conventionsPath,
1293
+ ledgerPath,
1294
+ now,
1295
+ canonical,
1296
+ roots,
1297
+ });
1298
+ let decisionsToApply = decisions;
1299
+ if (unloadedOne) {
1300
+ unloaded.push(unloadedOne);
1301
+ envelope = countRulesAndLines({ rulesDir, conventionsPath });
1302
+ ctx.envelope = envelope;
1303
+ decisionsToApply = decisions.filter((item) => item.signature !== unloadedOne.signature);
1304
+ }
635
1305
 
636
- for (const decision of decisions) {
1306
+ for (const decision of decisionsToApply) {
637
1307
  if (decision.tier.action === 'create') {
638
- stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir });
1308
+ stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir, roots });
639
1309
  envelope = countRulesAndLines({ rulesDir, conventionsPath });
640
1310
  ctx.envelope = envelope;
641
1311
  continue;
@@ -663,6 +1333,7 @@ function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsP
663
1333
  now,
664
1334
  staged,
665
1335
  reason: decision.compliance ?? band.reason,
1336
+ roots,
666
1337
  });
667
1338
  continue;
668
1339
  }
@@ -685,10 +1356,16 @@ function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsP
685
1356
  now,
686
1357
  staged,
687
1358
  reason: plan.reason,
1359
+ roots,
688
1360
  });
689
1361
  continue;
690
1362
  }
691
- if (appliedThisRun >= 1) {
1363
+ const decisionSlugs = Array.isArray(decision.slugs) ? decision.slugs : [];
1364
+ // No contributing slug means no evidence of which task spends the cap:
1365
+ // fail closed and stage instead of guessing.
1366
+ const capped = decisionSlugs.length === 0
1367
+ || decisionSlugs.some((slug) => appliedSlugs.has(slug));
1368
+ if (capped) {
692
1369
  const proposed = proposedConventions(ctx, decision);
693
1370
  appendStage({
694
1371
  prior,
@@ -700,7 +1377,10 @@ function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsP
700
1377
  after: proposed.after,
701
1378
  now,
702
1379
  staged,
703
- reason: 'rate limit: ≤1 applied rule per task',
1380
+ reason: decisionSlugs.length === 0
1381
+ ? 'rate limit: no contributing slug to spend'
1382
+ : 'rate limit: ≤1 applied rule per task',
1383
+ roots,
704
1384
  });
705
1385
  continue;
706
1386
  }
@@ -708,15 +1388,26 @@ function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsP
708
1388
  const before = readExisting(plan.target);
709
1389
  const after = addConventionsEntry(before ?? '', plan.section, plan.entry);
710
1390
  const entry = ledgerEntry(decision, plan.action, plan.target, before, after, now);
711
- commitWrite({ ledgerPath, target: plan.target, content: after, entry });
1391
+ commitWrite({ ledgerPath, target: plan.target, content: after, entry, roots });
712
1392
  prior.push(entry);
713
- appliedThisRun += 1;
1393
+ for (const slug of decisionSlugs) appliedSlugs.add(slug);
714
1394
  applied.push({ signature: decision.signature, target: plan.target });
715
1395
  envelope = countRulesAndLines({ rulesDir, conventionsPath });
716
1396
  ctx.envelope = envelope;
717
1397
  }
718
1398
 
719
- return { applied, staged, skipped, envelope };
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
+ });
1407
+ }
1408
+ }
1409
+
1410
+ return { applied, staged, skipped, unloaded, envelope, errors };
720
1411
  } finally {
721
1412
  releaseLock(lockPath, token);
722
1413
  }
@@ -734,17 +1425,49 @@ export function runImprover(options = {}) {
734
1425
  const conventionsPath = options.conventionsPath ?? path.join(baseDir, 'conventions.md');
735
1426
  const ledgerPath = options.ledgerPath ?? path.join(baseDir, 'rule-changes.jsonl');
736
1427
  const lockPath = options.lockPath ?? path.join(baseDir, '.rules.lock');
1428
+ // Two roots: the project root owns lesson paths and file I/O; the repo root
1429
+ // owns the ledger's portable `target`. A nested overlay has both.
1430
+ const roots = resolveRoots(ledgerPath, options);
1431
+ const rootDir = roots.project;
1432
+ const aliasPath = options.aliasPath ?? path.join(baseDir, 'signature-aliases.json');
1433
+ const catalogPath = options.catalogPath ?? path.join(baseDir, 'signature-catalog.json');
737
1434
  const now = options.now ?? (() => new Date().toISOString());
738
1435
 
739
- const { groups, errors } = groupSignatures({ signalsPath });
1436
+ const errors = [];
1437
+ const aliasLoad = loadAliasMap(aliasPath);
1438
+ if (aliasLoad.error) {
1439
+ errors.push({ signature: 'signature-aliases', reason: aliasLoad.error });
1440
+ }
1441
+ const canonical = (signature) => canonicalSignature(signature, aliasLoad.aliases);
1442
+
1443
+ const grouped = groupSignatures({ signalsPath, canonical });
1444
+ errors.push(...grouped.errors);
1445
+
1446
+ const catalogLoad = loadCatalog(catalogPath);
1447
+ if (catalogLoad.error) {
1448
+ errors.push({ signature: 'signature-catalog', reason: catalogLoad.error });
1449
+ }
1450
+ const catalog = catalogLoad.entries;
1451
+ const scriptReport = collectScriptReport(rootDir);
1452
+ for (const reason of scriptReport.errors) {
1453
+ errors.push({ signature: 'package-scripts', reason });
1454
+ }
1455
+ const scriptNames = scriptReport.names;
1456
+
740
1457
  const rejected = [];
741
1458
  const decisions = [];
1459
+ const skipped = [];
1460
+ const visiblePending = [];
742
1461
 
743
- for (const group of enrichGroups(groups, signalsPath)) {
1462
+ for (const group of enrichGroups(grouped.groups, signalsPath, canonical)) {
744
1463
  if (group.distinctSlugCount < 2) continue;
745
1464
  let decision;
746
1465
  try {
747
- decision = decide(group);
1466
+ decision = decide(group, {
1467
+ rootDir,
1468
+ catalogEntry: catalog[group.signature] ?? null,
1469
+ scriptNames,
1470
+ });
748
1471
  } catch (error) {
749
1472
  // A malformed/inconsistent signal (e.g. signature↔stem mismatch) must be
750
1473
  // skipped + reported, never abort the whole loop (§5.2 robustness).
@@ -758,60 +1481,110 @@ export function runImprover(options = {}) {
758
1481
  rejected.push({ signature: decision.signature, reason: 'denylist' });
759
1482
  continue;
760
1483
  }
1484
+ if (decision.lesson === null) {
1485
+ const band = classifyBand({
1486
+ denied: false,
1487
+ compliance: Boolean(decision.compliance),
1488
+ overrideKill: false,
1489
+ decision: false,
1490
+ severity: decision.severity,
1491
+ editsExisting: false,
1492
+ });
1493
+ if (band.verdict === 'stage') visiblePending.push({ decision, reason: band.reason });
1494
+ else skipped.push({ signature: decision.signature, reason: 'pending-lesson' });
1495
+ continue;
1496
+ }
761
1497
  decisions.push(decision);
762
1498
  }
763
1499
 
764
1500
  let applied = [];
765
1501
  let staged = [];
766
- let skipped = [];
767
- let envelope;
768
- if (decisions.length === 0) {
769
- envelope = countRulesAndLines({ rulesDir, conventionsPath });
770
- } else {
771
- ({ applied, staged, skipped, envelope } = applyDecisionsUnderLock({
772
- decisions, rulesDir, libraryDir, conventionsPath, ledgerPath, lockPath, now,
1502
+ let applySkipped = [];
1503
+ let unloaded = [];
1504
+ let applyErrors = [];
1505
+ let envelope = { ruleCount: 0, lineCount: 0 };
1506
+ try {
1507
+ ({ applied, staged, skipped: applySkipped, unloaded, envelope, errors: applyErrors } = applyDecisionsUnderLock({
1508
+ decisions,
1509
+ visiblePending,
1510
+ rulesDir,
1511
+ libraryDir,
1512
+ conventionsPath,
1513
+ ledgerPath,
1514
+ lockPath,
1515
+ signalsPath,
1516
+ now,
1517
+ canonical,
1518
+ rootDir,
1519
+ roots,
773
1520
  }));
774
- // Mark the signals that actually wrote a change as `applied` so a later
775
- // rejection/rollback can flip them to a non-qualifying status (W4).
776
- for (const item of applied) {
777
- markSignalsApplied(item.signature, { signalsPath });
778
- }
1521
+ errors.push(...applyErrors);
1522
+ } catch (error) {
1523
+ const reason = error instanceof Error ? error.message : String(error);
1524
+ if (!reason.startsWith('unreadable rule') && !reason.startsWith('unreadable conventions')) throw error;
1525
+ errors.push({ signature: 'envelope', reason });
779
1526
  }
780
1527
 
1528
+ const allSkipped = [...skipped, ...applySkipped];
1529
+
781
1530
  return {
782
1531
  applied,
783
1532
  staged,
784
- skipped,
1533
+ skipped: allSkipped,
1534
+ unloaded,
785
1535
  rejected,
786
1536
  errors,
787
1537
  envelope,
788
- report: renderReport({ applied, staged, skipped, rejected, errors, envelope, ledgerPath }),
1538
+ report: renderReport({
1539
+ applied,
1540
+ staged,
1541
+ skipped: allSkipped,
1542
+ unloaded,
1543
+ rejected,
1544
+ errors,
1545
+ envelope,
1546
+ rootDir,
1547
+ roots,
1548
+ }),
789
1549
  };
790
1550
  }
791
1551
 
792
- function renderTarget(target, ledgerPath) {
1552
+ function renderTarget(target, roots) {
1553
+ if (target == null) return '(no file)';
793
1554
  if (typeof target !== 'string') return String(target);
794
1555
  try {
795
- return toLedgerTarget(target, projectRootFor(ledgerPath));
1556
+ return toLedgerTarget(target, roots.repo);
796
1557
  } catch {
797
1558
  return target;
798
1559
  }
799
1560
  }
800
1561
 
801
- function renderReport({ applied, staged, skipped, rejected, errors, envelope, ledgerPath }) {
1562
+ function appendSkipGroup(lines, items, heading) {
1563
+ if (items.length === 0) return;
1564
+ lines.push('', heading);
1565
+ for (const item of items) lines.push(` - ${item.signature} (${item.reason})`);
1566
+ }
1567
+
1568
+ function renderReport({ applied, staged, skipped, rejected, unloaded = [], errors, envelope, roots }) {
802
1569
  const lines = [
803
1570
  'Self-learning rule improver',
804
1571
  `envelope: ${envelope.ruleCount}/${MAX_ACTIVE_RULES} rules, ${envelope.lineCount}/${MAX_TOTAL_LINES} lines`,
805
1572
  '',
806
1573
  `applied (${applied.length}) — auto, low-risk, reversible`,
807
1574
  ];
808
- for (const item of applied) lines.push(` - ${item.signature} → ${renderTarget(item.target, ledgerPath)}`);
1575
+ for (const item of applied) lines.push(` - ${item.signature} → ${renderTarget(item.target, roots)}`);
809
1576
  lines.push('', `staged (${staged.length}) — human promote`);
810
- for (const item of staged) lines.push(` - ${item.signature} → ${renderTarget(item.target, ledgerPath)} (${item.reason})`);
811
- if (skipped.length > 0) {
812
- lines.push('', `skipped (${skipped.length}) — dedup no-op`);
813
- for (const item of skipped) lines.push(` - ${item.signature} (${item.reason})`);
1577
+ for (const item of staged) lines.push(` - ${item.signature} → ${renderTarget(item.target, roots)} (${item.reason})`);
1578
+ if (unloaded.length > 0) {
1579
+ lines.push('', `unloaded (${unloaded.length}) — lesson removed`);
1580
+ for (const item of unloaded) lines.push(` - ${item.signature} → ${renderTarget(item.target, roots)}`);
814
1581
  }
1582
+ const pending = skipped.filter((item) => item.reason === 'pending-lesson');
1583
+ const deduped = skipped.filter((item) => item.reason !== 'pending-lesson' && String(item.reason).startsWith('dedup'));
1584
+ const otherSkipped = skipped.filter((item) => item.reason !== 'pending-lesson' && !String(item.reason).startsWith('dedup'));
1585
+ appendSkipGroup(lines, pending, `skipped (${pending.length}) — pending lesson`);
1586
+ appendSkipGroup(lines, deduped, `skipped (${deduped.length}) — dedup no-op`);
1587
+ appendSkipGroup(lines, otherSkipped, `skipped (${otherSkipped.length}) — not applied`);
815
1588
  lines.push('', `rejected (${rejected.length}) — denylist`);
816
1589
  for (const item of rejected) lines.push(` - ${item.signature} (${item.reason})`);
817
1590
  if (errors.length > 0) {