@bonesofspring/ai-rules 0.2.50 → 0.2.51

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 (192) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +3 -1
  3. package/bin/cli.js +52 -13
  4. package/bin/lib/ai-local-drift.js +665 -0
  5. package/bin/lib/seed-ai-local-team.js +153 -35
  6. package/bin/mavis-install.js +6 -0
  7. package/bin/opencode-install.js +13 -2
  8. package/docs/LOCAL-OVERLAY.md +77 -1
  9. package/package.json +1 -1
  10. package/presets/_shared/ai-local/scripts/efficacy-oracle.mjs +1 -1
  11. package/presets/_shared/ai-local/scripts/rule-improver.mjs +491 -55
  12. package/presets/_shared/ai-local/scripts/run.mjs +56 -1
  13. package/presets/_shared/ai-local/scripts/signals.mjs +119 -6
  14. package/presets/_shared/core/quality/anti-hallucination-contract.md +2 -0
  15. package/presets/_shared/core/review/code-review-mr.md +20 -1
  16. package/presets/_shared/core/review/receiving-code-review.md +7 -0
  17. package/presets/claude/android-kotlin/agents/code-reviewer.md +14 -0
  18. package/presets/claude/android-kotlin/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  19. package/presets/claude/android-kotlin/rules/tooling-and-review/code-review.md +20 -1
  20. package/presets/claude/android-kotlin/skills/code-review/SKILL.md +11 -1
  21. package/presets/claude/go/agents/code-reviewer.md +36 -2
  22. package/presets/claude/go/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  23. package/presets/claude/go/rules/tooling-and-review/code-review.md +20 -1
  24. package/presets/claude/go/skills/code-review/SKILL.md +10 -1
  25. package/presets/claude/ios-swift/agents/code-reviewer.md +14 -0
  26. package/presets/claude/ios-swift/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  27. package/presets/claude/ios-swift/rules/tooling-and-review/code-review.md +20 -1
  28. package/presets/claude/ios-swift/skills/code-review/SKILL.md +11 -1
  29. package/presets/claude/java/agents/code-reviewer.md +36 -2
  30. package/presets/claude/java/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  31. package/presets/claude/java/rules/tooling-and-review/code-review.md +20 -1
  32. package/presets/claude/java/skills/code-review/SKILL.md +10 -1
  33. package/presets/claude/mcp-ts/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  34. package/presets/claude/mcp-ts/rules/tooling-and-review/code-review.md +20 -1
  35. package/presets/claude/mcp-ts/skills/code-review/SKILL.md +8 -0
  36. package/presets/claude/next/agents/code-reviewer.md +14 -0
  37. package/presets/claude/next/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  38. package/presets/claude/next/rules/tooling-and-review/code-review-mr.md +20 -1
  39. package/presets/claude/next/skills/code-review/SKILL.md +12 -2
  40. package/presets/claude/nuxt/agents/code-reviewer.md +14 -0
  41. package/presets/claude/nuxt/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  42. package/presets/claude/nuxt/rules/tooling-and-review/code-review-mr.md +20 -1
  43. package/presets/claude/nuxt/skills/code-review/SKILL.md +11 -1
  44. package/presets/claude/php-hexagonal/agents/code-reviewer.md +36 -2
  45. package/presets/claude/php-hexagonal/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  46. package/presets/claude/php-hexagonal/rules/tooling-and-review/code-review.md +20 -1
  47. package/presets/claude/php-hexagonal/skills/code-review/SKILL.md +10 -1
  48. package/presets/claude/php-laravel/agents/code-reviewer.md +36 -2
  49. package/presets/claude/php-laravel/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  50. package/presets/claude/php-laravel/rules/tooling-and-review/code-review.md +20 -1
  51. package/presets/claude/php-laravel/skills/code-review/SKILL.md +10 -1
  52. package/presets/claude/svelte/agents/code-reviewer.md +14 -0
  53. package/presets/claude/svelte/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  54. package/presets/claude/svelte/rules/tooling-and-review/code-review-mr.md +20 -1
  55. package/presets/claude/svelte/skills/code-review/SKILL.md +11 -1
  56. package/presets/cursor/android-kotlin/agents/code-reviewer.md +14 -0
  57. package/presets/cursor/android-kotlin/rules/anti-hallucination-contract.mdc +2 -0
  58. package/presets/cursor/android-kotlin/rules/code-review-mr.mdc +20 -1
  59. package/presets/cursor/android-kotlin/skills/code-review/SKILL.md +11 -1
  60. package/presets/cursor/go/agents/code-reviewer.md +36 -2
  61. package/presets/cursor/go/rules/anti-hallucination-contract.mdc +2 -0
  62. package/presets/cursor/go/rules/code-review-mr.mdc +20 -1
  63. package/presets/cursor/go/skills/code-review/SKILL.md +10 -1
  64. package/presets/cursor/ios-swift/agents/code-reviewer.md +14 -0
  65. package/presets/cursor/ios-swift/rules/anti-hallucination-contract.mdc +2 -0
  66. package/presets/cursor/ios-swift/rules/code-review-mr.mdc +20 -1
  67. package/presets/cursor/ios-swift/skills/code-review/SKILL.md +11 -1
  68. package/presets/cursor/java/agents/code-reviewer.md +36 -2
  69. package/presets/cursor/java/rules/anti-hallucination-contract.mdc +2 -0
  70. package/presets/cursor/java/rules/code-review-mr.mdc +20 -1
  71. package/presets/cursor/java/skills/code-review/SKILL.md +10 -1
  72. package/presets/cursor/mcp-ts/rules/anti-hallucination-contract.mdc +2 -0
  73. package/presets/cursor/mcp-ts/rules/code-review-mr.mdc +20 -1
  74. package/presets/cursor/mcp-ts/skills/code-review/SKILL.md +8 -0
  75. package/presets/cursor/next/agents/code-reviewer.md +14 -0
  76. package/presets/cursor/next/rules/anti-hallucination-contract.mdc +2 -0
  77. package/presets/cursor/next/rules/code-review-mr.mdc +20 -1
  78. package/presets/cursor/next/skills/code-review/SKILL.md +12 -2
  79. package/presets/cursor/nuxt/agents/code-reviewer.md +14 -0
  80. package/presets/cursor/nuxt/rules/anti-hallucination-contract.mdc +2 -0
  81. package/presets/cursor/nuxt/rules/code-review-mr.mdc +20 -1
  82. package/presets/cursor/nuxt/skills/code-review/SKILL.md +11 -1
  83. package/presets/cursor/php-hexagonal/agents/code-reviewer.md +36 -2
  84. package/presets/cursor/php-hexagonal/rules/anti-hallucination-contract.mdc +2 -0
  85. package/presets/cursor/php-hexagonal/rules/code-review-mr.mdc +20 -1
  86. package/presets/cursor/php-hexagonal/skills/code-review/SKILL.md +10 -1
  87. package/presets/cursor/php-laravel/agents/code-reviewer.md +36 -2
  88. package/presets/cursor/php-laravel/rules/anti-hallucination-contract.mdc +2 -0
  89. package/presets/cursor/php-laravel/rules/code-review-mr.mdc +20 -1
  90. package/presets/cursor/php-laravel/skills/code-review/SKILL.md +10 -1
  91. package/presets/cursor/svelte/agents/code-reviewer.md +14 -0
  92. package/presets/cursor/svelte/rules/anti-hallucination-contract.mdc +2 -0
  93. package/presets/cursor/svelte/rules/code-review-mr.mdc +20 -1
  94. package/presets/cursor/svelte/skills/code-review/SKILL.md +11 -1
  95. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  96. package/presets/mavis/android-kotlin/agents/code-reviewer.md +14 -0
  97. package/presets/mavis/android-kotlin/rules/anti-hallucination-contract.md +2 -0
  98. package/presets/mavis/android-kotlin/rules/code-review-mr.md +20 -1
  99. package/presets/mavis/android-kotlin/skills/code-review/SKILL.md +11 -1
  100. package/presets/mavis/go/adapter-map.json +1 -1
  101. package/presets/mavis/go/agents/code-reviewer.md +36 -2
  102. package/presets/mavis/go/rules/anti-hallucination-contract.md +2 -0
  103. package/presets/mavis/go/rules/code-review-mr.md +20 -1
  104. package/presets/mavis/go/skills/code-review/SKILL.md +10 -1
  105. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  106. package/presets/mavis/ios-swift/agents/code-reviewer.md +14 -0
  107. package/presets/mavis/ios-swift/rules/anti-hallucination-contract.md +2 -0
  108. package/presets/mavis/ios-swift/rules/code-review-mr.md +20 -1
  109. package/presets/mavis/ios-swift/skills/code-review/SKILL.md +11 -1
  110. package/presets/mavis/java/adapter-map.json +1 -1
  111. package/presets/mavis/java/agents/code-reviewer.md +36 -2
  112. package/presets/mavis/java/rules/anti-hallucination-contract.md +2 -0
  113. package/presets/mavis/java/rules/code-review-mr.md +20 -1
  114. package/presets/mavis/java/skills/code-review/SKILL.md +10 -1
  115. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  116. package/presets/mavis/mcp-ts/rules/anti-hallucination-contract.md +2 -0
  117. package/presets/mavis/mcp-ts/rules/code-review-mr.md +20 -1
  118. package/presets/mavis/mcp-ts/skills/code-review/SKILL.md +8 -0
  119. package/presets/mavis/next/adapter-map.json +1 -1
  120. package/presets/mavis/next/agents/code-reviewer.md +14 -0
  121. package/presets/mavis/next/rules/anti-hallucination-contract.md +2 -0
  122. package/presets/mavis/next/rules/code-review-mr.md +20 -1
  123. package/presets/mavis/next/skills/code-review/SKILL.md +12 -2
  124. package/presets/mavis/nuxt/adapter-map.json +1 -1
  125. package/presets/mavis/nuxt/agents/code-reviewer.md +14 -0
  126. package/presets/mavis/nuxt/rules/anti-hallucination-contract.md +2 -0
  127. package/presets/mavis/nuxt/rules/code-review-mr.md +20 -1
  128. package/presets/mavis/nuxt/skills/code-review/SKILL.md +11 -1
  129. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  130. package/presets/mavis/php-hexagonal/agents/code-reviewer.md +36 -2
  131. package/presets/mavis/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
  132. package/presets/mavis/php-hexagonal/rules/code-review-mr.md +20 -1
  133. package/presets/mavis/php-hexagonal/skills/code-review/SKILL.md +10 -1
  134. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  135. package/presets/mavis/php-laravel/agents/code-reviewer.md +36 -2
  136. package/presets/mavis/php-laravel/rules/anti-hallucination-contract.md +2 -0
  137. package/presets/mavis/php-laravel/rules/code-review-mr.md +20 -1
  138. package/presets/mavis/php-laravel/skills/code-review/SKILL.md +10 -1
  139. package/presets/mavis/svelte/adapter-map.json +1 -1
  140. package/presets/mavis/svelte/agents/code-reviewer.md +14 -0
  141. package/presets/mavis/svelte/rules/anti-hallucination-contract.md +2 -0
  142. package/presets/mavis/svelte/rules/code-review-mr.md +20 -1
  143. package/presets/mavis/svelte/skills/code-review/SKILL.md +11 -1
  144. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  145. package/presets/opencode/android-kotlin/agents/code-reviewer.md +14 -0
  146. package/presets/opencode/android-kotlin/rules/anti-hallucination-contract.md +2 -0
  147. package/presets/opencode/android-kotlin/rules/code-review-mr.md +20 -1
  148. package/presets/opencode/android-kotlin/skills/code-review/SKILL.md +11 -1
  149. package/presets/opencode/go/adapter-map.json +1 -1
  150. package/presets/opencode/go/agents/code-reviewer.md +36 -2
  151. package/presets/opencode/go/rules/anti-hallucination-contract.md +2 -0
  152. package/presets/opencode/go/rules/code-review-mr.md +20 -1
  153. package/presets/opencode/go/skills/code-review/SKILL.md +10 -1
  154. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  155. package/presets/opencode/ios-swift/agents/code-reviewer.md +14 -0
  156. package/presets/opencode/ios-swift/rules/anti-hallucination-contract.md +2 -0
  157. package/presets/opencode/ios-swift/rules/code-review-mr.md +20 -1
  158. package/presets/opencode/ios-swift/skills/code-review/SKILL.md +11 -1
  159. package/presets/opencode/java/adapter-map.json +1 -1
  160. package/presets/opencode/java/agents/code-reviewer.md +36 -2
  161. package/presets/opencode/java/rules/anti-hallucination-contract.md +2 -0
  162. package/presets/opencode/java/rules/code-review-mr.md +20 -1
  163. package/presets/opencode/java/skills/code-review/SKILL.md +10 -1
  164. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  165. package/presets/opencode/mcp-ts/rules/anti-hallucination-contract.md +2 -0
  166. package/presets/opencode/mcp-ts/rules/code-review-mr.md +20 -1
  167. package/presets/opencode/mcp-ts/skills/code-review/SKILL.md +8 -0
  168. package/presets/opencode/next/adapter-map.json +1 -1
  169. package/presets/opencode/next/agents/code-reviewer.md +14 -0
  170. package/presets/opencode/next/rules/anti-hallucination-contract.md +2 -0
  171. package/presets/opencode/next/rules/code-review-mr.md +20 -1
  172. package/presets/opencode/next/skills/code-review/SKILL.md +12 -2
  173. package/presets/opencode/nuxt/adapter-map.json +1 -1
  174. package/presets/opencode/nuxt/agents/code-reviewer.md +14 -0
  175. package/presets/opencode/nuxt/rules/anti-hallucination-contract.md +2 -0
  176. package/presets/opencode/nuxt/rules/code-review-mr.md +20 -1
  177. package/presets/opencode/nuxt/skills/code-review/SKILL.md +11 -1
  178. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  179. package/presets/opencode/php-hexagonal/agents/code-reviewer.md +36 -2
  180. package/presets/opencode/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
  181. package/presets/opencode/php-hexagonal/rules/code-review-mr.md +20 -1
  182. package/presets/opencode/php-hexagonal/skills/code-review/SKILL.md +10 -1
  183. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  184. package/presets/opencode/php-laravel/agents/code-reviewer.md +36 -2
  185. package/presets/opencode/php-laravel/rules/anti-hallucination-contract.md +2 -0
  186. package/presets/opencode/php-laravel/rules/code-review-mr.md +20 -1
  187. package/presets/opencode/php-laravel/skills/code-review/SKILL.md +10 -1
  188. package/presets/opencode/svelte/adapter-map.json +1 -1
  189. package/presets/opencode/svelte/agents/code-reviewer.md +14 -0
  190. package/presets/opencode/svelte/rules/anti-hallucination-contract.md +2 -0
  191. package/presets/opencode/svelte/rules/code-review-mr.md +20 -1
  192. 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) -------------------------------------
