@bonesofspring/ai-rules 0.2.51 → 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 (275) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/bin/cli.js +14 -1
  3. package/bin/lib/ai-local-drift.js +55 -14
  4. package/bin/lib/seed-ai-local-team.js +18 -7
  5. package/bin/mavis-install.js +2 -0
  6. package/bin/opencode-install.js +2 -0
  7. package/docs/LOCAL-OVERLAY.md +1 -1
  8. package/docs/PRESET-CONTRIBUTION.md +11 -9
  9. package/package.json +5 -1
  10. package/presets/_shared/ai-local/scripts/manifest.mjs +13 -3
  11. package/presets/_shared/ai-local/scripts/rule-improver.mjs +428 -91
  12. package/presets/_shared/ai-local/scripts/run.mjs +22 -4
  13. package/presets/_shared/ai-local/scripts/signals.mjs +4 -1
  14. package/presets/_shared/core/meta/preset-pr-checklist.md +1 -1
  15. package/presets/_shared/core/quality/interactive-questions.md +8 -8
  16. package/presets/claude/android-kotlin/agents/code-reviewer.md +1 -0
  17. package/presets/claude/android-kotlin/rules/tooling-and-review/interactive-questions.md +8 -8
  18. package/presets/claude/android-kotlin/rules/tooling-and-review/language-policy.md +1 -1
  19. package/presets/claude/android-kotlin/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  20. package/presets/claude/go/agents/code-reviewer.md +1 -0
  21. package/presets/claude/go/rules/tooling-and-review/interactive-questions.md +8 -8
  22. package/presets/claude/go/rules/tooling-and-review/language-policy.md +1 -1
  23. package/presets/claude/go/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  24. package/presets/claude/ios-swift/agents/code-reviewer.md +1 -0
  25. package/presets/claude/ios-swift/rules/tooling-and-review/interactive-questions.md +8 -8
  26. package/presets/claude/ios-swift/rules/tooling-and-review/language-policy.md +1 -1
  27. package/presets/claude/ios-swift/rules/tooling-and-review/post-change-build.md +1 -1
  28. package/presets/claude/ios-swift/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  29. package/presets/claude/java/agents/code-reviewer.md +1 -0
  30. package/presets/claude/java/rules/tooling-and-review/interactive-questions.md +8 -8
  31. package/presets/claude/java/rules/tooling-and-review/language-policy.md +1 -1
  32. package/presets/claude/java/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  33. package/presets/claude/mcp-ts/rules/tooling-and-review/interactive-questions.md +8 -8
  34. package/presets/claude/mcp-ts/rules/tooling-and-review/language-policy.md +1 -1
  35. package/presets/claude/mcp-ts/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  36. package/presets/claude/next/MCP.md +7 -0
  37. package/presets/claude/next/README.md +1 -1
  38. package/presets/claude/next/REPO_AGENTS.md +1 -1
  39. package/presets/claude/next/agents/README.md +3 -3
  40. package/presets/claude/next/agents/build-verifier.md +9 -3
  41. package/presets/claude/next/agents/code-reviewer.md +2 -1
  42. package/presets/claude/next/agents/codebase-analyzer.md +1 -1
  43. package/presets/claude/next/agents/feature-developer.md +18 -8
  44. package/presets/claude/next/agents/openspec-author.md +1 -1
  45. package/presets/claude/next/agents/playwright-test-generator.md +22 -68
  46. package/presets/claude/next/agents/playwright-test-healer.md +27 -54
  47. package/presets/claude/next/agents/playwright-test-planner.md +18 -51
  48. package/presets/claude/next/agents/task-analyst.md +25 -9
  49. package/presets/claude/next/agents/task-router.md +1 -1
  50. package/presets/claude/next/agents/tech-writer.md +1 -1
  51. package/presets/claude/next/mcp.json +3 -3
  52. package/presets/claude/next/rules/anti-hallucination/react-next-anti-hallucination.md +1 -1
  53. package/presets/claude/next/rules/architecture/layer-barrel-exports.md +1 -1
  54. package/presets/claude/next/rules/architecture/reference-features.md +1 -1
  55. package/presets/claude/next/rules/stack/navigation-router-ui.md +1 -1
  56. package/presets/claude/next/rules/stack/navigation-router.md +14 -0
  57. package/presets/claude/next/rules/stack/next-app-core.md +19 -17
  58. package/presets/claude/next/rules/stack/next-app-router.md +5 -17
  59. package/presets/claude/next/rules/stack/next-static-export.md +1 -1
  60. package/presets/claude/next/rules/tooling-and-review/interactive-questions.md +8 -8
  61. package/presets/claude/next/rules/tooling-and-review/language-policy.md +1 -1
  62. package/presets/claude/next/rules/tooling-and-review/post-change-lint.md +1 -1
  63. package/presets/claude/next/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  64. package/presets/claude/next/rules/tooling-and-review/preset-token-budget.md +1 -1
  65. package/presets/claude/next/rules/tooling-and-review/security-next.md +28 -3
  66. package/presets/claude/next/rules/ui-and-accessibility/css-property-order.md +1 -1
  67. package/presets/claude/next/rules/ui-and-accessibility/design-tokens-binding.md +4 -4
  68. package/presets/claude/next/rules/ui-and-accessibility/forms-validation.md +2 -2
  69. package/presets/claude/next/team/README.md +11 -0
  70. package/presets/claude/next/team/fixtures/feature-with-figma-url.json +10 -0
  71. package/presets/claude/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  72. package/presets/claude/next/team/fixtures/mockup-review-standalone.json +9 -0
  73. package/presets/claude/next/team/fixtures/ux-design-standalone.json +9 -0
  74. package/presets/claude/nuxt/agents/code-reviewer.md +1 -0
  75. package/presets/claude/nuxt/rules/architecture/layer-barrel-exports.md +1 -1
  76. package/presets/claude/nuxt/rules/stack/navigation-router-ui.md +1 -1
  77. package/presets/claude/nuxt/rules/tooling-and-review/interactive-questions.md +8 -8
  78. package/presets/claude/nuxt/rules/tooling-and-review/language-policy.md +1 -1
  79. package/presets/claude/nuxt/rules/tooling-and-review/post-change-lint.md +1 -1
  80. package/presets/claude/nuxt/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  81. package/presets/claude/php-hexagonal/agents/code-reviewer.md +1 -0
  82. package/presets/claude/php-hexagonal/rules/tooling-and-review/interactive-questions.md +8 -8
  83. package/presets/claude/php-hexagonal/rules/tooling-and-review/language-policy.md +1 -1
  84. package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  85. package/presets/claude/php-laravel/agents/code-reviewer.md +1 -0
  86. package/presets/claude/php-laravel/rules/tooling-and-review/interactive-questions.md +8 -8
  87. package/presets/claude/php-laravel/rules/tooling-and-review/language-policy.md +1 -1
  88. package/presets/claude/php-laravel/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  89. package/presets/claude/svelte/agents/code-reviewer.md +1 -0
  90. package/presets/claude/svelte/rules/architecture/layer-barrel-exports.md +1 -1
  91. package/presets/claude/svelte/rules/tooling-and-review/interactive-questions.md +8 -8
  92. package/presets/claude/svelte/rules/tooling-and-review/language-policy.md +1 -1
  93. package/presets/claude/svelte/rules/tooling-and-review/post-change-lint.md +1 -1
  94. package/presets/claude/svelte/rules/tooling-and-review/preset-pr-checklist.md +1 -1
  95. package/presets/cursor/android-kotlin/agents/code-reviewer.md +1 -0
  96. package/presets/cursor/android-kotlin/rules/README.md +1 -0
  97. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +3 -3
  98. package/presets/cursor/android-kotlin/rules/interactive-questions.mdc +8 -8
  99. package/presets/cursor/android-kotlin/rules/preset-pr-checklist.mdc +1 -1
  100. package/presets/cursor/go/agents/code-reviewer.md +1 -0
  101. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +2 -2
  102. package/presets/cursor/go/rules/interactive-questions.mdc +8 -8
  103. package/presets/cursor/go/rules/preset-pr-checklist.mdc +1 -1
  104. package/presets/cursor/ios-swift/agents/code-reviewer.md +1 -0
  105. package/presets/cursor/ios-swift/rules/README.md +1 -0
  106. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +3 -3
  107. package/presets/cursor/ios-swift/rules/interactive-questions.mdc +8 -8
  108. package/presets/cursor/ios-swift/rules/preset-pr-checklist.mdc +1 -1
  109. package/presets/cursor/java/agents/code-reviewer.md +1 -0
  110. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +2 -2
  111. package/presets/cursor/java/rules/interactive-questions.mdc +8 -8
  112. package/presets/cursor/java/rules/preset-pr-checklist.mdc +1 -1
  113. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +2 -2
  114. package/presets/cursor/mcp-ts/rules/interactive-questions.mdc +8 -8
  115. package/presets/cursor/mcp-ts/rules/preset-pr-checklist.mdc +1 -1
  116. package/presets/cursor/next/MCP.md +7 -0
  117. package/presets/cursor/next/REPO_AGENTS.md +1 -1
  118. package/presets/cursor/next/agents/code-reviewer.md +1 -0
  119. package/presets/cursor/next/agents/playwright-test-healer.md +1 -0
  120. package/presets/cursor/next/ai-local/rules-library/router-pages.md +5 -5
  121. package/presets/cursor/next/mcp.json +3 -3
  122. package/presets/cursor/next/rules/README.md +1 -1
  123. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +1 -1
  124. package/presets/cursor/next/rules/css-property-order-stylelint.mdc +1 -1
  125. package/presets/cursor/next/rules/design-tokens-binding.mdc +4 -4
  126. package/presets/cursor/next/rules/forms-validation.mdc +2 -2
  127. package/presets/cursor/next/rules/interactive-questions.mdc +8 -8
  128. package/presets/cursor/next/rules/navigation-router-stack.mdc +14 -1
  129. package/presets/cursor/next/rules/next-app-core.mdc +19 -17
  130. package/presets/cursor/next/rules/next-app-router.mdc +5 -17
  131. package/presets/cursor/next/rules/next-static-export.mdc +1 -1
  132. package/presets/cursor/next/rules/preset-pr-checklist.mdc +1 -1
  133. package/presets/cursor/next/rules/preset-token-budget.mdc +1 -1
  134. package/presets/cursor/next/rules/react-next-anti-hallucination.mdc +1 -1
  135. package/presets/cursor/next/rules/reference-features.mdc +1 -1
  136. package/presets/cursor/next/rules/security-next.mdc +28 -3
  137. package/presets/cursor/next/team/README.md +11 -0
  138. package/presets/cursor/next/team/fixtures/feature-with-figma-url.json +10 -0
  139. package/presets/cursor/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  140. package/presets/cursor/next/team/fixtures/mockup-review-standalone.json +9 -0
  141. package/presets/cursor/next/team/fixtures/ux-design-standalone.json +9 -0
  142. package/presets/cursor/nuxt/agents/code-reviewer.md +1 -0
  143. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  144. package/presets/cursor/nuxt/rules/interactive-questions.mdc +8 -8
  145. package/presets/cursor/nuxt/rules/preset-pr-checklist.mdc +1 -1
  146. package/presets/cursor/php-hexagonal/agents/code-reviewer.md +1 -0
  147. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +2 -2
  148. package/presets/cursor/php-hexagonal/rules/interactive-questions.mdc +8 -8
  149. package/presets/cursor/php-hexagonal/rules/preset-pr-checklist.mdc +1 -1
  150. package/presets/cursor/php-laravel/agents/code-reviewer.md +1 -0
  151. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +2 -2
  152. package/presets/cursor/php-laravel/rules/interactive-questions.mdc +8 -8
  153. package/presets/cursor/php-laravel/rules/preset-pr-checklist.mdc +1 -1
  154. package/presets/cursor/svelte/agents/code-reviewer.md +1 -0
  155. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  156. package/presets/cursor/svelte/rules/interactive-questions.mdc +8 -8
  157. package/presets/cursor/svelte/rules/preset-pr-checklist.mdc +1 -1
  158. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  159. package/presets/mavis/android-kotlin/agents/code-reviewer.md +1 -0
  160. package/presets/mavis/android-kotlin/rules/interactive-questions.md +8 -8
  161. package/presets/mavis/android-kotlin/rules/preset-pr-checklist.md +1 -1
  162. package/presets/mavis/go/adapter-map.json +1 -1
  163. package/presets/mavis/go/agents/code-reviewer.md +1 -0
  164. package/presets/mavis/go/rules/interactive-questions.md +8 -8
  165. package/presets/mavis/go/rules/preset-pr-checklist.md +1 -1
  166. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  167. package/presets/mavis/ios-swift/agents/code-reviewer.md +1 -0
  168. package/presets/mavis/ios-swift/rules/interactive-questions.md +8 -8
  169. package/presets/mavis/ios-swift/rules/preset-pr-checklist.md +1 -1
  170. package/presets/mavis/java/adapter-map.json +1 -1
  171. package/presets/mavis/java/agents/code-reviewer.md +1 -0
  172. package/presets/mavis/java/rules/interactive-questions.md +8 -8
  173. package/presets/mavis/java/rules/preset-pr-checklist.md +1 -1
  174. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  175. package/presets/mavis/mcp-ts/rules/interactive-questions.md +8 -8
  176. package/presets/mavis/mcp-ts/rules/preset-pr-checklist.md +1 -1
  177. package/presets/mavis/next/MCP.md +7 -0
  178. package/presets/mavis/next/REPO_AGENTS.md +1 -1
  179. package/presets/mavis/next/adapter-map.json +1 -1
  180. package/presets/mavis/next/agents/code-reviewer.md +1 -0
  181. package/presets/mavis/next/agents/playwright-test-healer.md +1 -0
  182. package/presets/mavis/next/ai-local/rules-library/router-pages.md +5 -5
  183. package/presets/mavis/next/mcp.json +3 -3
  184. package/presets/mavis/next/rules/css-property-order-stylelint.md +1 -1
  185. package/presets/mavis/next/rules/design-tokens-binding.md +4 -4
  186. package/presets/mavis/next/rules/forms-validation.md +2 -2
  187. package/presets/mavis/next/rules/interactive-questions.md +8 -8
  188. package/presets/mavis/next/rules/navigation-router-stack.md +12 -0
  189. package/presets/mavis/next/rules/next-app-core.md +18 -17
  190. package/presets/mavis/next/rules/next-app-router.md +4 -17
  191. package/presets/mavis/next/rules/next-static-export.md +1 -1
  192. package/presets/mavis/next/rules/preset-pr-checklist.md +1 -1
  193. package/presets/mavis/next/rules/react-next-anti-hallucination.md +1 -1
  194. package/presets/mavis/next/rules/reference-features.md +1 -1
  195. package/presets/mavis/next/rules/security-next.md +24 -3
  196. package/presets/mavis/next/team/README.md +11 -0
  197. package/presets/mavis/next/team/fixtures/feature-with-figma-url.json +10 -0
  198. package/presets/mavis/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  199. package/presets/mavis/next/team/fixtures/mockup-review-standalone.json +9 -0
  200. package/presets/mavis/next/team/fixtures/ux-design-standalone.json +9 -0
  201. package/presets/mavis/nuxt/adapter-map.json +1 -1
  202. package/presets/mavis/nuxt/agents/code-reviewer.md +1 -0
  203. package/presets/mavis/nuxt/rules/interactive-questions.md +8 -8
  204. package/presets/mavis/nuxt/rules/preset-pr-checklist.md +1 -1
  205. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  206. package/presets/mavis/php-hexagonal/agents/code-reviewer.md +1 -0
  207. package/presets/mavis/php-hexagonal/rules/interactive-questions.md +8 -8
  208. package/presets/mavis/php-hexagonal/rules/preset-pr-checklist.md +1 -1
  209. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  210. package/presets/mavis/php-laravel/agents/code-reviewer.md +1 -0
  211. package/presets/mavis/php-laravel/rules/interactive-questions.md +8 -8
  212. package/presets/mavis/php-laravel/rules/preset-pr-checklist.md +1 -1
  213. package/presets/mavis/svelte/adapter-map.json +1 -1
  214. package/presets/mavis/svelte/agents/code-reviewer.md +1 -0
  215. package/presets/mavis/svelte/rules/interactive-questions.md +8 -8
  216. package/presets/mavis/svelte/rules/preset-pr-checklist.md +1 -1
  217. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  218. package/presets/opencode/android-kotlin/agents/code-reviewer.md +1 -0
  219. package/presets/opencode/android-kotlin/rules/interactive-questions.md +8 -8
  220. package/presets/opencode/android-kotlin/rules/preset-pr-checklist.md +1 -1
  221. package/presets/opencode/go/adapter-map.json +1 -1
  222. package/presets/opencode/go/agents/code-reviewer.md +1 -0
  223. package/presets/opencode/go/rules/interactive-questions.md +8 -8
  224. package/presets/opencode/go/rules/preset-pr-checklist.md +1 -1
  225. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  226. package/presets/opencode/ios-swift/agents/code-reviewer.md +1 -0
  227. package/presets/opencode/ios-swift/rules/interactive-questions.md +8 -8
  228. package/presets/opencode/ios-swift/rules/preset-pr-checklist.md +1 -1
  229. package/presets/opencode/java/adapter-map.json +1 -1
  230. package/presets/opencode/java/agents/code-reviewer.md +1 -0
  231. package/presets/opencode/java/rules/interactive-questions.md +8 -8
  232. package/presets/opencode/java/rules/preset-pr-checklist.md +1 -1
  233. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  234. package/presets/opencode/mcp-ts/rules/interactive-questions.md +8 -8
  235. package/presets/opencode/mcp-ts/rules/preset-pr-checklist.md +1 -1
  236. package/presets/opencode/next/MCP.md +7 -0
  237. package/presets/opencode/next/REPO_AGENTS.md +1 -1
  238. package/presets/opencode/next/adapter-map.json +1 -1
  239. package/presets/opencode/next/agents/code-reviewer.md +1 -0
  240. package/presets/opencode/next/agents/playwright-test-healer.md +1 -0
  241. package/presets/opencode/next/ai-local/rules-library/router-pages.md +5 -5
  242. package/presets/opencode/next/opencode.json +3 -3
  243. package/presets/opencode/next/rules/css-property-order-stylelint.md +1 -1
  244. package/presets/opencode/next/rules/design-tokens-binding.md +4 -4
  245. package/presets/opencode/next/rules/forms-validation.md +2 -2
  246. package/presets/opencode/next/rules/interactive-questions.md +8 -8
  247. package/presets/opencode/next/rules/navigation-router-stack.md +12 -0
  248. package/presets/opencode/next/rules/next-app-core.md +18 -17
  249. package/presets/opencode/next/rules/next-app-router.md +4 -17
  250. package/presets/opencode/next/rules/next-static-export.md +1 -1
  251. package/presets/opencode/next/rules/preset-pr-checklist.md +1 -1
  252. package/presets/opencode/next/rules/react-next-anti-hallucination.md +1 -1
  253. package/presets/opencode/next/rules/reference-features.md +1 -1
  254. package/presets/opencode/next/rules/security-next.md +24 -3
  255. package/presets/opencode/next/team/README.md +11 -0
  256. package/presets/opencode/next/team/fixtures/feature-with-figma-url.json +10 -0
  257. package/presets/opencode/next/team/fixtures/feature-with-ux-no-figma.json +10 -0
  258. package/presets/opencode/next/team/fixtures/mockup-review-standalone.json +9 -0
  259. package/presets/opencode/next/team/fixtures/ux-design-standalone.json +9 -0
  260. package/presets/opencode/nuxt/adapter-map.json +1 -1
  261. package/presets/opencode/nuxt/agents/code-reviewer.md +1 -0
  262. package/presets/opencode/nuxt/rules/interactive-questions.md +8 -8
  263. package/presets/opencode/nuxt/rules/preset-pr-checklist.md +1 -1
  264. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  265. package/presets/opencode/php-hexagonal/agents/code-reviewer.md +1 -0
  266. package/presets/opencode/php-hexagonal/rules/interactive-questions.md +8 -8
  267. package/presets/opencode/php-hexagonal/rules/preset-pr-checklist.md +1 -1
  268. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  269. package/presets/opencode/php-laravel/agents/code-reviewer.md +1 -0
  270. package/presets/opencode/php-laravel/rules/interactive-questions.md +8 -8
  271. package/presets/opencode/php-laravel/rules/preset-pr-checklist.md +1 -1
  272. package/presets/opencode/svelte/adapter-map.json +1 -1
  273. package/presets/opencode/svelte/agents/code-reviewer.md +1 -0
  274. package/presets/opencode/svelte/rules/interactive-questions.md +8 -8
  275. package/presets/opencode/svelte/rules/preset-pr-checklist.md +1 -1
