@skillstech/thunderlang 0.5.11 → 0.5.12

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 (66) hide show
  1. package/CHANGELOG.md +437 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
package/src/review.mjs ADDED
@@ -0,0 +1,671 @@
1
+ // thunder review: what a change did to the MEANING of the code, in plain sentences, so a pull request can be reviewed
2
+ // without reading the code diff. Both versions are read into the Thunder model (model.mjs); each action, rule, and
3
+ // function is paired with its other version (by file and name, then by name, then by meaning), and the facts a
4
+ // reviewer checks are compared: the ways it stops and when, what it gives back, what it takes, what it changes or
5
+ // sends, what it relies on, and, for rules, their answers (by running both on every edge case, as `thunder same`).
6
+ //
7
+ // Honest by design: "same" or "only the form changed" is said only when it is shown: the code is identical apart
8
+ // from spacing and comments, or only local names changed, or a rule gives the same answer on every edge case. When
9
+ // Thunder's words read the same but the code differs, that is said too ("changed, check"), because Thunder's words
10
+ // leave some details out. Pure and browser-safe: takes [{ path, source }] for each side; the CLI does the git work.
11
+ import { thunderModel, readLevel, modelText } from './model.mjs';
12
+ import { comparePlainRules, nameKey } from './same.mjs';
13
+ import { readableLanguage } from './read-repo.mjs';
14
+
15
+ export const REVIEW_SCHEMA = 'thunder-review-v1';
16
+ export const REVIEW_MARKER = '<!-- thunder-review -->';
17
+
18
+ const SEVERITY_ORDER = ['risk', 'meaning', 'form'];
19
+ // Within a severity, what a reviewer should read first.
20
+ const KIND_ORDER = ['unreadable', 'not-read', 'infrastructure', 'stop-removed', 'stop-changed', 'address', 'effect-added', 'stop-added',
21
+ 'rule-limit', 'rule-answer', 'rule-new-answer', 'rule-removed-answer', 'rule-facts', 'input-added', 'input-removed',
22
+ 'gives-back-added', 'gives-back-removed', 'gives-back-changed', 'effect-removed', 'effect-changed', 'relies-on', 'hidden',
23
+ 'steps', 'outside', 'added', 'removed', 'thing', 'renamed', 'moved', 'form'];
24
+
25
+ const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
26
+ const cap = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
27
+ const lc = (s) => (s && !/^[A-Z]{2}|^[A-Z]\w*[A-Z_]/.test(s) ? s.charAt(0).toLowerCase() + s.slice(1) : s);
28
+ const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : cap(words(r)));
29
+ const stemKey = (path) => nameKey(String(path).replace(/\.[^./]+$/, '').replace(/\\/g, '/'));
30
+ const KIND_WORD = { action: 'action', rule: 'rule', steps: 'function', setup: 'setup', 'not-read': 'function' };
31
+
32
+ // ── Tokens: the code without spacing and comments, so "only the form changed" can be shown, not guessed ──────────
33
+
34
+ const HASH_COMMENTS = new Set(['python', 'ruby', 'php']);
35
+ const SLASH_COMMENTS = new Set(['typescript', 'javascript', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php']);
36
+ const DECLARE = new Set(['const', 'let', 'var', 'val', 'def', 'fn', 'func', 'function', 'auto', 'my', 'local', 'for', 'as']);
37
+
38
+ /** The code as tokens ({ t, k }: k is id, str, num, op, nl, indent, dedent). Spacing and comments are not tokens. */
39
+ export function codeTokens(src, language) {
40
+ const out = [];
41
+ const s = String(src ?? '');
42
+ const py = language === 'python';
43
+ const stack = [0];
44
+ let depth = 0, lineStart = true;
45
+ const push = (t, k) => out.push({ t, k });
46
+ const nl = () => { if (out.length && out.at(-1).k !== 'nl' && out.at(-1).k !== 'indent' && out.at(-1).k !== 'dedent') push('\n', 'nl'); };
47
+ for (let i = 0; i < s.length;) {
48
+ const c = s[i];
49
+ if (lineStart && py && depth === 0) {
50
+ // Python: indentation is meaning, so it is kept as indent / dedent tokens (blank and comment lines skipped).
51
+ let j = i, w = 0;
52
+ while (s[j] === ' ' || s[j] === '\t') { w += s[j] === '\t' ? 8 : 1; j++; }
53
+ if (s[j] !== '\n' && s[j] !== '\r' && s[j] !== '#' && j < s.length) {
54
+ if (w > stack.at(-1)) { stack.push(w); push('', 'indent'); }
55
+ while (w < stack.at(-1)) { stack.pop(); push('', 'dedent'); }
56
+ }
57
+ lineStart = false; i = j; continue;
58
+ }
59
+ if (c === '\n') { if (depth === 0) nl(); lineStart = true; i++; continue; }
60
+ if (/\s/.test(c)) { i++; continue; }
61
+ if (SLASH_COMMENTS.has(language) && c === '/' && s[i + 1] === '/') { while (i < s.length && s[i] !== '\n') i++; continue; }
62
+ if (SLASH_COMMENTS.has(language) && c === '/' && s[i + 1] === '*') { const e = s.indexOf('*/', i + 2); i = e < 0 ? s.length : e + 2; continue; }
63
+ if (HASH_COMMENTS.has(language) && c === '#' && !(language === 'php' && s[i + 1] === '[')) { while (i < s.length && s[i] !== '\n') i++; continue; }
64
+ if (language === 'sql' && c === '-' && s[i + 1] === '-') { while (i < s.length && s[i] !== '\n') i++; continue; }
65
+ if (language === 'sql' && c === '/' && s[i + 1] === '*') { const e = s.indexOf('*/', i + 2); i = e < 0 ? s.length : e + 2; continue; }
66
+ if (c === '"' || c === "'" || c === '`') {
67
+ const triple = py && s.slice(i, i + 3) === c.repeat(3);
68
+ const q = triple ? c.repeat(3) : c;
69
+ let j = i + q.length;
70
+ while (j < s.length && s.slice(j, j + q.length) !== q) j += s[j] === '\\' ? 2 : 1;
71
+ push(s.slice(i, j + q.length), 'str'); i = j + q.length; continue;
72
+ }
73
+ const num = s.slice(i).match(/^\d[\w.]*/);
74
+ if (num) { push(num[0], 'num'); i += num[0].length; continue; }
75
+ const id = s.slice(i).match(/^[A-Za-z_$@][\w$]*/);
76
+ if (id) { push(id[0], 'id'); i += id[0].length; continue; }
77
+ if ('([{'.includes(c)) depth++;
78
+ else if (')]}'.includes(c)) depth = Math.max(0, depth - 1);
79
+ push(c, 'op'); i++;
80
+ }
81
+ nl();
82
+ // A Python string standing alone on its line is a docstring: a note for people, not something the code does.
83
+ if (py) return out.filter((tk, i) => !(tk.k === 'str' && (i === 0 || ['nl', 'indent', 'dedent'].includes(out[i - 1].k)) && (!out[i + 1] || out[i + 1].k === 'nl')));
84
+ return out;
85
+ }
86
+
87
+ const sameTokens = (a, b) => a.length === b.length && a.every((x, i) => x.t === b[i].t);
88
+
89
+ /**
90
+ * Two token lists that differ only by a consistent renaming of names the code itself declares (inputs, local
91
+ * values): [[old, new], …], or null when anything else differs. A renamed name that is also a field, a key, or a
92
+ * named argument is not accepted, because renaming those changes what the code does.
93
+ */
94
+ export function localRenames(a, b, language, allowed = []) {
95
+ if (a.length !== b.length) return null;
96
+ const fwd = new Map(), back = new Map();
97
+ for (let i = 0; i < a.length; i++) {
98
+ if (a[i].t === b[i].t) { if (a[i].k === 'id' && (fwd.has(a[i].t) || back.has(b[i].t)) && fwd.get(a[i].t) !== b[i].t) return null; continue; }
99
+ if (a[i].k !== 'id' || b[i].k !== 'id') return null;
100
+ if ((fwd.has(a[i].t) && fwd.get(a[i].t) !== b[i].t) || (back.has(b[i].t) && back.get(b[i].t) !== a[i].t)) return null;
101
+ fwd.set(a[i].t, b[i].t); back.set(b[i].t, a[i].t);
102
+ }
103
+ // A name kept as-is somewhere and renamed elsewhere is not a consistent rename.
104
+ for (let i = 0; i < a.length; i++) if (a[i].k === 'id' && a[i].t === b[i].t && fwd.has(a[i].t) && fwd.get(a[i].t) !== a[i].t) return null;
105
+ const firstNl = a.findIndex((x) => x.k === 'nl');
106
+ const head = firstNl < 0 ? a.length : firstNl;
107
+ const js = language === 'typescript' || language === 'javascript';
108
+ const localAssign = (language === 'python' || language === 'ruby') && !a.some((x) => x.t === 'global' || x.t === 'nonlocal' || x.t === '$');
109
+ for (const name of fwd.keys()) {
110
+ if (allowed.includes(name)) continue;
111
+ let declared = false;
112
+ for (let i = 0; i < a.length; i++) {
113
+ if (a[i].t !== name || a[i].k !== 'id') continue;
114
+ const prev = a[i - 1]?.t, next = a[i + 1]?.t;
115
+ if (prev === '.' || prev === '->' || prev === ':' && a[i - 2]?.t === ':') return null; // a field or a path
116
+ if (i >= head && next === ':' && language !== 'python' && language !== 'go') return null; // an object key
117
+ if (i >= head && next === '=' && a[i + 2]?.t !== '=' && (prev === '(' || prev === ',') && language === 'python') return null; // a named argument
118
+ if (js && (prev === '{' || prev === ',') && (next === '}' || next === ',') && i >= head) return null; // { name } shorthand
119
+ if (DECLARE.has(prev) || (i < head && (prev === '(' || prev === ',' || prev === '*'))) declared = true;
120
+ // Python and Ruby: a name assigned at the start of a statement is local to the function (unless declared global).
121
+ if (localAssign && (i === 0 || ['nl', 'indent', 'dedent'].includes(a[i - 1].k)) && next === '=' && a[i + 2]?.t !== '=') declared = true;
122
+ }
123
+ if (!declared) return null;
124
+ }
125
+ return [...fwd.entries()];
126
+ }
127
+
128
+ // ── Lines: before and after, only where they differ ──────────────────────────────────────────────────────────
129
+
130
+ /** The lines that changed, with one line of context above each change: { before: [...], after: [...] }. */
131
+ export function lineChanges(oldLines, newLines, max = 1500) {
132
+ // Lines the same at the start and the end are not compared (one line of context is kept above the change).
133
+ let p = 0;
134
+ while (p < oldLines.length && p < newLines.length && oldLines[p] === newLines[p]) p++;
135
+ let q = 0;
136
+ while (q < oldLines.length - p && q < newLines.length - p && oldLines[oldLines.length - 1 - q] === newLines[newLines.length - 1 - q]) q++;
137
+ const from = Math.max(0, p - 1);
138
+ const a = oldLines.slice(from, oldLines.length - q).slice(0, max), b = newLines.slice(from, newLines.length - q).slice(0, max);
139
+ const n = a.length, m = b.length;
140
+ const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
141
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
142
+ const keepA = new Array(n).fill(false), keepB = new Array(m).fill(false);
143
+ for (let i = 0, j = 0; i < n && j < m;) {
144
+ if (a[i] === b[j]) { keepA[i] = keepB[j] = true; i++; j++; } else if (L[i + 1][j] >= L[i][j + 1]) i++; else j++;
145
+ }
146
+ const pick = (lines, keep) => {
147
+ const out = [];
148
+ lines.forEach((l, i) => {
149
+ if (keep[i]) return;
150
+ if (i > 0 && keep[i - 1] && !out.includes(` ${lines[i - 1]}`) && lines[i - 1].trim()) out.push(` ${lines[i - 1]}`);
151
+ out.push(`> ${l}`);
152
+ });
153
+ return out;
154
+ };
155
+ return { before: pick(a, keepA), after: pick(b, keepB) };
156
+ }
157
+
158
+ /**
159
+ * Where a function's body ends, from the code itself: the matching close brace, or (Python) the last line indented
160
+ * under it. Null when it cannot tell. The model's own range can stop early; the review must see the whole body.
161
+ */
162
+ function bodyEnd(lines, start, language) {
163
+ if (language === 'python') {
164
+ const indent = (l) => l.match(/^[ \t]*/)[0].length;
165
+ let i = start - 1;
166
+ // The header may span lines: it ends at the line ending with ':' outside brackets.
167
+ let depth = 0;
168
+ for (; i < lines.length; i++) {
169
+ for (const c of lines[i].replace(/#.*$/, '')) depth += '([{'.includes(c) ? 1 : ')]}'.includes(c) ? -1 : 0;
170
+ if (depth <= 0 && /:\s*(#.*)?$/.test(lines[i])) break;
171
+ }
172
+ const base = indent(lines[start - 1]);
173
+ let last = i + 1;
174
+ for (let j = i + 1; j < lines.length; j++) {
175
+ if (!lines[j].trim()) continue;
176
+ if (indent(lines[j]) <= base) break;
177
+ last = j + 1;
178
+ }
179
+ return last;
180
+ }
181
+ if (language === 'ruby' || language === 'sql') return null;
182
+ const text = lines.slice(start - 1).join('\n');
183
+ const toks = codeTokens(text, language);
184
+ // Count lines as we go: tokens do not carry lines, so walk the text and the brace depth together.
185
+ let depth = 0, line = start, opened = false, q = null;
186
+ for (let i = 0; i < text.length; i++) {
187
+ const c = text[i];
188
+ if (c === '\n') { line++; continue; }
189
+ if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
190
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
191
+ if (c === '/' && text[i + 1] === '/') { while (i < text.length && text[i + 1] !== '\n') i++; continue; }
192
+ if (c === '/' && text[i + 1] === '*') { const e = text.indexOf('*/', i + 2); if (e < 0) return null; line += text.slice(i, e).split('\n').length - 1; i = e + 1; continue; }
193
+ if (c === '{') { depth++; opened = true; } else if (c === '}') { depth--; if (opened && depth === 0) return line; }
194
+ if (!opened && c === ';' && depth === 0) return line; // a declaration with no body
195
+ }
196
+ return toks.length ? null : null;
197
+ }
198
+
199
+ // ── Reading one side ─────────────────────────────────────────────────────────────────────────────────────────
200
+
201
+ const stripLine = (l) => l.replace(/ {2}\(line \d+\)$/, '').replace(/\s+$/, '');
202
+
203
+ function side(files) {
204
+ // Infrastructure and pipeline files are read by thunderModel now, but review does not compare Resources yet: they
205
+ // stay a risk for a person to check (below), never a change described in words.
206
+ const model = thunderModel(files.filter((f) => readableLanguage(f.path) && !isInfra(f.path)));
207
+ const sources = new Map(files.map((f) => [f.path, String(f.source ?? '')]));
208
+ const thingName = new Map(model.things.map((t) => [t.id, t.name]));
209
+ const members = [], byKey = new Map(), seen = new Map();
210
+ for (const m of model.members) {
211
+ const base = `${stemKey(m.file)}#${nameKey(thingName.get(m.owner) ?? '')}#${nameKey(m.name)}`;
212
+ const nth = (seen.get(base) || 0) + 1; seen.set(base, nth);
213
+ const key = nth > 1 ? `${base}#${nth}` : base;
214
+ let text;
215
+ try { text = modelText(model, m.id).split('\n').filter((l) => l.trim() && !/^\s*Author's note:/.test(l)).map(stripLine); } catch { text = [m.label]; }
216
+ const all = (sources.get(m.file) ?? '').split('\n');
217
+ const end = Math.max(m.lines[1], bodyEnd(all, m.lines[0], m.language) ?? 0);
218
+ m.reviewLines = [m.lines[0], end];
219
+ const lines = all.slice(m.lines[0] - 1, end);
220
+ const entry = { key, m, model, text, sig: text.slice(1).join('\n'), code: lines, tokens: codeTokens(lines.join('\n'), m.language) };
221
+ members.push(entry); byKey.set(key, entry);
222
+ }
223
+ return { model, sources, members, byKey };
224
+ }
225
+
226
+ let detailsCache = new WeakMap();
227
+ const details = (e) => {
228
+ if (!detailsCache.has(e)) { let d; try { d = readLevel(e.model, 'details', e.m.id); } catch { d = {}; } detailsCache.set(e, d); }
229
+ return detailsCache.get(e);
230
+ };
231
+
232
+ // ── Sentences ────────────────────────────────────────────────────────────────────────────────────────────────
233
+
234
+ function whenPart(w) {
235
+ if (w.says) return w.says;
236
+ const q = String(w.question).replace(/\?$/, '');
237
+ if ((w.answer === 'Yes' || w.answer === 'No') && /\?$/.test(w.question)) return `the answer to "${w.question}" is ${w.answer.toLowerCase()}`;
238
+ if (w.answer === 'Yes') return lc(q.replace(/^If /, ''));
239
+ if (w.answer === 'For each') return lc(q);
240
+ return `${lc(q)}: ${lc(w.answer)}`;
241
+ }
242
+ const whenText = (when, skip = new Set()) => {
243
+ const parts = (when || []).filter((w) => !skip.has(w.question)).map(whenPart);
244
+ return parts.length ? ` when ${parts.join(' and ')}` : '';
245
+ };
246
+ const stopName = (s) => `${s.error}${s.message ? ` ("${s.message}")` : ''}`;
247
+ const whenLines = (when) => (when || []).map((w) => `${w.question} ${w.answer}`);
248
+
249
+ function item(kind, severity, subject, where, says, evidence) {
250
+ return { kind, severity, subject, where, says, ...(evidence ? { evidence } : {}) };
251
+ }
252
+ const whereOf = (e, line) => ({ file: e.m.file, line: line ?? e.m.lines[0] });
253
+ const subjectOf = (e) => (e.m.route ? e.m.route : `${e.m.label}${e.m.yesNo ? '?' : ''}`);
254
+
255
+ /** Pair two lists by a key, keeping order: [[a, b]] with a or b missing when it has no partner. */
256
+ function pairBy(as, bs, key) {
257
+ const left = new Map();
258
+ for (const a of as) { const k = key(a); if (!left.has(k)) left.set(k, []); left.get(k).push(a); }
259
+ const out = [];
260
+ for (const b of bs) { const list = left.get(key(b)); out.push([list?.length ? list.shift() : undefined, b]); }
261
+ for (const list of left.values()) for (const a of list) out.push([a, undefined]);
262
+ return out;
263
+ }
264
+
265
+ // ── Comparing one member with its other version ──────────────────────────────────────────────────────────────
266
+
267
+ /** A rule's answer for one value of its one number fact, read from its limits. */
268
+ const rangeAnswer = (lim, v) => lim.ranges.find((x) => (x.from == null || v >= x.from) && (x.to == null || v <= x.to))?.answer;
269
+
270
+ function ruleChanges(o, n, r, items) {
271
+ const subject = subjectOf(n);
272
+ const label = n.m.label + (n.m.yesNo ? '?' : '');
273
+ const dO = details(o), dN = details(n);
274
+ const ansLines = (d) => (d.answers || []).map((a) => `${a.answer}${a.when === 'otherwise' ? ' otherwise' : ` when ${a.when}`}`);
275
+ const evidence = { before: ansLines(dO), after: ansLines(dN) };
276
+ if (r.counterexample) {
277
+ const ins = o.m.rule.inputs;
278
+ const facts = ins.map((i) => { const v = r.counterexample.values[i.id]; return i.kind === 'yesno' ? (v ? i.yes ?? `${i.label} is yes` : i.no ?? `${i.label} is no`) : `${i.label.replace(/^the /, '')} is ${v}`; }).join(' and ');
279
+ evidence.counterexample = { facts, before: answerWords(r.counterexample.old), after: answerWords(r.counterexample.new), values: r.counterexample.values };
280
+ }
281
+ let said = false;
282
+ // Limits: the same answers in the same order, with a boundary that moved.
283
+ if (dO.limits && dN.limits && dO.limits.fact === dN.limits.fact) {
284
+ // A whole-number example reads better than an edge value such as 7.01: the first whole number where they differ.
285
+ const all = [...dO.limits.ranges, ...dN.limits.ranges].flatMap((x) => [x.from, x.to]).filter((x) => x != null);
286
+ for (let v = Math.min(...all) - 1; v <= Math.max(...all) + 1; v++) {
287
+ const x = rangeAnswer(dO.limits, v), y = rangeAnswer(dN.limits, v);
288
+ if (x !== y) { evidence.counterexample = { facts: `${dN.limits.fact} is ${v}`, before: x, after: y, values: { [n.m.rule.inputs[0].id]: v } }; break; }
289
+ }
290
+ const bounds = (lim) => lim.ranges.slice(0, -1).map((x, i) => ({ pair: `${x.answer}→${lim.ranges[i + 1].answer}`, at: x.to, left: x.answer, right: lim.ranges[i + 1].answer }));
291
+ for (const [a, b] of pairBy(bounds(dO.limits), bounds(dN.limits), (x) => x.pair)) {
292
+ if (a && b && a.at !== b.at) {
293
+ items.push(item('rule-limit', 'meaning', subject, whereOf(n), `${label}: the limit between ${a.left} and ${a.right} moved from ${a.at} to ${b.at} ${dN.limits.fact}: ${a.left} now goes up to ${b.at} (was ${a.at}).`, evidence));
294
+ said = true;
295
+ }
296
+ }
297
+ }
298
+ const before = new Set((dO.answers || []).map((a) => a.answer)), after = new Set((dN.answers || []).map((a) => a.answer));
299
+ for (const a of after) if (!before.has(a)) { items.push(item('rule-new-answer', 'meaning', subject, whereOf(n), `${label}: can now answer ${a}.`, evidence)); said = true; }
300
+ for (const a of before) if (!after.has(a)) { items.push(item('rule-removed-answer', 'meaning', subject, whereOf(n), `${label}: no longer answers ${a}.`, evidence)); said = true; }
301
+ if (!said && r.counterexample) {
302
+ const c = evidence.counterexample;
303
+ items.push(item('rule-answer', 'meaning', subject, whereOf(n), `${label}: when ${c.facts}, it now gives ${c.after} (was ${c.before}).`, evidence));
304
+ } else if (!said) {
305
+ items.push(item('rule-facts', 'meaning', subject, whereOf(n), `${label}: ${lc(r.reason || 'its answers changed.')}`, evidence));
306
+ }
307
+ }
308
+
309
+ function compareFacets(o, n, items) {
310
+ const subject = subjectOf(n);
311
+ const dO = details(o), dN = details(n);
312
+ const before = items.length;
313
+ if ((o.m.route || '') !== (n.m.route || '')) {
314
+ items.push(item('address', 'risk', subject, whereOf(n), `The address changed: ${o.m.route || 'none'} is now ${n.m.route || 'none'}. Anything calling the old address must change too.`));
315
+ }
316
+ // Inputs
317
+ const gi = new Set(o.m.youGive), gn = new Set(n.m.youGive);
318
+ for (const x of n.m.youGive) if (!gi.has(x)) items.push(item('input-added', 'meaning', subject, whereOf(n), `Now also takes ${x}.`));
319
+ for (const x of o.m.youGive) if (!gn.has(x)) items.push(item('input-removed', 'meaning', subject, whereOf(n), `No longer takes ${x}.`));
320
+ // Stops: paired by their error, in order.
321
+ const added = [], removed = [];
322
+ const stopPairs = pairBy(dO.stops || [], dN.stops || [], (s) => s.error);
323
+ for (const [a, b] of stopPairs) { if (!a) added.push(b); if (!b) removed.push(a); }
324
+ // A new check guards everything after it: its question is left out of the other facts' conditions, and said once.
325
+ const guardsNew = new Set(added.map((s) => s.when.at(-1)?.question).filter(Boolean));
326
+ const guardsOld = new Set(removed.map((s) => s.when.at(-1)?.question).filter(Boolean));
327
+ const skipO = guardsOld, skipN = guardsNew;
328
+ for (const s of added) {
329
+ items.push(item('stop-added', 'meaning', subject, whereOf(n, s.line), `Now stops with ${stopName(s)}${whenText(s.when)}.`, { before: null, after: [...whenLines(s.when), `Stop: ${stopName(s)}`] }));
330
+ }
331
+ for (const s of removed) {
332
+ items.push(item('stop-removed', 'risk', subject, whereOf(n), `No longer stops with ${stopName(s)}${whenText(s.when)}. Check that this is no longer needed.`, { before: [...whenLines(s.when), `Stop: ${stopName(s)}`], after: null }));
333
+ }
334
+ for (const [a, b] of stopPairs) {
335
+ if (!a || !b) continue;
336
+ if ((a.message || '') !== (b.message || '')) items.push(item('stop-changed', 'meaning', subject, whereOf(n, b.line), `When it stops with ${b.error}, it now says "${b.message ?? ''}" (was "${a.message ?? ''}").`));
337
+ const wa = whenText(a.when, skipO), wb = whenText(b.when, skipN);
338
+ if (wa !== wb) items.push(item('stop-changed', 'risk', subject, whereOf(n, b.line), `Stops with ${b.error} under different conditions: now${wb || ' always'} (was${wa || ' always'}).`, { before: [...whenLines(a.when), `Stop: ${stopName(a)}`], after: [...whenLines(b.when), `Stop: ${stopName(b)}`] }));
339
+ }
340
+ // What it gives back (rules are compared by their answers instead).
341
+ if (n.m.kind !== 'rule') {
342
+ for (const [a, b] of pairBy(dO.givesBack || [], dN.givesBack || [], (g) => g.text)) {
343
+ if (!a) items.push(item('gives-back-added', 'meaning', subject, whereOf(n, b.line), `Now also ${lc(b.text)}${whenText(b.when, skipN)}.`, { before: null, after: [...whenLines(b.when), b.text] }));
344
+ else if (!b) items.push(item('gives-back-removed', 'meaning', subject, whereOf(n), `No longer ${lc(a.text)}${whenText(a.when, skipO)}.`, { before: [...whenLines(a.when), a.text], after: null }));
345
+ else if (whenText(a.when, skipO) !== whenText(b.when, skipN)) items.push(item('gives-back-changed', 'meaning', subject, whereOf(n, b.line), `${b.text} under different conditions: now${whenText(b.when, skipN) || ' always'} (was${whenText(a.when, skipO) || ' always'}).`));
346
+ }
347
+ }
348
+ // What it changes, saves, sends, or asks of another service.
349
+ const effects = (e, d) => {
350
+ const out = (d.changes || []).map((c) => ({ text: c.text, does: c.does, line: c.line, when: c.when }));
351
+ for (const nd of e.m.flow.nodes) if ((nd.does === 'ask' || nd.does === 'redirect') && nd.kind === 'step' && !out.some((x) => x.text === nd.text)) out.push({ text: nd.text, does: nd.does, line: nd.line ?? null, when: null });
352
+ return out;
353
+ };
354
+ // Reaching outside the program (another service, a payment, an email, stored data) is worth a careful look; adding
355
+ // to a list in memory or writing a log is not.
356
+ const outward = (x) => x.does === 'ask' || x.does === 'redirect' || (x.does === 'send' && !/^Writes a log/.test(x.text))
357
+ || (x.does === 'save' && /^(Writes to the database|Saves|Stores|Records|Deletes|Updates|Creates|Inserts)\b/.test(x.text));
358
+ for (const [a, b] of pairBy(effects(o, dO), effects(n, dN), (x) => x.text)) {
359
+ if (!a) items.push(item('effect-added', outward(b) ? 'risk' : 'meaning', subject, whereOf(n, b.line), `Now also ${lc(b.text)}${b.when ? whenText(b.when, skipN) : ''}.`, { before: null, after: [...whenLines(b.when), b.text] }));
360
+ else if (!b) items.push(item('effect-removed', 'meaning', subject, whereOf(n), `No longer ${lc(a.text)}${a.when ? whenText(a.when, skipO) : ''}.`, { before: [...whenLines(a.when), a.text], after: null }));
361
+ else if (a.when && b.when && whenText(a.when, skipO) !== whenText(b.when, skipN)) items.push(item('effect-changed', 'meaning', subject, whereOf(n, b.line), `${b.text} under different conditions: now${whenText(b.when, skipN) || ' always'} (was${whenText(a.when, skipO) || ' always'}).`));
362
+ }
363
+ // What it relies on.
364
+ const ro = new Set((dO.reliesOn || []).map((r) => r.label)), rn = new Set((dN.reliesOn || []).map((r) => r.label));
365
+ for (const r of rn) if (!ro.has(r)) items.push(item('relies-on', 'meaning', subject, whereOf(n), `Now also relies on ${r}.`));
366
+ for (const r of ro) if (!rn.has(r)) items.push(item('relies-on', 'meaning', subject, whereOf(n), `No longer relies on ${r}.`));
367
+ return items.length - before;
368
+ }
369
+
370
+ const literals = (tokens) => tokens.filter((t) => t.k === 'str' || t.k === 'num').map((t) => t.t);
371
+ function valueChanges(o, n) {
372
+ const a = literals(o.tokens), b = literals(n.tokens);
373
+ const onlyA = a.filter((x) => !b.includes(x)), onlyB = b.filter((x) => !a.includes(x));
374
+ if (!onlyA.length && !onlyB.length) return '';
375
+ if (onlyA.length === 1 && onlyB.length === 1) return ` (${onlyA[0]} became ${onlyB[0]})`;
376
+ return ` (values ${onlyA.length ? `${onlyA.slice(0, 4).join(', ')} removed` : ''}${onlyA.length && onlyB.length ? ', ' : ''}${onlyB.length ? `${onlyB.slice(0, 4).join(', ')} added` : ''})`;
377
+ }
378
+
379
+ function compareMember(o, n, items) {
380
+ const subject = subjectOf(n);
381
+ const sameCode = sameTokens(o.tokens, n.tokens);
382
+ const sameThunder = o.sig === n.sig;
383
+ const renamedOrMoved = [];
384
+ if (o.m.file !== n.m.file) renamedOrMoved.push(`moved from ${o.m.file} to ${n.m.file}`);
385
+ // A route handler is named after its address: a new address is said once, as the address.
386
+ if (nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? '') === (n.m.route ?? '')) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
387
+ const moveKind = o.m.file !== n.m.file && nameKey(o.m.name) === nameKey(n.m.name) ? 'moved' : 'renamed';
388
+ const formOnly = (why) => items.push(item(renamedOrMoved.length ? moveKind : 'form', 'form', subject, whereOf(n),
389
+ `${renamedOrMoved.length ? `${cap(renamedOrMoved.join(' and '))}. ` : ''}Only the form changed: ${why}`));
390
+ if (sameCode && sameThunder) {
391
+ if (!renamedOrMoved.length && o.code.join('\n') === n.code.join('\n')) return 'unchanged';
392
+ formOnly(renamedOrMoved.length ? 'the code is the same.' : 'spacing, line breaks, or comments; the code is otherwise identical.');
393
+ return 'form';
394
+ }
395
+ const noteMove = () => { if (renamedOrMoved.length) items.push(item(moveKind, 'form', subject, whereOf(n), `${cap(renamedOrMoved.join(' and '))}.`)); };
396
+ // Only local names changed (an input, a value it works out), consistently, and nothing else.
397
+ const renames = localRenames(o.tokens, n.tokens, n.m.language, [o.m.name]);
398
+ if (renames) {
399
+ const list = renames.filter(([a]) => a !== o.m.name).map(([a, b]) => `${a} is now ${b}`);
400
+ if (!list.length) { formOnly('the code is the same apart from its name.'); return 'form'; }
401
+ formOnly(`only names it declares itself changed (${list.join(', ')}); the code is otherwise identical.`);
402
+ return 'form';
403
+ }
404
+ if (o.m.kind === 'not-read' || n.m.kind === 'not-read') {
405
+ noteMove();
406
+ items.push(item('not-read', 'risk', subject, whereOf(n), 'Thunder cannot read this yet, and its code changed: check the code itself.', lineChanges(o.code, n.code)));
407
+ return 'changed';
408
+ }
409
+ if (o.m.rule && n.m.rule && !o.m.rule.partial && !n.m.rule.partial) {
410
+ const r = comparePlainRules(o.m.rule, n.m.rule);
411
+ if (r.same) {
412
+ formOnly(`same answer on all ${r.tried} edge cases, run on both versions.`);
413
+ return 'form';
414
+ }
415
+ noteMove();
416
+ ruleChanges(o, n, r, items);
417
+ return 'changed';
418
+ }
419
+ noteMove();
420
+ const start = items.length;
421
+ compareFacets(o, n, items);
422
+ const flat = (t) => String(t).toLowerCase().replace(/[^a-z0-9]+/g, '');
423
+ const facetEvidence = flat(items.slice(start).map((x) => JSON.stringify(x.evidence ?? '') + x.says).join(' '));
424
+ if (sameThunder) {
425
+ items.push(item('hidden', 'meaning', subject, whereOf(n), `Changed, check: Thunder reads the same, but the code differs in details Thunder's words leave out${valueChanges(o, n)}.`, lineChanges(o.code, n.code)));
426
+ return 'changed';
427
+ }
428
+ const diff = lineChanges(o.text.slice(1), n.text.slice(1));
429
+ const changed = [...diff.before, ...diff.after].filter((l) => l.startsWith('> '))
430
+ .map((l) => l.slice(2).trim().replace(/^- /, '').replace(/^(Ask|Answer): /, ''))
431
+ .filter((l) => !/^(Yes|No|For each|Always, at the end|If anything goes wrong)(:.*)?$/.test(l) && !/^(You give it|You get back|When someone calls):?/.test(l));
432
+ const uncovered = changed.filter((l) => !facetEvidence.includes(flat(l).slice(0, 40)));
433
+ if (uncovered.length || items.length === start) {
434
+ items.push(item('steps', 'meaning', subject, whereOf(n), `${items.length === start ? 'Steps changed' : 'Other steps changed too'}, check the before and after.`, diff));
435
+ }
436
+ return 'changed';
437
+ }
438
+
439
+ function summaryOf(e) {
440
+ const parts = [];
441
+ if (e.m.youGive.length) parts.push(`takes ${e.m.youGive.join(', ')}`);
442
+ if (e.m.youGetBack) parts.push(e.m.youGetBack.includes('stops with') ? `gives back ${e.m.youGetBack}` : `gives back ${e.m.youGetBack}`);
443
+ if (e.m.kind === 'rule') { const d = details(e); if (d.answers?.length) parts.push(`answers ${d.answers.map((a) => a.answer).join(', ')}`); }
444
+ return parts.length ? `: ${parts.join('; ')}` : '';
445
+ }
446
+
447
+ // ── Things (records, choices) ───────────────────────────────────────────────────────────────────────────────
448
+
449
+ function compareThings(A, B, items) {
450
+ const key = (t) => `${stemKey(t.file)}#${nameKey(t.name)}`;
451
+ let pairs = pairBy(A.model.things, B.model.things, key);
452
+ // A Thing in a moved file: the same name, once on each side.
453
+ const count = (list) => { const c = new Map(); for (const t of list) c.set(nameKey(t.name), (c.get(nameKey(t.name)) || 0) + 1); return c; };
454
+ const lonelyA = pairs.filter(([a, b]) => a && !b).map(([a]) => a), lonelyB = pairs.filter(([a, b]) => b && !a).map(([, b]) => b);
455
+ const ca = count(lonelyA), cb = count(lonelyB);
456
+ for (const a of lonelyA) {
457
+ if (ca.get(nameKey(a.name)) !== 1 || cb.get(nameKey(a.name)) !== 1) continue;
458
+ const b = lonelyB.find((t) => nameKey(t.name) === nameKey(a.name));
459
+ pairs = pairs.filter(([x, y]) => x !== a && y !== b).concat([[a, b]]);
460
+ items.push(item('moved', 'form', b.label, { file: b.file, line: b.lines[0] }, `Moved from ${a.file} to ${b.file}.`));
461
+ }
462
+ for (const [a, b] of pairs) {
463
+ const t = b ?? a;
464
+ const where = { file: t.file, line: t.lines[0] };
465
+ if (!a) { items.push(item('thing', 'meaning', t.label, where, `New ${t.kind === 'choices' ? 'set of choices' : t.kind}: ${t.label}${t.knows.length ? `, which knows ${[...new Set(t.knows.map((k) => k.label))].join(', ')}` : ''}${t.choices.length ? `: one of ${t.choices.join(', ')}` : ''}.`)); continue; }
466
+ if (!b) { items.push(item('thing', 'meaning', t.label, where, `Removed ${t.kind === 'choices' ? 'set of choices' : t.kind}: ${t.label}.`)); continue; }
467
+ const ka = new Map(a.knows.map((k) => [k.label, k])), kb = new Map(b.knows.map((k) => [k.label, k]));
468
+ for (const [l, k] of kb) {
469
+ if (!ka.has(l)) items.push(item('thing', 'meaning', t.label, { file: b.file, line: k.line ?? b.lines[0] }, `${b.label} now also knows ${l}${k.start ? ` (${k.start})` : ''}.`));
470
+ else if ((ka.get(l).start ?? '') !== (k.start ?? '')) items.push(item('thing', 'meaning', t.label, { file: b.file, line: k.line ?? b.lines[0] }, `${b.label}: ${l} is now ${k.start ?? 'not set'} (was ${ka.get(l).start ?? 'not set'}).`));
471
+ }
472
+ for (const l of ka.keys()) if (!kb.has(l)) items.push(item('thing', 'meaning', t.label, where, `${b.label} no longer knows ${l}.`));
473
+ for (const c of b.choices) if (!a.choices.includes(c)) items.push(item('thing', 'meaning', t.label, where, `${b.label} can now also be ${c}.`));
474
+ for (const c of a.choices) if (!b.choices.includes(c)) items.push(item('thing', 'meaning', t.label, where, `${b.label} can no longer be ${c}.`));
475
+ }
476
+ }
477
+
478
+ // ── Files Thunder does not read as steps ────────────────────────────────────────────────────────────────────
479
+
480
+ const INFRA = [/\.tf$/i, /\.tfvars$/i, /\.bicep$/i, /(^|\/)Dockerfile[^/]*$/i, /(^|\/)docker-compose[^/]*\.ya?ml$/i, /(^|\/)compose\.ya?ml$/i,
481
+ /(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/i, /(^|\/)\.gitlab-ci\.ya?ml$/i, /azure-pipelines[^/]*\.ya?ml$/i, /(^|\/)(k8s|kubernetes|helm|charts|deploy|infra|manifests)\/.+\.ya?ml$/i,
482
+ /(^|\/)serverless\.ya?ml$/i, /(^|\/)template\.ya?ml$/i, /\.cfn\.(json|ya?ml)$/i];
483
+ const isInfra = (p) => INFRA.some((re) => re.test(p));
484
+ // A line that only brings in something from another file (import, require, use, using, package).
485
+ const IMPORT_LINE = /^\s*(import\b|from\s+\S+\s+import\b|export\s+(\*|\{[^}]*\})\s+from\b|(const|let|var)\s+[\w${}\s,:]+=\s*require\(|require(_relative)?\s*\(?['"]|use\s+[\w:\\]+|using\s+[\w.]+\s*;|package\s+[\w.]+)/;
486
+
487
+ /** Code outside every action and rule (settings, imports, top-level values), as tokens: changes there change meaning. */
488
+ function outsideTokens(S, path) {
489
+ const src = S.sources.get(path);
490
+ if (src == null) return null;
491
+ const lang = readableLanguage(path);
492
+ const covered = new Set();
493
+ for (const e of S.members) if (e.m.file === path) for (let l = e.m.reviewLines[0]; l <= e.m.reviewLines[1]; l++) covered.add(l);
494
+ const all = src.split('\n');
495
+ const at = all.map((_, i) => i + 1).filter((l) => !covered.has(l));
496
+ const lines = at.map((l) => all[l - 1]);
497
+ return { lines, at, all, tokens: codeTokens(lines.join('\n'), lang) };
498
+ }
499
+
500
+ /** The name of the function a line sits in, from the nearest declaration above it (any common language). */
501
+ function enclosingName(lines, line) {
502
+ // A line can only sit inside a declaration indented less than itself; a line at the left edge is in none.
503
+ const indent = (l) => (l ?? '').match(/^[ \t]*/)[0].replace(/\t/g, ' ').length;
504
+ const target = indent(lines[line - 1]);
505
+ if (!target) return null;
506
+ for (let i = line - 2; i >= 0 && i >= line - 400; i--) {
507
+ if (!lines[i].trim() || indent(lines[i]) >= target) continue;
508
+ const m = lines[i].match(/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\*?|def|func|fn|fun|sub)\s+(?:\([^)]*\)\s*)?([A-Za-z_$][\w$]*)/)
509
+ || lines[i].match(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function|\(|[A-Za-z_$][\w$]*\s*=>)/)
510
+ || lines[i].match(/^\s*(?:(?:public|private|protected|internal|static|override|async|final)\s+)+[\w<>\[\],\s]*?\b([A-Za-z_]\w*)\s*\([^;]*$/);
511
+ if (m && !/^(if|for|while|switch|catch|return|else|elif|when|match|new|throw|await|typeof)$/.test(m[1])) return m[1];
512
+ }
513
+ return null;
514
+ }
515
+
516
+ // ── The review ──────────────────────────────────────────────────────────────────────────────────────────────
517
+
518
+ /**
519
+ * What changed in meaning between two versions of some code. `oldFiles` and `newFiles` are [{ path, source }];
520
+ * pass only the files that changed (and, for a moved file, both paths) or whole trees. Returns
521
+ * { schema, summary, items, notRead, unchanged } with items ordered by importance (risk, then meaning, then form).
522
+ */
523
+ export function thunderReview(oldFiles, newFiles) {
524
+ detailsCache = new WeakMap();
525
+ const A = side(oldFiles || []), B = side(newFiles || []);
526
+ const items = [];
527
+ const used = new Set(), pairs = [];
528
+ // 1. Same file and name.
529
+ for (const o of A.members) { const n = B.byKey.get(o.key); if (n && !used.has(n)) { used.add(n); pairs.push([o, n]); o.paired = true; } }
530
+ // 2. The same name, used once on each side (a moved file).
531
+ const unique = (list) => { const c = new Map(); for (const e of list) c.set(`${nameKey(e.m.name)}#${e.m.kind}`, (c.get(`${nameKey(e.m.name)}#${e.m.kind}`) || 0) + 1); return c; };
532
+ const leftA = () => A.members.filter((e) => !e.paired), leftB = () => B.members.filter((e) => !used.has(e));
533
+ {
534
+ const ua = unique(leftA()), ub = unique(leftB());
535
+ for (const o of leftA()) {
536
+ const k = `${nameKey(o.m.name)}#${o.m.kind}`;
537
+ if (ua.get(k) !== 1 || ub.get(k) !== 1) continue;
538
+ const n = leftB().find((e) => `${nameKey(e.m.name)}#${e.m.kind}` === k);
539
+ if (n) { used.add(n); pairs.push([o, n]); o.paired = true; }
540
+ }
541
+ }
542
+ // 3. A route handler whose address changed: the same file and method, and the same code apart from the address.
543
+ const withoutAddress = (e) => e.tokens.map((t) => (t.k === 'str' && e.m.route && t.t.slice(1, -1) === e.m.route.split(' ').slice(1).join(' ') ? '"ADDRESS"' : t.t)).join(' ');
544
+ for (const o of leftA().filter((e) => e.m.route)) {
545
+ const n = leftB().find((e) => e.m.route && e.m.file === o.m.file && e.m.route.split(' ')[0] === o.m.route.split(' ')[0] && withoutAddress(e) === withoutAddress(o));
546
+ if (n) { used.add(n); pairs.push([o, n]); o.paired = true; }
547
+ }
548
+ // 4. By meaning: a renamed function whose code is the same apart from its name, or a rule with the same answers.
549
+ for (const o of leftA()) {
550
+ const n = leftB().find((e) => e.m.kind === o.m.kind && e.m.language === o.m.language && ((e.sig === o.sig && localRenames(o.tokens, e.tokens, e.m.language, [o.m.name]))
551
+ || (o.m.rule && e.m.rule && !o.m.rule.partial && !e.m.rule.partial && comparePlainRules(o.m.rule, e.m.rule).same)));
552
+ if (n) { used.add(n); pairs.push([o, n]); o.paired = true; }
553
+ }
554
+ let unchanged = 0;
555
+ for (const [o, n] of pairs) if (compareMember(o, n, items) === 'unchanged') unchanged++;
556
+ for (const o of leftA()) items.push(item('removed', 'meaning', subjectOf(o), whereOf(o), `Removed ${KIND_WORD[o.m.kind] ?? 'function'}: ${subjectOf(o)}.`, { before: o.text, after: null }));
557
+ for (const n of leftB()) items.push(item('added', n.m.kind === 'not-read' ? 'risk' : 'meaning', subjectOf(n), whereOf(n),
558
+ n.m.kind === 'not-read' ? "New function that Thunder cannot read yet: check the code itself." : `New ${KIND_WORD[n.m.kind] ?? 'function'}: ${subjectOf(n)}${summaryOf(n)}.`, { before: null, after: n.text }));
559
+ compareThings(A, B, items);
560
+
561
+ // Files: code outside every action and rule, files Thunder could not read, and files it does not read.
562
+ const paths = [...new Set([...A.sources.keys(), ...B.sources.keys()])];
563
+ const notRead = [];
564
+ for (const p of paths) {
565
+ const before = A.sources.get(p), after = B.sources.get(p);
566
+ if (before === after) continue;
567
+ const lang = !isInfra(p) && readableLanguage(p);
568
+ if (!lang) {
569
+ if (isInfra(p)) items.push(item('infrastructure', 'risk', p, { file: p, line: 1 }, `${before == null ? 'New' : after == null ? 'Removed' : 'Changed'} infrastructure or pipeline file. Thunder does not read these in this version, so check it yourself.`, before != null && after != null ? lineChanges(before.split('\n'), after.split('\n')) : null));
570
+ else notRead.push({ path: p, status: before == null ? 'added' : after == null ? 'removed' : 'changed' });
571
+ continue;
572
+ }
573
+ const why = B.model.unknowns.find((u) => u.file === p && /^Could not read this file/.test(u.why));
574
+ if (why) { items.push(item('unreadable', 'risk', p, { file: p, line: 1 }, `Thunder could not read this file, so its changes are not described here: check it yourself. (${why.why})`)); continue; }
575
+ if (before == null || after == null) continue; // a whole new or removed file: its members are listed
576
+ const oa = outsideTokens(A, p), ob = outsideTokens(B, p);
577
+ if (oa && ob && !sameTokens(oa.tokens, ob.tokens)) {
578
+ const diff = lineChanges(oa.lines, ob.lines);
579
+ // Where: the first changed line in the new file, and the function it sits in when the code names one.
580
+ let k = 0;
581
+ while (k < oa.lines.length && k < ob.lines.length && oa.lines[k] === ob.lines[k]) k++;
582
+ const line = ob.at[Math.min(k, ob.at.length - 1)] ?? 1;
583
+ const near = enclosingName(ob.all, line);
584
+ const changedLines = [...diff.before, ...diff.after].filter((l) => l.startsWith('> ') && l.slice(2).trim());
585
+ if (changedLines.length && changedLines.every((l) => IMPORT_LINE.test(l.slice(2)) || /^[\s{}()[\],;]*$/.test(l.slice(2)) || /^\s*[\w$]+,?\s*$/.test(l.slice(2)))) {
586
+ items.push(item('outside', 'meaning', p, { file: p, line }, 'What this file uses from other files changed (its imports): check the before and after.', diff));
587
+ } else {
588
+ items.push(item('outside', 'meaning', p, { file: p, line }, `Changed in code Thunder did not read as an action or rule${near ? ` (in or near ${near})` : ' (outside any function)'}, which can change what the code does: check the before and after.`, diff));
589
+ }
590
+ }
591
+ }
592
+
593
+ // A moved file: one line, not one per function.
594
+ const moved = items.filter((x) => x.kind === 'moved' && x.severity === 'form' && /Only the form changed/.test(x.says));
595
+ const groups = new Map();
596
+ for (const x of moved) { const k = x.says.match(/moved from (\S+) to (\S+?)\. /i)?.slice(1).join('→'); if (k) { if (!groups.has(k)) groups.set(k, []); groups.get(k).push(x); } }
597
+ for (const [k, list] of groups) {
598
+ if (list.length < 2) continue;
599
+ const [from, to] = k.split('→');
600
+ for (const x of list) items.splice(items.indexOf(x), 1);
601
+ items.push(item('moved', 'form', to, { file: to, line: 1 }, `Moved from ${from} to ${to}. Only the form changed: ${list.length} actions, rules, or functions have the same code.`));
602
+ }
603
+
604
+ // The same sentence about several functions (a renamed input passed everywhere): one item that names them all.
605
+ const same = new Map();
606
+ for (const x of [...items]) {
607
+ if (x.severity === 'form' || x.kind === 'outside' || x.kind === 'hidden' || x.kind === 'steps' || x.kind === 'not-read') continue;
608
+ const k = `${x.severity}|${x.kind}|${x.says}`;
609
+ if (!same.has(k)) { same.set(k, x); continue; }
610
+ (same.get(k).also ||= []).push({ subject: x.subject, where: x.where });
611
+ items.splice(items.indexOf(x), 1);
612
+ }
613
+ // "Changed, check" and "cannot read" in many functions: one item each, naming the functions.
614
+ for (const kind of ['hidden', 'not-read']) {
615
+ const list = items.filter((x) => x.kind === kind);
616
+ if (list.length < 4) continue;
617
+ const [first, ...rest] = list;
618
+ first.also = rest.map((x) => ({ subject: x.subject, where: x.where, ...(x.evidence ? { evidence: x.evidence } : {}) }));
619
+ for (const x of rest) items.splice(items.indexOf(x), 1);
620
+ }
621
+ for (const x of items) if (x.also) x.subject = `${x.subject} and ${x.also.length} more`;
622
+
623
+ items.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind)
624
+ || String(a.where.file).localeCompare(String(b.where.file)) || (a.where.line ?? 0) - (b.where.line ?? 0));
625
+ const count = (s) => items.filter((x) => x.severity === s).length;
626
+ const summary = { meaning: count('meaning'), risk: count('risk'), form: count('form'), unchanged, files: paths.filter((p) => A.sources.get(p) !== B.sources.get(p)).length };
627
+ const onlyNotRead = !items.length && summary.files && notRead.length === summary.files;
628
+ return { schema: REVIEW_SCHEMA, summary, says: onlyNotRead ? 'Only files Thunder does not read changed.' : summaryLine(summary), items, notRead };
629
+ }
630
+
631
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
632
+ function summaryLine(s) {
633
+ if (!s.meaning && !s.risk && !s.form) return s.files ? 'No change in the code Thunder reads, apart from comments or spacing outside its actions and rules.' : 'Nothing changed.';
634
+ return `${plural(s.meaning, 'change', 'changes')} in meaning, ${plural(s.risk, 'risk', 'risks')}, ${s.form} form-only.`;
635
+ }
636
+
637
+ // ── Markdown, for a pull request comment ─────────────────────────────────────────────────────────────────────
638
+
639
+ const fence = (lines) => ['```', ...lines.map((l) => l.replace(/```/g, "'''")), '```'];
640
+ function evidenceBlock(ev) {
641
+ if (!ev) return [];
642
+ const out = [];
643
+ if (ev.counterexample) out.push(`Tried both: when ${ev.counterexample.facts}, before: **${ev.counterexample.before}**, after: **${ev.counterexample.after}**.`, '');
644
+ if (ev.before?.length) out.push('Before:', ...fence(ev.before));
645
+ if (ev.after?.length) out.push('After:', ...fence(ev.after));
646
+ return out.length ? ['<details><summary>Before and after</summary>', '', ...out, '', '</details>'] : [];
647
+ }
648
+
649
+ /** The review as Markdown for a pull request comment, starting with REVIEW_MARKER so a bot can find and update it. */
650
+ export function renderReview(r, { title = 'Thunder review', maxChars = 60000, footer = '' } = {}) {
651
+ const out = [REVIEW_MARKER, `### ${title}`, '', `**${r.says}**`, ''];
652
+ out.push('Read from the code by the Thunder compiler, with no AI. "Only the form changed" is said only when it is shown: the code is identical apart from spacing, comments, or names it declares itself, or a rule gives the same answer on every edge case.', '');
653
+ const alsoIn = (x) => (x.also?.length ? [` <details><summary>Also in ${x.also.length} more</summary>`, '', ...x.also.slice(0, 50).map((a) => ` - **${a.subject}** · \`${a.where.file}:${a.where.line}\``), ...(x.also.length > 50 ? [` - and ${x.also.length - 50} more`] : []), '', ' </details>'] : []);
654
+ const line = (x) => [`- **${x.subject}** · \`${x.where.file}:${x.where.line}\`: ${x.says}`, ...evidenceBlock(x.evidence).map((l) => (l ? ` ${l}` : '')), ...alsoIn(x)];
655
+ const section = (sev, head) => {
656
+ const list = r.items.filter((x) => x.severity === sev);
657
+ if (!list.length) return;
658
+ if (sev === 'form') { out.push(`<details><summary>${head} (${list.length})</summary>`, '', ...list.map((x) => `- **${x.subject}** · \`${x.where.file}:${x.where.line}\`: ${x.says}`), '', '</details>', ''); return; }
659
+ out.push(`#### ${head}`, '');
660
+ for (const x of list) out.push(...line(x));
661
+ out.push('');
662
+ };
663
+ section('risk', 'Needs a careful look');
664
+ section('meaning', 'Changes in meaning');
665
+ section('form', 'Only the form changed');
666
+ if (r.notRead.length) out.push(`Also changed, not read by Thunder: ${r.notRead.slice(0, 20).map((f) => `\`${f.path}\``).join(', ')}${r.notRead.length > 20 ? `, and ${r.notRead.length - 20} more` : ''}.`, '');
667
+ if (footer) out.push(footer, '');
668
+ let text = out.join('\n');
669
+ if (text.length > maxChars) text = `${text.slice(0, maxChars - 200)}\n\n…cut short to fit. Run \`thunder review\` locally to see every change.\n`;
670
+ return text;
671
+ }