@@ -202,17 +211,221 @@ export function imperativeSentence(kind, phrase) {
202
211
  return `${KIND_VERB[kind] ?? 'Fix'} ${phrase}.`;
203
212
  }
204
213
 
214
+ function signatureKind(signature) {
215
+ return signature.slice(0, signature.indexOf(':'));
216
+ }
217
+
218
+ export function loadAliasMap(filePath) {
219
+ let raw;
220
+ try {
221
+ raw = fs.readFileSync(filePath, 'utf8');
222
+ } catch (error) {
223
+ if (error && error.code === 'ENOENT') return { aliases: {}, error: null };
224
+ return { aliases: {}, error: error instanceof Error ? error.message : String(error) };
225
+ }
226
+ let data;
227
+ try {
228
+ data = JSON.parse(raw);
229
+ } catch {
230
+ return { aliases: {}, error: 'invalid JSON' };
231
+ }
232
+ if (
233
+ data === null
234
+ || typeof data !== 'object'
235
+ || data.version !== 1
236
+ || typeof data.aliases !== 'object'
237
+ || data.aliases === null
238
+ || Array.isArray(data.aliases)
239
+ ) {
240
+ return { aliases: {}, error: 'malformed alias map' };
241
+ }
242
+ const aliases = {};
243
+ for (const [from, to] of Object.entries(data.aliases)) {
244
+ if (typeof from !== 'string' || typeof to !== 'string' || !SIGNATURE_RE.test(from) || !SIGNATURE_RE.test(to)) {
245
+ return { aliases: {}, error: 'invalid alias entry' };
246
+ }
247
+ if (signatureKind(from) !== signatureKind(to)) {
248
+ return { aliases: {}, error: 'kind mismatch' };
249
+ }
250
+ aliases[from] = to;
251
+ }
252
+ return { aliases, error: null };
253
+ }
254
+
255
+ export function canonicalSignature(signature, aliases) {
256
+ const visited = new Set();
257
+ let current = signature;
258
+ while (Object.prototype.hasOwnProperty.call(aliases, current)) {
259
+ if (visited.has(current)) throw new Error('alias cycle');
260
+ visited.add(current);
261
+ current = aliases[current];
262
+ }
263
+ return current;
264
+ }
265
+
266
+ export function loadCatalog(filePath) {
267
+ let raw;
268
+ try {
269
+ raw = fs.readFileSync(filePath, 'utf8');
270
+ } catch (error) {
271
+ if (error && error.code === 'ENOENT') return { entries: {}, error: null };
272
+ return { entries: {}, error: error instanceof Error ? error.message : String(error) };
273
+ }
274
+ let data;
275
+ try {
276
+ data = JSON.parse(raw);
277
+ } catch {
278
+ return { entries: {}, error: 'invalid JSON' };
279
+ }
280
+ if (
281
+ data === null
282
+ || typeof data !== 'object'
283
+ || data.version !== 1
284
+ || typeof data.entries !== 'object'
285
+ || data.entries === null
286
+ || Array.isArray(data.entries)
287
+ ) {
288
+ return { entries: {}, error: 'malformed catalog' };
289
+ }
290
+ const entries = {};
291
+ for (const [signature, entry] of Object.entries(data.entries)) {
292
+ if (!SIGNATURE_RE.test(signature)) return { entries: {}, error: 'invalid catalog signature' };
293
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
294
+ return { entries: {}, error: 'invalid catalog entry' };
295
+ }
296
+ let normalizedEntry = entry;
297
+ if (normalizedEntry.paths !== undefined) {
298
+ if (!Array.isArray(normalizedEntry.paths)) return { entries: {}, error: 'invalid catalog paths' };
299
+ normalizedEntry = {
300
+ ...normalizedEntry,
301
+ paths: normalizedEntry.paths.filter((item) => isRepoRelativePath(item)),
302
+ };
303
+ }
304
+ if (
305
+ normalizedEntry.command !== undefined
306
+ && normalizedEntry.command !== null
307
+ && typeof normalizedEntry.command !== 'string'
308
+ ) {
309
+ return { entries: {}, error: 'invalid catalog command' };
310
+ }
311
+ entries[signature] = normalizedEntry;
312
+ }
313
+ return { entries, error: null };
314
+ }
315
+
316
+ function readPackageScriptNames(packagePath) {
317
+ 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);
323
+ } catch (error) {
324
+ if (error && error.code === 'ENOENT') return [];
325
+ return [];
326
+ }
327
+ }
328
+
329
+ export function collectScriptNames(rootDir) {
330
+ 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);
333
+ let packageNames = [];
334
+ try {
335
+ packageNames = fs.readdirSync(path.join(rootDir, 'packages'));
336
+ } catch {}
337
+ for (const name of packageNames) {
338
+ for (const script of readPackageScriptNames(path.join(rootDir, 'packages', name, 'package.json'))) {
339
+ names.add(script);
340
+ }
341
+ }
342
+ return names;
343
+ }
344
+
345
+ function repoRelativePathExists(rootDir, relPath) {
346
+ if (!isRepoRelativePath(relPath)) return false;
347
+ const rootAbs = path.resolve(rootDir);
348
+ const abs = path.resolve(rootAbs, relPath);
349
+ const relative = path.relative(rootAbs, abs);
350
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) return false;
351
+ try {
352
+ return fs.existsSync(abs);
353
+ } catch {
354
+ return false;
355
+ }
356
+ }
357
+
358
+ function normalizedScriptCommand(command) {
359
+ if (command === undefined || command === null) return null;
360
+ return isScriptCommandName(command) ? command : null;
361
+ }
362
+
363
+ export function resolveLesson({ signals, rootDir, catalogEntry, scriptNames }) {
364
+ const slugsByPath = new Map();
365
+ for (const signal of signals) {
366
+ if (!Array.isArray(signal.paths)) continue;
367
+ for (const item of signal.paths) {
368
+ const slugs = slugsByPath.get(item) ?? new Set();
369
+ slugs.add(signal.slug);
370
+ slugsByPath.set(item, slugs);
371
+ }
372
+ }
373
+ const candidatePaths = new Set();
374
+ for (const [item, slugs] of slugsByPath) {
375
+ if (slugs.size >= 2) candidatePaths.add(item);
376
+ }
377
+ if (catalogEntry?.paths) {
378
+ for (const item of catalogEntry.paths) candidatePaths.add(item);
379
+ }
380
+ const paths = [...candidatePaths].filter((item) => repoRelativePathExists(rootDir, item)).sort();
381
+ if (paths.length === 0) return null;
382
+
383
+ let command = null;
384
+ if (catalogEntry?.command) {
385
+ command = normalizedScriptCommand(catalogEntry.command);
386
+ } else {
387
+ const slugsByCommand = new Map();
388
+ for (const signal of signals) {
389
+ const script = normalizedScriptCommand(signal.command);
390
+ if (script === null) continue;
391
+ const slugs = slugsByCommand.get(script) ?? new Set();
392
+ slugs.add(signal.slug);
393
+ slugsByCommand.set(script, slugs);
394
+ }
395
+ const agreed = [...slugsByCommand.entries()].filter(([, slugs]) => slugs.size >= 2);
396
+ if (agreed.length === 1) command = agreed[0][0];
397
+ }
398
+ if (command !== null && !scriptNames.has(command)) command = null;
399
+ return { paths, command };
400
+ }
401
+
402
+ export function lessonSentence({ kind, issue, paths, command }) {
403
+ if (!Array.isArray(paths) || paths.length === 0) return null;
404
+ const pathLabel = paths.join('`, `');
405
+ const phrase = humanize(issue);
406
+ if (command) {
407
+ return `When editing \`${pathLabel}\`, run \`${command}\` before the receipt (${phrase}).`;
408
+ }
409
+ const first = phrase.split(' ')[0];
410
+ if (DIRECTIVE_PREFIXES.has(first)) return `When editing \`${pathLabel}\`, ${phrase}.`;
411
+ return `When editing \`${pathLabel}\`, ${(KIND_VERB[kind] ?? 'Fix').toLowerCase()} ${phrase}.`;
412
+ }
413
+
205
414
  /**
206
415
  * Re-derive the rule text from the signature via the canonical template
207
416
  * (architecture.md §3). The only free-form input is the already-validated
208
417
  * kebab-case `issue` and `stem`; `kind` comes from the fixed vocabulary, so
209
418
  * no task/spec prose can reach the rule body.
210
419
  */