@@ -122,7 +122,37 @@ export function projectRootFor(ledgerPath) {
122
122
  return path.dirname(path.dirname(path.resolve(ledgerPath)));
123
123
  }
124
124
 
125
- /** 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. */
126
156
  export function toLedgerTarget(target, rootDir) {
127
157
  const absolute = path.isAbsolute(target) ? target : path.resolve(rootDir, target);
128
158
  const relative = path.relative(rootDir, absolute);
@@ -132,13 +162,31 @@ export function toLedgerTarget(target, rootDir) {
132
162
  return relative.split(path.sep).join('/');
133
163
  }
134
164
 
135
- /** Ledger form -> the absolute path file I/O needs; tolerates legacy absolute rows. */
136
- export function resolveLedgerTarget(target, rootDir) {
137
- return path.isAbsolute(target) ? target : path.resolve(rootDir, target);
138
- }
139
-
140
- function appendLedgerLine(ledgerPath, entry) {
141
- const normalized = { ...entry, target: toLedgerTarget(entry.target, projectRootFor(ledgerPath)) };
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;
182
+ }
183
+
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
+ };
142
190
  const existing = readExisting(ledgerPath) ?? '';
143
191
  const temporary = `${ledgerPath}.${process.pid}.${Date.now()}.tmp`;
