@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
@@ -0,0 +1,665 @@
1
+ /**
2
+ * Template drift for a consumer's `.ai.local/` overlay: the tree-local base
3
+ * record, the pure four-outcome classifier, the opt-in merge, and the unified
4
+ * diff it diverts a consumer edit into.
5
+ *
6
+ * The invariant the whole module protects: a recorded base only ever describes
7
+ * a *template* byte. `fast-forward` therefore only replaces bytes the consumer
8
+ * has not changed since a template shipped them. A consumer file whose content
9
+ * differs from the current template is never recorded as its own base and never
10
+ * rewritten.
11
+ *
12
+ * Nothing here writes a consumer file on its own. The caller passes the install
13
+ * transaction as `writeFile`, so a fast-forward and the record land in the same
14
+ * rollback as the rest of `init`, and a refused destination is caught before
15
+ * anything is written.
16
+ */
17
+ const crypto = require('crypto');
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { assertSafeDest } = require('./safe-path');
21
+
22
+ const RECORD_REL = '.ai.local/.template-base.json';
23
+ const SINK_REL = '.ai.local/.rollback/template-drift';
24
+ const MERGE_FLAG = '--merge-ai-local';
25
+ const RECORD_SCHEMA_VERSION = 1;
26
+ /** Above this many line pairs the diff degrades to a whole-file hunk. */
27
+ const MAX_DIFF_CELLS = 4_000_000;
28
+
29
+ /**
30
+ * One `.ai.local/` rel as recorded in `.template-base.json`. The raw `sha256`
31
+ * reports byte-level drift; `normSha256` (line endings and trailing newlines
32
+ * normalised away) decides whether the consumer still holds the base bytes.
33
+ *
34
+ * @typedef {{ sha256: string, normSha256: string, source: string }} BaseEntry
35
+ */
36
+
37
+ /** @typedef {{ sha256: string, normSha256: string }} Digest */
38
+
39
+ function warn(message) {
40
+ console.warn(`Warning: ${message}`);
41
+ }
42
+
43
+ function errorMessage(error) {
44
+ return error instanceof Error ? error.message : String(error);
45
+ }
46
+
47
+ /** Strip CRLF and trailing newlines so EOL churn is not a consumer edit. */
48
+ function normaliseText(content) {
49
+ return String(content)
50
+ .replace(/\r\n?/g, '\n')
51
+ .replace(/\n+$/, '');
52
+ }
53
+
54
+ function hash(content) {
55
+ return crypto.createHash('sha256').update(content).digest('hex');
56
+ }
57
+
58
+ /** @returns {Digest} */
59
+ function digestContent(content) {
60
+ return { sha256: hash(content), normSha256: hash(normaliseText(content)) };
61
+ }
62
+
63
+ /** @returns {Digest | null} `null` when the path is absent or not a regular file. */
64
+ function digestFile(filePath) {
65
+ let stat;
66
+ try {
67
+ stat = fs.lstatSync(filePath);
68
+ } catch {
69
+ return null;
70
+ }
71
+ if (!stat.isFile()) {
72
+ return null;
73
+ }
74
+ return digestContent(fs.readFileSync(filePath));
75
+ }
76
+
77
+ /**
78
+ * The whole decision table, pure: no filesystem, process, or network access.
79
+ *
80
+ * `noop` — nothing to do: the consumer file is absent, the preset ships no
81
+ * entry for the rel, the recorded base belongs to another tool or preset, or
82
+ * the consumer already holds the current template under a current base.
83
+ * `adopt` — the consumer file equals the current template, but the record does
84
+ * not say so (no base yet, or a base from an older template the consumer already
85
+ * applied). Record the template bytes, write nothing.
86
+ * `fast-forward` — the consumer still holds the recorded base and the template
87
+ * moved, so the template bytes may replace it.
88
+ * `drift` — the consumer bytes match neither the current template nor the base:
89
+ * either the consumer changed the file, or the file predates the record and
90
+ * cannot be attributed. Keep it byte-identical and report it.
91
+ *
92
+ * Recording consumer bytes as a base is deliberately impossible: it would turn
93
+ * a pre-existing edit into "unchanged since the base", and the next template
94
+ * move would silently overwrite it.
95
+ *
96
+ * `source` stays part of the decision rather than becoming a label: per-tool
97
+ * template trees differ (`presets/claude/next/ai-local/conventions.md` ships
98
+ * fewer sections than `cursor/next`), so a foreign pass must not rewrite a rel
99
+ * another tool seeded. Every pass classifies, so the writing tool's own pass is
100
+ * the one that decides — a foreign source no longer disables the feature.
101
+ *
102
+ * @param {{ consumer?: Digest | null, base?: BaseEntry | null, template?: Digest | null, source: string }} input
103
+ * @returns {'noop' | 'adopt' | 'fast-forward' | 'drift'}
104
+ */
105
+ function decide({ consumer, base, template, source }) {
106
+ if (!consumer || !template) {
107
+ return 'noop';
108
+ }
109
+ if (base && base.source !== source) {
110
+ return 'noop';
111
+ }
112
+ if (consumer.normSha256 === template.normSha256) {
113
+ return base && base.normSha256 === template.normSha256 ? 'noop' : 'adopt';
114
+ }
115
+ if (!base) {
116
+ return 'drift';
117
+ }
118
+ if (consumer.normSha256 !== base.normSha256) {
119
+ return 'drift';
120
+ }
121
+ return 'fast-forward';
122
+ }
123
+
124
+ /**
125
+ * Read the record; a missing or malformed file reads as `null` (no base). The
126
+ * declared `schemaVersion` is preserved so a record written by a newer CLI is
127
+ * detected instead of silently rewritten as v1.
128
+ */
129
+ function readRecord(recordPath) {
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(fs.readFileSync(recordPath, 'utf8'));
133
+ } catch {
134
+ return null;
135
+ }
136
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
137
+ return null;
138
+ }
139
+ const files = parsed.files && typeof parsed.files === 'object' && !Array.isArray(parsed.files)
140
+ ? parsed.files
141
+ : {};
142
+ const out = {};
143
+ for (const rel of Object.keys(files)) {
144
+ const entry = files[rel];
145
+ if (!entry || typeof entry !== 'object') {
146
+ continue;
147
+ }
148
+ if (typeof entry.sha256 !== 'string' || typeof entry.normSha256 !== 'string') {
149
+ continue;
150
+ }
151
+ const source = typeof entry.source === 'string' ? entry.source : '';
152
+ out[rel] = { sha256: entry.sha256, normSha256: entry.normSha256, source };
153
+ }
154
+ return {
155
+ schemaVersion: typeof parsed.schemaVersion === 'number' ? parsed.schemaVersion : RECORD_SCHEMA_VERSION,
156
+ packageVersion: typeof parsed.packageVersion === 'string' ? parsed.packageVersion : '',
157
+ files: out,
158
+ };
159
+ }
160
+
161
+ function sortKeys(object) {
162
+ const out = {};
163
+ for (const key of Object.keys(object).sort()) {
164
+ out[key] = object[key];
165
+ }
166
+ return out;
167
+ }
168
+
169
+ /**
170
+ * Merge the rels the seed just wrote into the previous record. A rel the seed
171
+ * rewrote keeps its original `source`: attribution follows the first tool that
172
+ * wrote the file, so a second tool's run cannot re-source another preset's rel.
173
+ *
174
+ * @param {{ previous?: { files: Record<string, BaseEntry> } | null, packageVersion: string, source: string, written: Array<{ rel: string } & Digest> }} input
175
+ */
176
+ function buildRecord({ previous, packageVersion, source, written }) {
177
+ const files = {};
178
+ for (const rel of Object.keys((previous && previous.files) || {})) {
179
+ const entry = previous.files[rel];
180
+ files[rel] = { sha256: entry.sha256, normSha256: entry.normSha256, source: entry.source };
181
+ }
182
+ for (const item of written) {
183
+ const prior = files[item.rel];
184
+ files[item.rel] = {
185
+ sha256: item.sha256,
186
+ normSha256: item.normSha256,
187
+ source: prior ? prior.source : source,
188
+ };
189
+ }
190
+ return {
191
+ schemaVersion: RECORD_SCHEMA_VERSION,
192
+ packageVersion,
193
+ files: sortKeys(files),
194
+ };
195
+ }
196
+
197
+ /** Serialise deterministically: sorted keys, no timestamp, two-space JSON. */
198
+ function serialiseRecord(record) {
199
+ return `${JSON.stringify(
200
+ {
201
+ schemaVersion: record.schemaVersion,
202
+ packageVersion: record.packageVersion,
203
+ files: sortKeys(record.files),
204
+ },
205
+ null,
206
+ 2,
207
+ )}\n`;
208
+ }
209
+
210
+ /**
211
+ * Classify every rel the preset ships against the consumer tree and the record.
212
+ *
213
+ * @param {{ cwd: string, record: { files: Record<string, BaseEntry> } | null, templates: Map<string, { content: Buffer, digest: Digest }>, source: string }} input
214
+ */
215
+ function collectOutcomes({ cwd, record, templates, source }) {
216
+ const rows = [];
217
+ for (const rel of [...templates.keys()].sort()) {
218
+ const template = templates.get(rel).digest;
219
+ const base = (record && record.files[rel]) || null;
220
+ const consumer = digestFile(path.join(cwd, rel));
221
+ rows.push({ rel, outcome: decide({ consumer, base, template, source }), consumer, base, template });
222
+ }
223
+ return rows;
224
+ }
225
+
226
+ /** `/` → `__`; the result never ends in `.md`, so the overlay probe cannot load it. */
227
+ function sinkEntryName(rel) {
228
+ return rel.replace(/\//g, '__');
229
+ }
230
+
231
+ function splitLines(text) {
232
+ const normalised = normaliseText(text);
233
+ return normalised === '' ? [] : normalised.split('\n');
234
+ }
235
+
236
+ /** Longest-common-subsequence edit script over normalised lines. */
237
+ function diffOps(a, b) {
238
+ const rows = a.length;
239
+ const cols = b.length;
240
+ const table = Array.from({ length: rows + 1 }, () => new Uint32Array(cols + 1));
241
+ for (let i = rows - 1; i >= 0; i -= 1) {
242
+ for (let j = cols - 1; j >= 0; j -= 1) {
243
+ table[i][j] = a[i] === b[j]
244
+ ? table[i + 1][j + 1] + 1
245
+ : Math.max(table[i + 1][j], table[i][j + 1]);
246
+ }
247
+ }
248
+ const ops = [];
249
+ let i = 0;
250
+ let j = 0;
251
+ while (i < rows && j < cols) {
252
+ if (a[i] === b[j]) {
253
+ ops.push({ type: '=', text: a[i], aIndex: i, bIndex: j });
254
+ i += 1;
255
+ j += 1;
256
+ } else if (table[i + 1][j] >= table[i][j + 1]) {
257
+ ops.push({ type: '-', text: a[i], aIndex: i, bIndex: j });
258
+ i += 1;
259
+ } else {
260
+ ops.push({ type: '+', text: b[j], aIndex: i, bIndex: j });
261
+ j += 1;
262
+ }
263
+ }
264
+ while (i < rows) {
265
+ ops.push({ type: '-', text: a[i], aIndex: i, bIndex: j });
266
+ i += 1;
267
+ }
268
+ while (j < cols) {
269
+ ops.push({ type: '+', text: b[j], aIndex: i, bIndex: j });
270
+ j += 1;
271
+ }
272
+ return ops;
273
+ }
274
+
275
+ function hunkRanges(ops, context) {
276
+ const ranges = [];
277
+ ops.forEach((op, index) => {
278
+ if (op.type === '=') {
279
+ return;
280
+ }
281
+ const start = Math.max(0, index - context);
282
+ const end = Math.min(ops.length - 1, index + context);
283
+ const last = ranges[ranges.length - 1];
284
+ if (last && start <= last.end + 1) {
285
+ last.end = Math.max(last.end, end);
286
+ } else {
287
+ ranges.push({ start, end });
288
+ }
289
+ });
290
+ return ranges;
291
+ }
292
+
293
+ /**
294
+ * Render a unified diff from the consumer text (`a/`) to the template text
295
+ * (`b/`), over normalised lines so line-ending churn is not a conflict.
296
+ */
297
+ function unifiedDiff({ rel, from, to, context = 3 }) {
298
+ const a = splitLines(from);
299
+ const b = splitLines(to);
300
+ const header = `--- a/${rel}\n+++ b/${rel}\n`;
301
+ if (a.length * b.length > MAX_DIFF_CELLS) {
302
+ const removed = a.map((line) => `-${line}`).join('\n');
303
+ const added = b.map((line) => `+${line}`).join('\n');
304
+ const body = [removed, added].filter(Boolean).join('\n');
305
+ return `${header}@@ -${a.length === 0 ? 0 : 1},${a.length} +${b.length === 0 ? 0 : 1},${b.length} @@\n${body}\n`;
306
+ }
307
+ const ops = diffOps(a, b);
308
+ const ranges = hunkRanges(ops, context);
309
+ if (ranges.length === 0) {
310
+ return `${header}`;
311
+ }
312
+ const chunks = [];
313
+ for (const { start, end } of ranges) {
314
+ const slice = ops.slice(start, end + 1);
315
+ const oldCount = slice.filter((op) => op.type !== '+').length;
316
+ const newCount = slice.filter((op) => op.type !== '-').length;
317
+ const first = slice[0];
318
+ const oldStart = oldCount === 0 ? first.aIndex : first.aIndex + 1;
319
+ const newStart = newCount === 0 ? first.bIndex : first.bIndex + 1;
320
+ const body = slice
321
+ .map((op) => `${op.type === '=' ? ' ' : op.type}${op.text}`)
322
+ .join('\n');
323
+ chunks.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@\n${body}\n`);
324
+ }
325
+ return `${header}${chunks.join('')}`;
326
+ }
327
+
328
+ /** One tree-level line; printed once per tree, never once per tool. */
329
+ function summaryLine({ behind, edited }) {
330
+ return `.ai.local drift: ${behind} behind template, ${edited} edited locally `
331
+ + `(run with ${MERGE_FLAG} to fast-forward the untouched ones)`;
332
+ }
333
+
334
+ /** Under the flag the same summary reports what the merge actually did. */
335
+ function mergeSummaryLine({ fastForwarded, adopted, edited }) {
336
+ return `.ai.local drift: ${fastForwarded} fast-forwarded, ${adopted} adopted, `
337
+ + `${edited} kept edited locally`;
338
+ }
339
+
340
+ /**
341
+ * Drift counters for the tree a command is working on, keyed by resolved `cwd`.
342
+ * Every tool's pass adds its own outcomes, so the one line describes the whole
343
+ * tree; the command boundary flushes it once (`flushAiLocalDriftSummary`).
344
+ *
345
+ * `claimedRels` keeps one outcome per rel for the command. A shared rel with no
346
+ * base would otherwise be counted, and its proposal rewritten, by every tool.
347
+ */
348
+ const driftTotals = new Map();
349
+ const claimedRels = new Map();
350
+
351
+ /**
352
+ * @returns {'count' | 'upgrade-adopt' | 'skip'}
353
+ * `upgrade-adopt` — an earlier pass called the rel drift, and this pass's
354
+ * template already matches the file. The earlier count is reversed and the
355
+ * earlier proposal is dropped.
356
+ */
357
+ function claimRel(cwd, rel, outcome) {
358
+ const key = path.resolve(cwd);
359
+ const claims = claimedRels.get(key) || new Map();
360
+ claimedRels.set(key, claims);
361
+ const prior = claims.get(rel);
362
+ if (!prior) {
363
+ claims.set(rel, outcome);
364
+ return 'count';
365
+ }
366
+ if (prior === 'drift' && outcome === 'adopt') {
367
+ claims.set(rel, 'adopt');
368
+ return 'upgrade-adopt';
369
+ }
370
+ return 'skip';
371
+ }
372
+
373
+ /** Rows this pass may count or write. A rel already claimed by an earlier pass is skipped. */
374
+ function actionableOutcomes(cwd, outcomes) {
375
+ const rows = [];
376
+ let adoptUpgrades = 0;
377
+ for (const row of outcomes) {
378
+ if (row.outcome === 'noop') continue;
379
+ const claim = claimRel(cwd, row.rel, row.outcome);
380
+ if (claim === 'skip') continue;
381
+ if (claim === 'upgrade-adopt') adoptUpgrades += 1;
382
+ rows.push(row);
383
+ }
384
+ return { rows, adoptUpgrades };
385
+ }
386
+
387
+ /**
388
+ * Drop the proposals this pass owns before rewriting them. The deletion is tracked
389
+ * by the install transaction (`trackFile`), so a flagged run that fails afterwards
390
+ * restores the previous proposals instead of leaving a half-cleared sink.
391
+ *
392
+ * @param {string[]} rels the rels this pass classifies or drops
393
+ * @param {((dest: string, label: string) => void) | undefined} trackFile
394
+ */
395
+ function clearSink(cwd, rels, trackFile) {
396
+ for (const rel of rels) {
397
+ const name = sinkEntryName(rel);
398
+ for (const suffix of ['.diff', '.template-new']) {
399
+ const dest = path.join(cwd, SINK_REL, `${name}${suffix}`);
400
+ if (!fs.existsSync(dest)) continue;
401
+ if (trackFile) trackFile(dest, path.join(SINK_REL, `${name}${suffix}`));
402
+ fs.rmSync(dest, { force: true });
403
+ }
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Record every rel that already holds the current template. Runs on every pass,
409
+ * with or without the flag: the record is a tool artifact, and leaving a base
410
+ * from an older template in place would report an applied proposal as an edit
411
+ * forever.
412
+ */
413
+ function adoptOutcomes({ record, outcomes, source }) {
414
+ for (const row of outcomes) {
415
+ if (row.outcome !== 'adopt') continue;
416
+ record.files[row.rel] = {
417
+ sha256: row.template.sha256,
418
+ normSha256: row.template.normSha256,
419
+ source,
420
+ };
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Record entries this pass owns whose rel the preset no longer ships. Only the
426
+ * writing tool may drop its own entry: another tool's template map is unknowable
427
+ * from here, and a stale entry would re-attribute a re-added rel to the wrong
428
+ * bytes.
429
+ */
430
+ function droppedRels({ record, templates, source }) {
431
+ return Object.keys(record.files)
432
+ .filter((rel) => record.files[rel].source === source && !templates.has(rel))
433
+ .sort();
434
+ }
435
+
436
+ /**
437
+ * Apply `--merge-ai-local` to one tree: fast-forward the rels whose base still
438
+ * matches, report the rels already at the template, and divert a consumer edit
439
+ * into the sink. A consumer file is never overwritten in the `drift` case, and
440
+ * no conflict marker is ever written. One rel's failure is a warning; it does
441
+ * not hide the work the other rels did.
442
+ */
443
+ function mergeOutcomes({ cwd, record, outcomes, templates, source, writeFile, trackFile }) {
444
+ const counts = { fastForwarded: 0, adopted: 0, drifted: 0 };
445
+ // Only the rels this pass owns: another tool's proposal must survive the pass that
446
+ // cannot re-derive it, and a rel whose base names a foreign source is not ours.
447
+ const owned = outcomes
448
+ .filter((row) => !row.base || row.base.source === source)
449
+ .map((row) => row.rel);
450
+ clearSink(cwd, owned, trackFile);
451
+ for (const row of outcomes) {
452
+ try {
453
+ if (row.outcome === 'adopt') {
454
+ counts.adopted += 1;
455
+ console.log(`merge-ai-local: adopt ${row.rel} (recorded; file untouched)`);
456
+ continue;
457
+ }
458
+ if (row.outcome === 'fast-forward') {
459
+ const template = templates.get(row.rel);
460
+ writeFile(path.join(cwd, row.rel), template.content, row.rel);
461
+ record.files[row.rel] = {
462
+ sha256: template.digest.sha256,
463
+ normSha256: template.digest.normSha256,
464
+ source,
465
+ };
466
+ counts.fastForwarded += 1;
467
+ console.log(`merge-ai-local: fast-forward ${row.rel}`);
468
+ continue;
469
+ }
470
+ if (row.outcome !== 'drift') {
471
+ continue;
472
+ }
473
+ const template = templates.get(row.rel);
474
+ const name = sinkEntryName(row.rel);
475
+ const diffRel = `${SINK_REL}/${name}.diff`;
476
+ const templateRel = `${SINK_REL}/${name}.template-new`;
477
+ writeFile(
478
+ path.join(cwd, diffRel),
479
+ unifiedDiff({ rel: row.rel, from: fs.readFileSync(path.join(cwd, row.rel)), to: template.content }),
480
+ diffRel,
481
+ );
482
+ writeFile(path.join(cwd, templateRel), template.content, templateRel);
483
+ counts.drifted += 1;
484
+ console.log(`merge-ai-local: drift ${row.rel} → ${diffRel}`);
485
+ } catch (error) {
486
+ warn(`${errorMessage(error)}; skipped .ai.local merge for ${row.rel}`);
487
+ }
488
+ }
489
+ return counts;
490
+ }
491
+
492
+ /**
493
+ * Add one pass's counts to the tree's running totals. The per-file `merge-ai-local:`
494
+ * lines print immediately; only the summary waits for the command boundary.
495
+ */
496
+ function accumulateDrift(cwd, { behind, edited, counts }) {
497
+ const key = path.resolve(cwd);
498
+ const totals = driftTotals.get(key) || {
499
+ behind: 0,
500
+ edited: 0,
501
+ fastForwarded: 0,
502
+ adopted: 0,
503
+ keptEdited: 0,
504
+ merged: false,
505
+ };
506
+ totals.behind += behind;
507
+ totals.edited += edited;
508
+ if (counts) {
509
+ totals.merged = true;
510
+ totals.fastForwarded += counts.fastForwarded;
511
+ totals.adopted += counts.adopted;
512
+ totals.keptEdited += counts.drifted;
513
+ }
514
+ driftTotals.set(key, totals);
515
+ }
516
+
517
+ /**
518
+ * Print one summary line for the tree, from the totals every tool's pass
519
+ * accumulated, then clear them. Called by the command boundary (`update`, `init`,
520
+ * `init multi`) after its last pass, never from inside a pass — a per-pass print
521
+ * reported only the first pass's rels on a tree written by more than one tool.
522
+ *
523
+ * @param {string} cwd resolved target directory
524
+ */
525
+ function flushAiLocalDriftSummary(cwd) {
526
+ const key = path.resolve(cwd);
527
+ const totals = driftTotals.get(key);
528
+ driftTotals.delete(key);
529
+ claimedRels.delete(key);
530
+ if (!totals) {
531
+ return;
532
+ }
533
+ if (totals.merged) {
534
+ if (totals.fastForwarded + totals.adopted + totals.keptEdited > 0) {
535
+ console.log(
536
+ mergeSummaryLine({
537
+ fastForwarded: totals.fastForwarded,
538
+ adopted: totals.adopted,
539
+ edited: totals.keptEdited,
540
+ }),
541
+ );
542
+ }
543
+ return;
544
+ }
545
+ if (totals.behind + totals.edited > 0) {
546
+ console.log(summaryLine({ behind: totals.behind, edited: totals.edited }));
547
+ }
548
+ }
549
+
550
+ /**
551
+ * Safety net for a pass that exits the process before the command boundary
552
+ * (`cmdInit` calls `process.exit` on failure). A successful command has already
553
+ * flushed and this prints nothing.
554
+ */
555
+ function flushAllAiLocalDriftSummaries() {
556
+ for (const key of [...driftTotals.keys()]) {
557
+ flushAiLocalDriftSummary(key);
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Phase A + B of the accepted design: record the rels this seed wrote, record
563
+ * every rel that already holds the current template, classify every rel of this
564
+ * tool's template map, run the opt-in merge, and feed the tree's drift totals.
565
+ *
566
+ * The pass runs for every installed tool, against that tool's own template map and its
567
+ * own `source`. Each rel is counted once per command: the first pass reports it, and a
568
+ * later pass does not add it or replace its proposal. A later pass whose template
569
+ * already matches the file adopts it and drops that proposal. Files two tools own
570
+ * separately still both appear in the one tree-level line.
571
+ *
572
+ * A refused destination (symlink or escape) warns and skips the record/merge; it
573
+ * never fails the install and never enters the `update` error channel. The
574
+ * record write goes through the caller's transaction writer, so a later failure
575
+ * removes it again.
576
+ */
577
+ function runTemplateDrift({ cwd, written, templates, source, packageVersion, mergeAiLocal, writeFile, trackFile }) {
578
+ if (!writeFile || !source || !templates) {
579
+ return;
580
+ }
581
+ const templateMap = new Map();
582
+ for (const [rel, content] of templates) {
583
+ templateMap.set(rel, { content, digest: digestContent(content) });
584
+ }
585
+ const recordPath = path.join(cwd, RECORD_REL);
586
+ try {
587
+ assertSafeDest(cwd, recordPath, RECORD_REL);
588
+ } catch (error) {
589
+ warn(`${errorMessage(error)}; skipped .ai.local template record and merge`);
590
+ return;
591
+ }
592
+
593
+ const previous = readRecord(recordPath);
594
+ if (previous && previous.schemaVersion > RECORD_SCHEMA_VERSION) {
595
+ warn(
596
+ `${RECORD_REL} declares schemaVersion ${previous.schemaVersion}, newer than this CLI `
597
+ + `(${RECORD_SCHEMA_VERSION}); skipped .ai.local template record and merge`,
598
+ );
599
+ return;
600
+ }
601
+
602
+ const seedWritten = [];
603
+ for (const rel of written) {
604
+ if (!templateMap.has(rel)) continue;
605
+ const digest = digestFile(path.join(cwd, rel));
606
+ if (digest) seedWritten.push({ rel, ...digest });
607
+ }
608
+ const record = buildRecord({ previous, packageVersion, source, written: seedWritten });
609
+
610
+ const outcomes = collectOutcomes({ cwd, record, templates: templateMap, source });
611
+ // One rel, one count, one proposal. A later pass adopts the rel when its
612
+ // template already matches, and does not add the file again.
613
+ const { rows: actionable, adoptUpgrades } = actionableOutcomes(cwd, outcomes);
614
+ adoptOutcomes({ record, outcomes: actionable, source });
615
+ const behind = actionable.filter((row) => row.outcome === 'fast-forward').length;
616
+ const edited = actionable.filter((row) => row.outcome === 'drift').length - adoptUpgrades;
617
+
618
+ let counts = null;
619
+ if (mergeAiLocal) {
620
+ const dropped = droppedRels({ record, templates: templateMap, source });
621
+ for (const rel of dropped) {
622
+ delete record.files[rel];
623
+ }
624
+ try {
625
+ assertSafeDest(cwd, path.join(cwd, SINK_REL), SINK_REL);
626
+ clearSink(cwd, dropped, trackFile);
627
+ counts = mergeOutcomes({
628
+ cwd, record, outcomes: actionable, templates: templateMap, source, writeFile, trackFile,
629
+ });
630
+ counts.drifted -= adoptUpgrades;
631
+ } catch (error) {
632
+ warn(`${errorMessage(error)}; skipped .ai.local merge`);
633
+ }
634
+ }
635
+
636
+ accumulateDrift(cwd, { behind, edited, counts });
637
+
638
+ try {
639
+ writeFile(recordPath, serialiseRecord(record), RECORD_REL);
640
+ } catch (error) {
641
+ warn(`${errorMessage(error)}; skipped .ai.local template record`);
642
+ }
643
+ }
644
+
645
+ module.exports = {
646
+ RECORD_REL,
647
+ RECORD_SCHEMA_VERSION,
648
+ SINK_REL,
649
+ MERGE_FLAG,
650
+ normaliseText,
651
+ digestContent,
652
+ digestFile,
653
+ decide,
654
+ readRecord,
655
+ buildRecord,
656
+ serialiseRecord,
657
+ collectOutcomes,
658
+ sinkEntryName,
659
+ unifiedDiff,
660
+ summaryLine,
661
+ mergeSummaryLine,
662
+ runTemplateDrift,
663
+ flushAiLocalDriftSummary,
664
+ flushAllAiLocalDriftSummaries,
665
+ };