211
- export function deriveRuleText({ stem, kind, issue, overrideKill = null }) {
420
+ export function deriveRuleText({ stem, kind, issue, overrideKill = null, paths, command = null }) {
212
421
  validateStem(stem);
213
422
  if (!KINDS.includes(kind)) throw new Error(`unknown kind "${kind}"`);
214
423
  const phrase = humanize(issue);
215
- const sentence = imperativeSentence(kind, phrase);
424
+ const lessonPaths = (paths ?? []).filter((item) => isRepoRelativePath(item));
425
+ const lessonCommand = normalizedScriptCommand(command);
426
+ const sentence = lessonPaths.length > 0
427
+ ? lessonSentence({ kind, issue, paths: lessonPaths, command: lessonCommand })
428
+ : imperativeSentence(kind, phrase);
216
429
  const lines = [`# ${stem}`, ''];
217
430
  if (overrideKill !== null) {
218
431
  if (typeof overrideKill !== 'string' || !STEM_RE.test(overrideKill)) {
@@ -226,8 +439,16 @@ export function deriveRuleText({ stem, kind, issue, overrideKill = null }) {
226
439
  return `${lines.join('\n')}\n`;
227
440
  }
228
441
 
229
- function deriveSeedText({ stem, kind, issue }) {
230
- return `glob: always\n\n## Body\n\n${deriveRuleText({ stem, kind, issue })}`;
442
+ function deriveSeedText({ stem, kind, issue, paths, command }) {
443
+ return `glob: always\n\n## Body\n\n${deriveRuleText({ stem, kind, issue, paths, command })}`;
444
+ }
445
+
446
+ /** Read-only `--status` lesson line: `lesson: pending` or `lesson: app/src [lint:js]`. */
447
+ export function formatLessonStatus(lesson) {
448
+ if (lesson === null) return 'lesson: pending';
449
+ const pathLabel = lesson.paths.join(', ');
450
+ if (lesson.command) return `lesson: ${pathLabel} [${lesson.command}]`;
451
+ return `lesson: ${pathLabel}`;
231
452
  }
232
453
 
233
454
  // --- Guards ------------------------------------------------------------------
@@ -364,6 +585,120 @@ export function addConventionsEntry(content, section, entry) {
364
585
  return `${content.slice(0, headerEnd)}\n\n- ${entry}${content.slice(headerEnd)}`;
365
586
  }
366
587
 
588
+ export function addedLine(before, after) {
589
+ const prior = new Set(String(before ?? '').split('\n').map((row) => row.trim()).filter((row) => row !== ''));
590
+ const added = String(after ?? '').split('\n').map((row) => row.trim()).filter((row) => row !== '' && !prior.has(row));
591
+ return added.length === 1 ? added[0] : null;
592
+ }
593
+
594
+ export function recurrenceSlugs({ signals, appliedAt }) {
595
+ const appliedMs = Date.parse(appliedAt);
596
+ const bySlug = new Map();
597
+ for (const signal of signals) {
598
+ if (signal.status === 'rejected' || signal.status === 'rolled_back') continue;
599
+ const list = bySlug.get(signal.slug) ?? [];
600
+ list.push(signal);
601
+ bySlug.set(signal.slug, list);
602
+ }
603
+ const recurring = [];
604
+ for (const [slug, rows] of bySlug) {
605
+ const hasAtOrBefore = rows.some((row) => Date.parse(row.at) <= appliedMs);
606
+ if (hasAtOrBefore) continue;
607
+ const hasAfter = rows.some((row) => Date.parse(row.at) > appliedMs);
608
+ if (hasAfter) recurring.push(slug);
609
+ }
610
+ return recurring.sort();
611
+ }
612
+
613
+ function removeTrimmedLineOnce(content, trimmedLine) {
614
+ const lines = content.split('\n');
615
+ let removed = false;
616
+ const next = lines.filter((line) => {
617
+ if (!removed && line.trim() === trimmedLine) {
618
+ removed = true;
619
+ return false;
620
+ }
621
+ return true;
622
+ });
623
+ if (!removed) return null;
624
+ return next.join('\n');
625
+ }
626
+
627
+ function conventionsFileHasTrimmedLine(content, trimmedLine) {
628
+ return content.split('\n').some((line) => line.trim() === trimmedLine);
629
+ }
630
+
631
+ function readSignalsForSignature(signalsPath, signature, canonical) {
632
+ let raw = '';
633
+ try { raw = fs.readFileSync(signalsPath, 'utf8'); } catch (error) {
634
+ if (error && error.code === 'ENOENT') return [];
635
+ throw error;
636
+ }
637
+ const signals = [];
638
+ for (const line of raw.split('\n')) {
639
+ const trimmed = line.trim();
640
+ if (trimmed === '') continue;
641
+ let signal;
642
+ try { signal = JSON.parse(trimmed); validateSignal(signal); } catch { continue; }
643
+ let groupSignature;
644
+ try { groupSignature = canonical(signal.signature); } catch { continue; }
645
+ if (groupSignature !== signature) continue;
646
+ signals.push(signal);
647
+ }
648
+ return signals;
649
+ }
650
+
651
+ function latestConventionsAddedBySignature(entries) {
652
+ const bySignature = new Map();
653
+ for (const entry of entries) {
654
+ if (!entry || typeof entry.signature !== 'string') continue;
655
+ if (entry.action === 'conventions-added') {
656
+ bySignature.set(entry.signature, entry);
657
+ } else if (entry.action === 'unloaded') {
658
+ bySignature.delete(entry.signature);
659
+ }
660
+ }
661
+ return bySignature;
662
+ }
663
+
664
+ function tryUnloadOne({
665
+ prior,
666
+ signalsPath,
667
+ conventionsPath,
668
+ ledgerPath,
669
+ now,
670
+ canonical,
671
+ }) {
672
+ const candidates = [...latestConventionsAddedBySignature(prior).entries()]
673
+ .sort(([a], [b]) => a.localeCompare(b));
674
+ for (const [signature, appliedEntry] of candidates) {
675
+ const line = addedLine(appliedEntry.before, appliedEntry.after);
676
+ if (line === null) continue;
677
+ const target = resolveLedgerTarget(appliedEntry.target, projectRootFor(ledgerPath));
678
+ const current = readExisting(target);
679
+ if (current === null || !conventionsFileHasTrimmedLine(current, line)) continue;
680
+ const signals = readSignalsForSignature(signalsPath, signature, canonical);
681
+ if (recurrenceSlugs({ signals, appliedAt: appliedEntry.at }).length < 2) continue;
682
+ const after = removeTrimmedLineOnce(current, line);
683
+ if (after === null) continue;
684
+ const entry = {
685
+ signature,
686
+ action: 'unloaded',
687
+ target: appliedEntry.target,
688
+ before: current,
689
+ after,
690
+ at: now(),
691
+ agent: appliedEntry.agent,
692
+ slug: appliedEntry.slug,
693
+ };
694
+ commitWrite({ ledgerPath, target, content: after, entry });
695
+ prior.push(entry);
696
+ markSignalsRolledBack(signature, { signalsPath, canonical });
697
+ return { signature, target: appliedEntry.target };
698
+ }
699
+ return null;
700
+ }
701
+
367
702
  // --- Rollback inverse --------------------------------------------------------
368
703
 
369
704
  export function rollbackInverse(entry, options = {}) {
@@ -401,8 +736,23 @@ export function rollbackInverse(entry, options = {}) {
401
736
 
402
737
  // --- Engine ------------------------------------------------------------------
403
738
 
404
- function enrichGroups(groups, signalsPath) {
405
- const bySignature = new Map();
739
+ function enrichGroups(groups, signalsPath, canonical = (signature) => signature) {
740
+ const bySignature = new Map(
741
+ groups.map((group) => [group.signature, {
742
+ signature: group.signature,
743
+ distinctSlugCount: group.distinctSlugCount,
744
+ slugs: group.slugs,
745
+ count: group.count,
746
+ signals: [],
747
+ severity: 'low',
748
+ severityRank: 0,
749
+ stem: null,
750
+ stems: [],
751
+ target: null,
752
+ targets: [],
753
+ agent: null,
754
+ }]),
755
+ );
406
756
  let raw = '';
407
757
  try { raw = fs.readFileSync(signalsPath, 'utf8'); } catch (error) {
408
758
  if (error && error.code === 'ENOENT') raw = '';
@@ -414,9 +764,15 @@ function enrichGroups(groups, signalsPath) {
414
764
  let signal;
415
765
  try { signal = JSON.parse(trimmed); validateSignal(signal); } catch { continue; }
416
766
  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
- };
767
+ let groupSignature;
768
+ try {
769
+ groupSignature = canonical(signal.signature);
770
+ } catch {
771
+ continue;
772
+ }
773
+ const entry = bySignature.get(groupSignature);
774
+ if (!entry) continue;
775
+ entry.signals.push(signal);
420
776
  const rank = SEVERITY_RANK[signal.severity] ?? 0;
421
777
  if (rank > entry.severityRank) { entry.severity = signal.severity; entry.severityRank = rank; }
422
778
  if (signal.stem) {
@@ -428,34 +784,27 @@ function enrichGroups(groups, signalsPath) {
428
784
  entry.targets.push(signal.target);
429
785
  }
430
786
  if (!entry.agent) entry.agent = signal.agent;
431
- bySignature.set(signal.signature, entry);
432
787
  }
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
- });
788
+ return [...bySignature.values()];
448
789
  }
449
790
 
450
791
  function guardSurfaces(group, phrase, ruleText) {
451
792
  return [group.signature, phrase, ruleText, ...(group.targets ?? []), ...(group.stems ?? [])];
452
793
  }
453
794
 
454
- function decide(group) {
795
+ function decide(group, { rootDir, catalogEntry, scriptNames }) {
455
796
  const { kind, issue } = parseSignature(group.signature);
456
797
  const phrase = humanize(issue);
457
798
  const stem = validateStem(group.stem ?? issue);
458
- const ruleText = deriveRuleText({ stem, kind, issue });
799
+ const lesson = resolveLesson({
800
+ signals: group.signals,
801
+ rootDir,
802
+ catalogEntry,
803
+ scriptNames,
804
+ });
805
+ const paths = lesson?.paths;
806
+ const command = lesson?.command ?? null;
807
+ const ruleText = deriveRuleText({ stem, kind, issue, paths, command });
459
808
  const surfaces = guardSurfaces(group, phrase, ruleText);
460
809
  const denied = surfaces.some((text) => isDenied(text));
461
810
  let compliance = null;
@@ -464,6 +813,9 @@ function decide(group) {
464
813
  if (compliance) break;
465
814
  }
466
815
  const tier = thresholdAction(group.distinctSlugCount);
816
+ const conventionsEntry = lesson
817
+ ? lessonSentence({ kind, issue, paths: lesson.paths, command: lesson.command })
818
+ : null;
467
819
  return {
468
820
  signature: group.signature,
469
821
  kind,
@@ -473,8 +825,10 @@ function decide(group) {
473
825
  tier,
474
826
  denied,
475
827
  compliance,
828
+ lesson,
829
+ conventionsEntry,
476
830
  ruleText,
477
- seedText: deriveSeedText({ stem, kind, issue }),
831
+ seedText: deriveSeedText({ stem, kind, issue, paths, command }),
478
832
  severity: group.severity,
479
833
  agent: group.agent,
480
834
  slug: group.slugs[0] ?? group.signature,
@@ -484,7 +838,7 @@ function decide(group) {
484
838
  function planConventions(ctx, decision) {
485
839
  const target = ctx.conventionsPath;
486
840
  const section = KIND_SECTION[decision.kind] ?? 'Patterns';
487
- const entry = imperativeSentence(decision.kind, decision.phrase);
841
+ const entry = decision.conventionsEntry ?? imperativeSentence(decision.kind, decision.phrase);
488
842
  const before = readExisting(target) ?? '';
489
843
  if (conventionsEntryExists(before, entry)) {
490
844
  return { type: 'skipped', reason: 'dedup: identical entry already present', target };
@@ -552,7 +906,7 @@ function proposedConventions(ctx, decision) {
552
906
  const before = readExisting(ctx.conventionsPath);
553
907
  if (before === null) return { before, after: null };
554
908
  const section = KIND_SECTION[decision.kind] ?? 'Patterns';
555
- const bullet = imperativeSentence(decision.kind, decision.phrase);
909
+ const bullet = decision.conventionsEntry ?? imperativeSentence(decision.kind, decision.phrase);
556
910
  try {
557
911
  return { before, after: addConventionsEntry(before, section, bullet) };
558
912
  } catch {
@@ -622,7 +976,17 @@ function stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir
622
976
  * Cap count, one-apply-per-run, and every write share one lock. The envelope
623
977
  * and the ledger are read again here — not from the pre-lock snapshot.
624
978
  */
625
- function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsPath, ledgerPath, lockPath, now }) {
979
+ function applyDecisionsUnderLock({
980
+ decisions,
981
+ rulesDir,
982
+ libraryDir,
983
+ conventionsPath,
984
+ ledgerPath,
985
+ lockPath,
986
+ signalsPath,
987
+ now,
988
+ canonical,
989
+ }) {
626
990
  const token = acquireLock(lockPath);
627
991
  try {
628
992
  let envelope = countRulesAndLines({ rulesDir, conventionsPath });
@@ -631,9 +995,26 @@ function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsP
631
995
  const applied = [];
632
996
  const staged = [];
633
997
  const skipped = [];
998
+ const unloaded = [];
634
999
  let appliedThisRun = 0;
635
1000
 
636
- for (const decision of decisions) {
1001
+ const unloadedOne = tryUnloadOne({
1002
+ prior,
1003
+ signalsPath,
1004
+ conventionsPath,
1005
+ ledgerPath,
1006
+ now,
1007
+ canonical,
1008
+ });
1009
+ let decisionsToApply = decisions;
1010
+ if (unloadedOne) {
1011
+ unloaded.push(unloadedOne);
1012
+ envelope = countRulesAndLines({ rulesDir, conventionsPath });
1013
+ ctx.envelope = envelope;
1014
+ decisionsToApply = decisions.filter((item) => item.signature !== unloadedOne.signature);
1015
+ }
1016
+
1017
+ for (const decision of decisionsToApply) {
637
1018
  if (decision.tier.action === 'create') {
638
1019
  stageNewRule({ decision, ctx, prior, ledgerPath, now, staged, rulesDir });
639
1020
  envelope = countRulesAndLines({ rulesDir, conventionsPath });
@@ -716,7 +1097,7 @@ function applyDecisionsUnderLock({ decisions, rulesDir, libraryDir, conventionsP
716
1097
  ctx.envelope = envelope;
717
1098
  }
718
1099
 
719
- return { applied, staged, skipped, envelope };
1100
+ return { applied, staged, skipped, unloaded, envelope };
720
1101
  } finally {
721
1102
  releaseLock(lockPath, token);
722
1103
  }
@@ -734,17 +1115,41 @@ export function runImprover(options = {}) {
734
1115
  const conventionsPath = options.conventionsPath ?? path.join(baseDir, 'conventions.md');
735
1116
  const ledgerPath = options.ledgerPath ?? path.join(baseDir, 'rule-changes.jsonl');
736
1117
  const lockPath = options.lockPath ?? path.join(baseDir, '.rules.lock');
1118
+ const rootDir = options.rootDir ?? projectRootFor(ledgerPath);
1119
+ const aliasPath = options.aliasPath ?? path.join(baseDir, 'signature-aliases.json');
1120
+ const catalogPath = options.catalogPath ?? path.join(baseDir, 'signature-catalog.json');
737
1121
  const now = options.now ?? (() => new Date().toISOString());
738
1122
 
739
- const { groups, errors } = groupSignatures({ signalsPath });
1123
+ const errors = [];
1124
+ const aliasLoad = loadAliasMap(aliasPath);
1125
+ if (aliasLoad.error) {
1126
+ errors.push({ signature: 'signature-aliases', reason: aliasLoad.error });
1127
+ }
1128
+ const canonical = (signature) => canonicalSignature(signature, aliasLoad.aliases);
1129
+
1130
+ const grouped = groupSignatures({ signalsPath, canonical });
1131
+ errors.push(...grouped.errors);
1132
+
1133
+ const catalogLoad = loadCatalog(catalogPath);
1134
+ if (catalogLoad.error) {
1135
+ errors.push({ signature: 'signature-catalog', reason: catalogLoad.error });
1136
+ }
1137
+ const catalog = catalogLoad.entries;
1138
+ const scriptNames = collectScriptNames(rootDir);
1139
+
740
1140
  const rejected = [];
741
1141
  const decisions = [];
1142
+ const skipped = [];
742
1143
 
743
- for (const group of enrichGroups(groups, signalsPath)) {
1144
+ for (const group of enrichGroups(grouped.groups, signalsPath, canonical)) {
744
1145
  if (group.distinctSlugCount < 2) continue;
745
1146
  let decision;
746
1147
  try {
747
- decision = decide(group);
1148
+ decision = decide(group, {
1149
+ rootDir,
1150
+ catalogEntry: catalog[group.signature] ?? null,
1151
+ scriptNames,
1152
+ });
748
1153
  } catch (error) {
749
1154
  // A malformed/inconsistent signal (e.g. signature↔stem mismatch) must be
750
1155
  // skipped + reported, never abort the whole loop (§5.2 robustness).
@@ -758,34 +1163,55 @@ export function runImprover(options = {}) {
758
1163
  rejected.push({ signature: decision.signature, reason: 'denylist' });
759
1164
  continue;
760
1165
  }
1166
+ if (decision.lesson === null) {
1167
+ skipped.push({ signature: decision.signature, reason: 'pending-lesson' });
1168
+ continue;
1169
+ }
761
1170
  decisions.push(decision);
762
1171
  }
763
1172
 
764
1173
  let applied = [];
765
1174
  let staged = [];
766
- let skipped = [];
1175
+ let applySkipped = [];
1176
+ let unloaded = [];
767
1177
  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,
773
- }));
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
- }
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 });
779
1193
  }
780
1194
 
1195
+ const allSkipped = [...skipped, ...applySkipped];
1196
+
781
1197
  return {
782
1198
  applied,
783
1199
  staged,
784
- skipped,
1200
+ skipped: allSkipped,
1201
+ unloaded,
785
1202
  rejected,
786
1203
  errors,
787
1204
  envelope,
788
- report: renderReport({ applied, staged, skipped, rejected, errors, envelope, ledgerPath }),
1205
+ report: renderReport({
1206
+ applied,
1207
+ staged,
1208
+ skipped: allSkipped,
1209
+ unloaded,
1210
+ rejected,
1211
+ errors,
1212
+ envelope,
1213
+ ledgerPath,
1214
+ }),
789
1215
  };
790
1216
  }
791
1217
 
@@ -798,7 +1224,13 @@ function renderTarget(target, ledgerPath) {
798
1224
  }
799
1225
  }
800
1226
 
801
- function renderReport({ applied, staged, skipped, rejected, errors, envelope, ledgerPath }) {
1227
+ function appendSkipGroup(lines, items, heading) {
1228
+ if (items.length === 0) return;
1229
+ lines.push('', heading);
1230
+ for (const item of items) lines.push(` - ${item.signature} (${item.reason})`);
1231
+ }
1232
+
1233
+ function renderReport({ applied, staged, skipped, rejected, unloaded = [], errors, envelope, ledgerPath }) {
802
1234
  const lines = [
803
1235
  'Self-learning rule improver',
804
1236
  `envelope: ${envelope.ruleCount}/${MAX_ACTIVE_RULES} rules, ${envelope.lineCount}/${MAX_TOTAL_LINES} lines`,
@@ -808,10 +1240,14 @@ function renderReport({ applied, staged, skipped, rejected, errors, envelope, le
808
1240
  for (const item of applied) lines.push(` - ${item.signature} → ${renderTarget(item.target, ledgerPath)}`);
809
1241
  lines.push('', `staged (${staged.length}) — human promote`);
810
1242
  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})`);
1243
+ if (unloaded.length > 0) {
1244
+ lines.push('', `unloaded (${unloaded.length}) — lesson removed`);
1245
+ for (const item of unloaded) lines.push(` - ${item.signature} → ${renderTarget(item.target, ledgerPath)}`);
814
1246
  }
1247
+ const pending = skipped.filter((item) => item.reason === 'pending-lesson');
1248
+ const deduped = skipped.filter((item) => item.reason !== 'pending-lesson');
1249
+ appendSkipGroup(lines, pending, `skipped (${pending.length}) — pending lesson`);
1250
+ appendSkipGroup(lines, deduped, `skipped (${deduped.length}) — dedup no-op`);
815
1251
  lines.push('', `rejected (${rejected.length}) — denylist`);
816
1252
  for (const item of rejected) lines.push(` - ${item.signature} (${item.reason})`);
817
1253
  if (errors.length > 0) {