144
192
  const fd = fs.openSync(temporary, 'w');
@@ -151,6 +199,73 @@ function appendLedgerLine(ledgerPath, entry) {
151
199
  fs.renameSync(temporary, ledgerPath);
152
200
  }
153
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
+
154
269
  function restoreText(target, previous) {
155
270
  if (previous === null) {
156
271
  try { fs.unlinkSync(target); } catch (error) {
@@ -161,18 +276,42 @@ function restoreText(target, previous) {
161
276
  writeFileAtomic(target, previous);
162
277
  }
163
278
 
164
- // Ledger intent lands before the file rename so a crash cannot leave a rule with no `before`.
165
- function commitWrite({ ledgerPath, target, content, entry }) {
166
- const previousLedger = readExisting(ledgerPath);
167
- 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 });
168
289
  try {
169
- writeFileAtomic(target, content);
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
+ }
170
297
  } catch (error) {
171
- try { restoreText(ledgerPath, previousLedger); } catch (compensateError) {
298
+ try { clearIntent(ledgerPath); } catch (compensateError) {
172
299
  error.cause = compensateError;
173
300
  }
174
301
  throw error;
175
302
  }
303
+ try {
304
+ appendLedgerLine(ledgerPath, serialized, resolved);
305
+ } catch (error) {
306
+ try {
307
+ restoreText(target, entry.before ?? null);
308
+ clearIntent(ledgerPath);
309
+ } catch (compensateError) {
310
+ error.cause = compensateError;
311
+ }
312
+ throw error;
313
+ }
314
+ clearIntent(ledgerPath);
176
315
  }
177
316
 
178
317
  // --- Signature parsing + template re-derivation ------------------------------
@@ -296,10 +435,14 @@ export function loadCatalog(filePath) {
296
435
  let normalizedEntry = entry;
297
436
  if (normalizedEntry.paths !== undefined) {
298
437
  if (!Array.isArray(normalizedEntry.paths)) return { entries: {}, error: 'invalid catalog paths' };
299
- normalizedEntry = {
300
- ...normalizedEntry,
301
- paths: normalizedEntry.paths.filter((item) => isRepoRelativePath(item)),
302
- };
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 };
303
446
  }
304
447
  if (
305
448
  normalizedEntry.command !== undefined
@@ -314,32 +457,56 @@ export function loadCatalog(filePath) {
314
457
  }
315
458
 
316
459
  function readPackageScriptNames(packagePath) {
460
+ let raw;
317
461
  try {
318
- const data = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
319
- if (data === null || typeof data !== 'object' || typeof data.scripts !== 'object' || data.scripts === null) {
320
- return [];
321
- }
322
- return Object.keys(data.scripts);
462
+ raw = fs.readFileSync(packagePath, 'utf8');
323
463
  } catch (error) {
324
- if (error && error.code === 'ENOENT') return [];
325
- return [];
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' };
326
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 };
327
481
  }
328
482
 
329
- export function collectScriptNames(rootDir) {
483
+ export function collectScriptReport(rootDir) {
330
484
  const names = new Set();
331
- for (const script of readPackageScriptNames(path.join(rootDir, 'package.json'))) names.add(script);
332
- for (const script of readPackageScriptNames(path.join(rootDir, 'app', 'package.json'))) names.add(script);
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'));
333
496
  let packageNames = [];
334
497
  try {
335
498
  packageNames = fs.readdirSync(path.join(rootDir, 'packages'));
336
- } catch {}
499
+ } catch (error) {
500
+ if (!error || error.code !== 'ENOENT') errors.push(`packages: ${error.message}`);
501
+ }
337
502
  for (const name of packageNames) {
338
- for (const script of readPackageScriptNames(path.join(rootDir, 'packages', name, 'package.json'))) {
339
- names.add(script);
340
- }
503
+ take(path.join(rootDir, 'packages', name, 'package.json'));
341
504
  }
342
- return names;
505
+ return { names, errors };
506
+ }
507
+
508
+ export function collectScriptNames(rootDir) {
509
+ return collectScriptReport(rootDir).names;
343
510
  }
344
511
 
345
512
  function repoRelativePathExists(rootDir, relPath) {
@@ -547,10 +714,22 @@ export function countRulesAndLines({ rulesDir, conventionsPath }) {
547
714
  for (const name of names) {
548
715
  if (!name.endsWith('.md')) continue;
549
716
  ruleCount += 1;
550
- 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
+ }
551
724
  }
552
725
  if (conventionsPath) {
553
- 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
+ }
554
733
  }
555
734
  return { ruleCount, lineCount };
556
735
  }
@@ -578,9 +757,11 @@ export function addConventionsEntry(content, section, entry) {
578
757
  const next = content.indexOf('\n## ', headerEnd);
579
758
  const sectionEnd = next === -1 ? content.length : next;
580
759
  const body = content.slice(idx, sectionEnd);
581
- 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);
582
763
  if (placeholder) {
583
- 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);
584
765
  }
585
766
  return `${content.slice(0, headerEnd)}\n\n- ${entry}${content.slice(headerEnd)}`;
586
767
  }
@@ -668,13 +849,14 @@ function tryUnloadOne({
668
849
  ledgerPath,
669
850
  now,
670
851
  canonical,
852
+ roots,
671
853
  }) {
672
854
  const candidates = [...latestConventionsAddedBySignature(prior).entries()]
673
855
  .sort(([a], [b]) => a.localeCompare(b));
674
856
  for (const [signature, appliedEntry] of candidates) {
675
857
  const line = addedLine(appliedEntry.before, appliedEntry.after);
676
858
  if (line === null) continue;
677
- const target = resolveLedgerTarget(appliedEntry.target, projectRootFor(ledgerPath));
859
+ const target = resolveLedgerTarget(appliedEntry.target, roots);
678
860
  const current = readExisting(target);
679
861
  if (current === null || !conventionsFileHasTrimmedLine(current, line)) continue;
680
862
  const signals = readSignalsForSignature(signalsPath, signature, canonical);
@@ -691,7 +873,7 @@ function tryUnloadOne({
691
873
  agent: appliedEntry.agent,
692
874
  slug: appliedEntry.slug,
693
875
  };
694
- commitWrite({ ledgerPath, target, content: after, entry });
876
+ commitWrite({ ledgerPath, target, content: after, entry, roots });
695
877
  prior.push(entry);
696
878
  markSignalsRolledBack(signature, { signalsPath, canonical });
697
879
  return { signature, target: appliedEntry.target };
@@ -717,17 +899,14 @@ export function rollbackInverse(entry, options = {}) {
717
899
  after: entry.before,
718
900
  at: now(),
719
901
  };
902
+ const roots = resolveRoots(ledgerPath, options);
720
903
  const token = acquireLock(lockPath);
721
- const target = resolveLedgerTarget(entry.target, projectRootFor(ledgerPath));
722
904
  try {
723
- if (inverse.after == null) {
724
- try { fs.unlinkSync(target); } catch (error) {
725
- if (!error || error.code !== 'ENOENT') throw error;
726
- }
727
- } else {
728
- writeFileAtomic(target, inverse.after);
729
- }
730
- 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 });
731
910
  return inverse;
732
911
  } finally {
733
912
  releaseLock(lockPath, token);
@@ -776,7 +955,6 @@ function enrichGroups(groups, signalsPath, canonical = (signature) => signature)
776
955
  const rank = SEVERITY_RANK[signal.severity] ?? 0;
777
956
  if (rank > entry.severityRank) { entry.severity = signal.severity; entry.severityRank = rank; }
778
957
  if (signal.stem) {
779
- entry.stem = signal.stem;
780
958
  entry.stems.push(signal.stem);
781
959
  }
782
960
  if (signal.target) {
@@ -795,7 +973,12 @@ function guardSurfaces(group, phrase, ruleText) {
795
973
  function decide(group, { rootDir, catalogEntry, scriptNames }) {
796
974
  const { kind, issue } = parseSignature(group.signature);
797
975
  const phrase = humanize(issue);
798
- const stem = validateStem(group.stem ?? 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);
799
982
  const lesson = resolveLesson({
800
983
  signals: group.signals,
801
984
  rootDir,
@@ -832,6 +1015,7 @@ function decide(group, { rootDir, catalogEntry, scriptNames }) {
832
1015
  severity: group.severity,
833
1016
  agent: group.agent,
834
1017
  slug: group.slugs[0] ?? group.signature,
1018
+ slugs: group.slugs ?? [],
835
1019
  };
836
1020
  }
837
1021
 
@@ -843,7 +1027,16 @@ function planConventions(ctx, decision) {
843
1027
  if (conventionsEntryExists(before, entry)) {
844
1028
  return { type: 'skipped', reason: 'dedup: identical entry already present', target };
845
1029
  }
846
- 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
+ }
847
1040
  const envelope = evaluateEnvelope({
848
1041
  ruleCount: ctx.envelope.ruleCount,
849
1042
  lineCount: ctx.envelope.lineCount,
@@ -872,6 +1065,7 @@ function ledgerEntry(decision, action, target, before, after, now) {
872
1065
  at: now(),
873
1066
  agent: decision.agent,
874
1067
  slug: decision.slug,
1068
+ slugs: Array.isArray(decision.slugs) ? [...decision.slugs] : [],
875
1069
  };
876
1070
  }
877
1071
 
@@ -914,15 +1108,15 @@ function proposedConventions(ctx, decision) {
914
1108
  }
915
1109
  }
916
1110
 
917
- 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 }) {
918
1112
  staged.push({ signature: decision.signature, target, reason });
919
1113
  if (hasOpenStage(prior, decision.signature)) return;
920
1114
  const entry = ledgerEntry(decision, action, target, before, after, now);
921
- appendLedgerLine(ledgerPath, entry);
1115
+ appendLedgerLine(ledgerPath, entry, roots);
922
1116
  prior.push(entry);
923
1117
  }
924
1118
 
925
- function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir }) {
1119
+ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir, roots }) {
926
1120
  const rulePath = path.join(rulesDir, `${decision.stem}.md`);
927
1121
  const editsExisting = fs.existsSync(rulePath);
928
1122
  const band = classifyBand({
@@ -945,6 +1139,7 @@ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir
945
1139
  now,
946
1140
  staged,
947
1141
  reason: band.reason,
1142
+ roots,
948
1143
  });
949
1144
  return;
950
1145
  }
@@ -962,22 +1157,79 @@ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir
962
1157
  now,
963
1158
  staged,
964
1159
  reason: 'seed already staged',
1160
+ roots,
965
1161
  });
966
1162
  return;
967
1163
  }
968
1164
  const reason = decision.compliance ?? (band.verdict === 'stage' ? band.reason : 'new rule staged for human promote');
969
1165
  const entry = ledgerEntry(decision, 'seed-staged', seed.target, null, seed.content, now);
970
- commitWrite({ ledgerPath, target: seed.target, content: seed.content, entry });
1166
+ commitWrite({ ledgerPath, target: seed.target, content: seed.content, entry, roots });
971
1167
  prior.push(entry);
972
1168
  staged.push({ signature: decision.signature, target: seed.target, reason });
973
1169
  }
974
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
+
975
1226
  /**
976
- * Cap count, one-apply-per-run, and every write share one lock. The envelope
977
- * 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.
978
1229
  */
979
1230
  function applyDecisionsUnderLock({
980
1231
  decisions,
1232
+ visiblePending,
981
1233
  rulesDir,
982
1234
  libraryDir,
983
1235
  conventionsPath,
@@ -986,9 +1238,12 @@ function applyDecisionsUnderLock({
986
1238
  signalsPath,
987
1239
  now,
988
1240
  canonical,
1241
+ rootDir,
1242
+ roots,
989
1243
  }) {
990
1244
  const token = acquireLock(lockPath);
991
1245
  try {
1246
+ const recovery = recoverPendingCommit(ledgerPath, roots);
992
1247
  let envelope = countRulesAndLines({ rulesDir, conventionsPath });
993
1248
  const prior = parseLedger(readExisting(ledgerPath) ?? '');
994
1249
  const ctx = { rulesDir, libraryDir, conventionsPath, envelope };
@@ -996,7 +1251,40 @@ function applyDecisionsUnderLock({
996
1251
  const staged = [];
997
1252
  const skipped = [];
998
1253
  const unloaded = [];
999
- let appliedThisRun = 0;
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
+ }
1000
1288
 
1001
1289
  const unloadedOne = tryUnloadOne({
1002
1290
  prior,
@@ -1005,6 +1293,7 @@ function applyDecisionsUnderLock({
1005
1293
  ledgerPath,
1006
1294
  now,
1007
1295
  canonical,
1296
+ roots,
1008
1297
  });
1009
1298
  let decisionsToApply = decisions;
1010
1299
  if (unloadedOne) {
@@ -1016,7 +1305,7 @@ function applyDecisionsUnderLock({
1016
1305
 
1017
1306
  for (const decision of decisionsToApply) {
1018
1307
  if (decision.tier.action === 'create') {
1019
- stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir });
1308
+ stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir, roots });
1020
1309
  envelope = countRulesAndLines({ rulesDir, conventionsPath });
1021
1310
  ctx.envelope = envelope;
1022
1311
  continue;
@@ -1044,6 +1333,7 @@ function applyDecisionsUnderLock({
1044
1333
  now,
1045
1334
  staged,
1046
1335
  reason: decision.compliance ?? band.reason,
1336
+ roots,
1047
1337
  });
1048
1338
  continue;
1049
1339
  }
@@ -1066,10 +1356,16 @@ function applyDecisionsUnderLock({
1066
1356
  now,
1067
1357
  staged,
1068
1358
  reason: plan.reason,
1359
+ roots,
1069
1360
  });
1070
1361
  continue;
1071
1362
  }
1072
- 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) {
1073
1369
  const proposed = proposedConventions(ctx, decision);
1074
1370
  appendStage({
1075
1371
  prior,
@@ -1081,7 +1377,10 @@ function applyDecisionsUnderLock({
1081
1377
  after: proposed.after,
1082
1378
  now,
1083
1379
  staged,
1084
- 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,
1085
1384
  });
1086
1385
  continue;
1087
1386
  }
@@ -1089,15 +1388,26 @@ function applyDecisionsUnderLock({
1089
1388
  const before = readExisting(plan.target);
1090
1389
  const after = addConventionsEntry(before ?? '', plan.section, plan.entry);
1091
1390
  const entry = ledgerEntry(decision, plan.action, plan.target, before, after, now);
1092
- commitWrite({ ledgerPath, target: plan.target, content: after, entry });
1391
+ commitWrite({ ledgerPath, target: plan.target, content: after, entry, roots });
1093
1392
  prior.push(entry);
1094
- appliedThisRun += 1;
1393
+ for (const slug of decisionSlugs) appliedSlugs.add(slug);
1095
1394
  applied.push({ signature: decision.signature, target: plan.target });
1096
1395
  envelope = countRulesAndLines({ rulesDir, conventionsPath });
1097
1396
  ctx.envelope = envelope;
1098
1397
  }
1099
1398
 
1100
- return { applied, staged, skipped, unloaded, 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 };
1101
1411
  } finally {
1102
1412
  releaseLock(lockPath, token);
1103
1413
  }
@@ -1115,7 +1425,10 @@ export function runImprover(options = {}) {
1115
1425
  const conventionsPath = options.conventionsPath ?? path.join(baseDir, 'conventions.md');
1116
1426
  const ledgerPath = options.ledgerPath ?? path.join(baseDir, 'rule-changes.jsonl');
1117
1427
  const lockPath = options.lockPath ?? path.join(baseDir, '.rules.lock');
1118
- const rootDir = options.rootDir ?? projectRootFor(ledgerPath);
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;
1119
1432
  const aliasPath = options.aliasPath ?? path.join(baseDir, 'signature-aliases.json');
1120
1433
  const catalogPath = options.catalogPath ?? path.join(baseDir, 'signature-catalog.json');
1121
1434
  const now = options.now ?? (() => new Date().toISOString());
@@ -1135,11 +1448,16 @@ export function runImprover(options = {}) {
1135
1448
  errors.push({ signature: 'signature-catalog', reason: catalogLoad.error });
1136
1449
  }
1137
1450
  const catalog = catalogLoad.entries;
1138
- const scriptNames = collectScriptNames(rootDir);
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;
1139
1456
 
1140
1457
  const rejected = [];
1141
1458
  const decisions = [];
1142
1459
  const skipped = [];
1460
+ const visiblePending = [];
1143
1461
 
1144
1462
  for (const group of enrichGroups(grouped.groups, signalsPath, canonical)) {
1145
1463
  if (group.distinctSlugCount < 2) continue;
@@ -1164,7 +1482,16 @@ export function runImprover(options = {}) {
1164
1482
  continue;
1165
1483
  }
1166
1484
  if (decision.lesson === null) {
1167
- skipped.push({ signature: decision.signature, reason: 'pending-lesson' });
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' });
1168
1495
  continue;
1169
1496
  }
1170
1497
  decisions.push(decision);
@@ -1174,22 +1501,28 @@ export function runImprover(options = {}) {
1174
1501
  let staged = [];
1175
1502
  let applySkipped = [];
1176
1503
  let unloaded = [];
1177
- let envelope;
1178
- ({ applied, staged, skipped: applySkipped, unloaded, envelope } = applyDecisionsUnderLock({
1179
- decisions,
1180
- rulesDir,
1181
- libraryDir,
1182
- conventionsPath,
1183
- ledgerPath,
1184
- lockPath,
1185
- signalsPath,
1186
- now,
1187
- canonical,
1188
- }));
1189
- // Mark the signals that actually wrote a change as `applied` so a later
1190
- // rejection/rollback can flip them to a non-qualifying status (W4).
1191
- for (const item of applied) {
1192
- markSignalsApplied(item.signature, { signalsPath, canonical });
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,
1520
+ }));
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 });
1193
1526
  }
1194
1527
 
1195
1528
  const allSkipped = [...skipped, ...applySkipped];
@@ -1210,15 +1543,17 @@ export function runImprover(options = {}) {
1210
1543
  rejected,
1211
1544
  errors,
1212
1545
  envelope,
1213
- ledgerPath,
1546
+ rootDir,
1547
+ roots,
1214
1548
  }),
1215
1549
  };
1216
1550
  }
1217
1551
 
1218
- function renderTarget(target, ledgerPath) {
1552
+ function renderTarget(target, roots) {
1553
+ if (target == null) return '(no file)';
1219
1554
  if (typeof target !== 'string') return String(target);
1220
1555
  try {
1221
- return toLedgerTarget(target, projectRootFor(ledgerPath));
1556
+ return toLedgerTarget(target, roots.repo);
1222
1557
  } catch {
1223
1558
  return target;
1224
1559
  }
@@ -1230,24 +1565,26 @@ function appendSkipGroup(lines, items, heading) {
1230
1565
  for (const item of items) lines.push(` - ${item.signature} (${item.reason})`);
1231
1566
  }
1232
1567
 
1233
- function renderReport({ applied, staged, skipped, rejected, unloaded = [], errors, envelope, ledgerPath }) {
1568
+ function renderReport({ applied, staged, skipped, rejected, unloaded = [], errors, envelope, roots }) {
1234
1569
  const lines = [
1235
1570
  'Self-learning rule improver',
1236
1571
  `envelope: ${envelope.ruleCount}/${MAX_ACTIVE_RULES} rules, ${envelope.lineCount}/${MAX_TOTAL_LINES} lines`,
1237
1572
  '',
1238
1573
  `applied (${applied.length}) — auto, low-risk, reversible`,
1239
1574
  ];
1240
- 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)}`);
1241
1576
  lines.push('', `staged (${staged.length}) — human promote`);
1242
- for (const item of staged) lines.push(` - ${item.signature} → ${renderTarget(item.target, ledgerPath)} (${item.reason})`);
1577
+ for (const item of staged) lines.push(` - ${item.signature} → ${renderTarget(item.target, roots)} (${item.reason})`);
1243
1578
  if (unloaded.length > 0) {
1244
1579
  lines.push('', `unloaded (${unloaded.length}) — lesson removed`);
1245
- for (const item of unloaded) lines.push(` - ${item.signature} → ${renderTarget(item.target, ledgerPath)}`);
1580
+ for (const item of unloaded) lines.push(` - ${item.signature} → ${renderTarget(item.target, roots)}`);
1246
1581
  }
1247
1582
  const pending = skipped.filter((item) => item.reason === 'pending-lesson');
1248
- const deduped = 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'));
1249
1585
  appendSkipGroup(lines, pending, `skipped (${pending.length}) — pending lesson`);
1250
1586
  appendSkipGroup(lines, deduped, `skipped (${deduped.length}) — dedup no-op`);
1587
+ appendSkipGroup(lines, otherSkipped, `skipped (${otherSkipped.length}) — not applied`);
1251
1588
  lines.push('', `rejected (${rejected.length}) — denylist`);
1252
1589
  for (const item of rejected) lines.push(` - ${item.signature} (${item.reason})`);
1253
1590
  if (errors.length > 0) {