@skillstech/thunderlang 1.6.1 → 1.8.0

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 (81) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +10 -3
  3. package/dist/core.cjs +264 -47
  4. package/dist/index.cjs +9118 -1077
  5. package/dist/learn.cjs +1419 -90
  6. package/package.json +1 -1
  7. package/src/ai.mjs +2 -1
  8. package/src/atlas.mjs +2 -1
  9. package/src/behaviour.mjs +246 -0
  10. package/src/cli-main.mjs +3015 -0
  11. package/src/cli.mjs +9 -2799
  12. package/src/conflict.mjs +0 -0
  13. package/src/core/ThunderDotnet.cs +195 -0
  14. package/src/core/check.mjs +316 -10
  15. package/src/core/cli.mjs +67 -10
  16. package/src/core/csharp-run.mjs +29 -8
  17. package/src/core/diagnostics.mjs +12 -1
  18. package/src/core/engine-core.mjs +161 -20
  19. package/src/core/engine-values.mjs +1 -0
  20. package/src/core/engine.mjs +131 -7
  21. package/src/core/go-run.mjs +3 -2
  22. package/src/core/index.mjs +6 -2
  23. package/src/core/java-run.mjs +3 -3
  24. package/src/core/kind.mjs +45 -0
  25. package/src/core/lexer.mjs +16 -2
  26. package/src/core/parser.mjs +254 -22
  27. package/src/core/project-root.mjs +18 -0
  28. package/src/core/project.mjs +18 -18
  29. package/src/core/react-run.mjs +3 -3
  30. package/src/core/runtime-go/thunder_runtime.go +269 -1
  31. package/src/core/runtime-npm.mjs +79 -0
  32. package/src/core/runtime-python.mjs +365 -3
  33. package/src/core/runtime-react.mjs +2 -1
  34. package/src/core/runtime-typescript.mjs +155 -6
  35. package/src/core/rust-run.mjs +3 -2
  36. package/src/core/serving.mjs +12 -0
  37. package/src/core/store-format.mjs +110 -0
  38. package/src/core/target-csharp.mjs +5 -1
  39. package/src/core/target-go.mjs +11 -4
  40. package/src/core/target-python.mjs +39 -6
  41. package/src/core/target-rust.mjs +1 -1
  42. package/src/core/target-typescript.mjs +95 -7
  43. package/src/core/typescript-run.mjs +14 -7
  44. package/src/core-changes-fs.mjs +28 -0
  45. package/src/core-changes.d.mts +67 -0
  46. package/src/core-changes.mjs +603 -0
  47. package/src/core-rules.mjs +146 -0
  48. package/src/core-services.d.mts +4 -0
  49. package/src/core-services.mjs +49 -0
  50. package/src/decision.mjs +2 -1
  51. package/src/distributed.mjs +2 -1
  52. package/src/emit.mjs +2 -2
  53. package/src/evidence.mjs +28 -0
  54. package/src/examples.d.mts +21 -0
  55. package/src/examples.mjs +175 -0
  56. package/src/focus.mjs +2 -1
  57. package/src/index.d.ts +4 -0
  58. package/src/index.mjs +4 -0
  59. package/src/intent-atlas.mjs +4 -3
  60. package/src/mcp.mjs +52 -6
  61. package/src/passport-fs.mjs +2 -1
  62. package/src/passport.mjs +2 -1
  63. package/src/privacy.mjs +2 -1
  64. package/src/program.d.mts +4 -0
  65. package/src/program.mjs +4 -0
  66. package/src/read-repo-fs.mjs +2 -1
  67. package/src/read-repo.mjs +3 -2
  68. package/src/report.mjs +3 -2
  69. package/src/review.mjs +71 -4
  70. package/src/select.mjs +2 -1
  71. package/src/semantic-diff.mjs +7 -6
  72. package/src/system.mjs +3 -2
  73. package/src/text-order.mjs +6 -0
  74. package/src/thunderize.mjs +2 -1
  75. package/src/trace-cli.mjs +8 -3
  76. package/src/trace-data.mjs +3 -2
  77. package/src/trace-fs.mjs +29 -3
  78. package/src/trace.mjs +27 -10
  79. package/src/write-across-cli.mjs +22 -4
  80. package/src/write-across.mjs +2 -1
  81. package/syntaxes/thunder.tmLanguage.json +196 -0
@@ -0,0 +1,603 @@
1
+ // Behaviour changes in Thunder™ programs: what a change to Thunder Core code does, rule by rule, and what to look at
2
+ // again because of it (roadmap 3.4 + D.5). The Core side of `thunder review`, and the library calls
3
+ // coreChanges(oldFiles, newFiles) and affectedBy(files, change).
4
+ //
5
+ // before ─┐ 1. rules, each with a stable name ┌─ "decide refund: now a review Refund instead of an approved
6
+ // ├─ 2. paired by name, then compared ───┤ Refund when amount is from $50.00 to $99.99 (tried)"
7
+ // after ──┘ 3. both versions run on inputs └─ look again at: POST /orders/{number}/refunds, test "…"
8
+ //
9
+ // 1. A rule's name comes from what it is, never from its line: `function:decide refund`, `endpoint:POST /orders`,
10
+ // `keep:review limit`, `never:Product: Never allow a negative stock`, `record:Product`, `store:products`,
11
+ // `test:the refund rule`. Moving, reformatting, or commenting code keeps the name; a function renamed with the
12
+ // same steps is paired as a rename.
13
+ // 2. What each rule uses (functions it calls, kept values, data types and their Never rules, stored lists,
14
+ // endpoints a test calls) is read from the checked program, so a change reaches everything that depends on it.
15
+ // 3. A function whose steps changed, or that uses something that changed, is run before and after on the same
16
+ // inputs, made from the numbers and text in both versions (each number with one step either side) and the usual
17
+ // edges. Answers that differ are grouped ("approved -> review") and, where one input decides it, given as the
18
+ // range of values tried. Tested evidence, never a proof: it covers the inputs it tried. A function that reads
19
+ // saved data or calls another service is not run, and says so. Each call has a step limit.
20
+ //
21
+ // Pure and browser-safe: takes [{ path, source }] for each side; the caller reads files and git.
22
+
23
+ import { isCoreProgram } from './core/kind.mjs';
24
+ import { coreSide as side, KIND_WORD, SKIP_KEYS, usesOf, reach, dependents } from './core-rules.mjs';
25
+ import { engineForCalls, OutOfSteps } from './core/engine-core.mjs';
26
+ import { inputValue, dataJson } from './core/store-format.mjs';
27
+ import { RecordVal, Dec, asPyErr, explain, show } from './core/engine-values.mjs';
28
+ import { byText } from './text-order.mjs';
29
+
30
+ export const CORE_CHANGES_SCHEMA = 'thunder-core-changes-v1';
31
+ export const AFFECTED_SCHEMA = 'thunder-affected-v1';
32
+
33
+ const MAX_RUNS = 3000; // inputs per function and side (a call is fast: thousands take well under a second)
34
+ const MAX_SHOWN_GROUPS = 4;
35
+ // Time limits, so a review stays quick however many functions changed: each function's runs, and the whole
36
+ // comparison. A comparison that stops early says how many inputs it tried.
37
+ const MS_PER_FUNCTION = 2000;
38
+ const MS_IN_ALL = 20000;
39
+
40
+ export { isCoreProgram };
41
+
42
+ // ── 2. Pairing and comparing ───────────────────────────────────────────────────────────────────────────────────
43
+
44
+ const sameText = (a, b) => a.length === b.length && a.every((l, i) => l.trim() === b[i].trim());
45
+
46
+ /** Pairs by name, then a function or endpoint renamed with the same steps. Gives [[old, new]] (either may be null). */
47
+ function pair(A, B) {
48
+ const pairs = [];
49
+ const usedB = new Set();
50
+ for (const [id, a] of A.units) { const b = B.units.get(id); if (b) { pairs.push([a, b]); usedB.add(id); } }
51
+ const leftA = [...A.units.values()].filter((a) => !B.units.has(a.id));
52
+ const leftB = [...B.units.values()].filter((b) => !usedB.has(b.id));
53
+ for (const a of leftA) {
54
+ const b = leftB.find((x) => !usedB.has(x.id) && x.kind === a.kind && (a.kind === 'function' || a.kind === 'endpoint' || a.kind === 'test') && sameText(a.text.slice(1), x.text.slice(1)) && a.text.length > 1);
55
+ if (b) { usedB.add(b.id); pairs.push([a, b]); } else pairs.push([a, null]);
56
+ }
57
+ for (const b of leftB) if (!usedB.has(b.id)) pairs.push([null, b]);
58
+ return pairs;
59
+ }
60
+
61
+ // ── 3. Running both versions ───────────────────────────────────────────────────────────────────────────────────
62
+
63
+ function engineOf(s) {
64
+ if (!s.engine) {
65
+ const ok = s.results.every((r) => r.ok);
66
+ s.engine = ok ? engineForCalls({ results: s.results }) : { failed: 'the program has problems' };
67
+ }
68
+ return s.engine;
69
+ }
70
+ const modOf = (s, u) => engineOf(s).mods?.[s.results.indexOf(u.result)];
71
+
72
+ /** Numbers and text written in a program: the values the inputs are made from. */
73
+ function literals(sides) {
74
+ // kept: the numbers written in kept values (Keep review limit at $100): limits, so they and their neighbours come first.
75
+ const lit = { money: new Set(), whole: new Set(), number: new Set(), text: new Set(), date: new Set(), kept: new Set() };
76
+ const seen = new Set();
77
+ const walk = (x, inKeep = false) => {
78
+ if (!x || typeof x !== 'object' || seen.has(x)) return;
79
+ seen.add(x);
80
+ if (Array.isArray(x)) { for (const y of x) walk(y, inKeep); return; }
81
+ if (x.k === 'keep') inKeep = true;
82
+ if ((x.k === 'money' || x.k === 'num') && x.text && inKeep) lit.kept.add(String(x.text).replace(/[$,]/g, ''));
83
+ if (x.k === 'money' && x.text) lit.money.add(String(x.text).replace(/[$,]/g, ''));
84
+ else if (x.k === 'num' && x.text) (x.whole ? lit.whole : lit.number).add(String(x.text).replace(/,/g, ''));
85
+ else if (x.k === 'str' && Array.isArray(x.parts) && x.parts.every((p) => typeof p === 'string')) { const t = x.parts.join(''); if (t.length <= 40) lit.text.add(t); }
86
+ else if (x.k === 'date' && x.text) lit.date.add(String(x.text));
87
+ for (const [k, v] of Object.entries(x)) if (!SKIP_KEYS.has(k)) walk(v, inKeep);
88
+ };
89
+ for (const s of sides) for (const r of s.results) walk(r.program);
90
+ return lit;
91
+ }
92
+
93
+ const decStr = (d) => d.toString();
94
+ const sortDec = (xs) => [...new Map(xs.map((x) => [decStr(x), x])).values()].sort((a, b) => Dec.cmp(a, b));
95
+ /**
96
+ * At most `n` values, in order: kept values and their neighbours, the edges, then the other numbers written in the
97
+ * program and their neighbours, in the order they are written. Given back sorted.
98
+ */
99
+ function capped(groups, n) {
100
+ const out = new Map();
101
+ for (const g of groups) for (const d of g) { if (out.size >= n) break; if (!out.has(decStr(d))) out.set(decStr(d), d); }
102
+ return sortDec([...out.values()]);
103
+ }
104
+
105
+ function candidates(kind, lit) {
106
+ switch (kind) {
107
+ case 'money': {
108
+ const step = Dec.parse('0.01');
109
+ const near = (ts) => ts.map((t) => Dec.parse(t)).filter(Boolean).flatMap((d) => [Dec.sub(d, step), d, Dec.add(d, step)]).filter((d) => !d.s || d.isZero());
110
+ const kept = near([...lit.kept].filter((t) => lit.money.has(t)));
111
+ const edges = ['0', '1000', '0.01', '1'].map((t) => Dec.parse(t));
112
+ return capped([kept, edges, near([...lit.money])], 24).map((d) => d.toFixed(2));
113
+ }
114
+ case 'whole': case 'number': {
115
+ const one = Dec.parse('1');
116
+ const pool = [...lit.whole, ...(kind === 'number' ? lit.number : [])];
117
+ const near = (ts) => ts.map((t) => Dec.parse(t)).filter(Boolean).flatMap((d) => [Dec.sub(d, one), d, Dec.add(d, one)]);
118
+ const kept = near([...lit.kept].filter((t) => pool.includes(t)));
119
+ const edges = ['0', '1', '1000', '-1', '2'].map((t) => Dec.parse(t));
120
+ return capped([kept, edges, near(pool)], 18).map((d) => (kind === 'whole' ? Number(decStr(d)) : decStr(d)));
121
+ }
122
+ case 'text': return [...new Set(['', 'x', ...lit.text])].slice(0, 10);
123
+ case 'bool': return [false, true];
124
+ case 'date': return [...new Set(['2026-01-01', '2026-12-31', ...lit.date])].slice(0, 6);
125
+ default: return null;
126
+ }
127
+ }
128
+
129
+ const SCALAR = new Set(['money', 'whole', 'number', 'text', 'bool', 'date']);
130
+
131
+ /**
132
+ * The inputs a function takes, as slots that each take one value: a plain input is one slot; a data type is one
133
+ * slot per field (an either/or type also chooses its alternative). Gives { slots, build(rawValues) -> rows } or
134
+ * { why } when an input has a kind the comparison doesn't make values for yet.
135
+ */
136
+ function slotsFor(params, recordsInfo, lit) {
137
+ const slots = [];
138
+ const plan = [];
139
+ for (const p of params) {
140
+ let t = p.type;
141
+ const optional = t?.k === 'optional';
142
+ if (optional) t = t.of;
143
+ if (SCALAR.has(t?.k)) {
144
+ const values = candidates(t.k, lit);
145
+ slots.push({ label: p.text, kind: t.k, values: optional ? [null, ...values] : values });
146
+ plan.push({ p, at: slots.length - 1 });
147
+ } else if (t?.k === 'record') {
148
+ const rec = recordsInfo.get(t.name);
149
+ if (!rec) return { why: `its input "${p.text}" is a data type this version does not have` };
150
+ const fields = [];
151
+ for (const f of rec.fields) {
152
+ let ft = f.type, opt = ft?.k === 'optional';
153
+ if (opt) ft = ft.of;
154
+ if (rec.alts && f.py === 'which') { slots.push({ label: `${p.text}'s alternative`, kind: 'which', values: rec.alts.map((a) => a.name) }); fields.push({ f, at: slots.length - 1 }); continue; }
155
+ if (SCALAR.has(ft?.k)) { slots.push({ label: `${p.text}'s ${f.name}`, kind: ft.k, values: candidates(ft.k, lit) }); fields.push({ f, at: slots.length - 1 }); continue; }
156
+ if (opt) { fields.push({ f, fixed: null }); continue; }
157
+ if (ft?.k === 'list') { fields.push({ f, fixed: [] }); continue; }
158
+ return { why: `its input "${p.text}" has a field (${f.text}) the comparison does not make values for yet` };
159
+ }
160
+ plan.push({ p, rec, fields });
161
+ } else if (t?.k === 'list' && SCALAR.has(t.of?.k)) {
162
+ const one = candidates(t.of.k, lit);
163
+ slots.push({ label: p.text, kind: 'list', values: [[], [one[Math.floor(one.length / 2)]], one.slice(0, 3)] });
164
+ plan.push({ p, at: slots.length - 1 });
165
+ } else if (optional) plan.push({ p, fixed: null });
166
+ else return { why: `its input "${p.text}" is a kind the comparison does not make values for yet` };
167
+ }
168
+ return { slots, plan };
169
+ }
170
+
171
+ /** Seeded, so the same function always gets the same inputs. */
172
+ function seeded(text) {
173
+ let h = 2166136261;
174
+ for (const c of text) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
175
+ return () => { h += 0x6d2b79f5; let t = h; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
176
+ }
177
+
178
+ /** Which values to try: every combination when there are few; otherwise each slot swept from several starting points, and a fixed sample. */
179
+ function inputsFor(slots, seedText) {
180
+ const total = slots.reduce((n, s) => n * s.values.length, 1);
181
+ const out = [], seen = new Set();
182
+ const push = (idx) => { const k = idx.join(','); if (!seen.has(k) && out.length < MAX_RUNS) { seen.add(k); out.push(idx); } };
183
+ if (total <= MAX_RUNS) {
184
+ const idx = slots.map(() => 0);
185
+ for (let n = 0; n < total; n++) { push([...idx]); for (let i = slots.length - 1; i >= 0; i--) { if (++idx[i] < slots[i].values.length) break; idx[i] = 0; } }
186
+ return out;
187
+ }
188
+ const rnd = seeded(seedText);
189
+ const pick = () => slots.map((s) => Math.floor(rnd() * s.values.length));
190
+ // Starting points: each slot at its lowest or highest value, in every combination (a large total with nothing
191
+ // refunded is one), in a fixed shuffled order; then a few chosen at random.
192
+ const combos = [];
193
+ const k = Math.min(slots.length, 8);
194
+ for (let m = 0; m < 2 ** k; m++) combos.push(slots.map((s, i) => (i < k && (m >> i) & 1 ? s.values.length - 1 : 0)));
195
+ const bases = [slots.map((s) => Math.floor(s.values.length / 2)), ...combos.map((c) => [rnd(), c]).sort((x, y) => x[0] - y[0]).map((x) => x[1])];
196
+ for (let i = 0; i < 8; i++) bases.push(pick());
197
+ for (const b of bases) for (let si = 0; si < slots.length; si++) for (let vi = 0; vi < slots[si].values.length; vi++) { const x = [...b]; x[si] = vi; push(x); }
198
+ for (let tries = 0; out.length < MAX_RUNS && tries < MAX_RUNS * 4; tries++) push(pick());
199
+ return out;
200
+ }
201
+
202
+ const article = (w) => (/^[aeiou]/i.test(w) ? 'an' : 'a');
203
+ const stopShape = (m) => m.replace(/\$?-?\d[\d,]*(\.\d+)?/g, '…');
204
+
205
+ /** What one call did, in words, with a key that says exactly what it gave (and its fields, for a record). */
206
+ function outcome(fn) {
207
+ try {
208
+ const v = fn();
209
+ let key;
210
+ try { key = dataJson(v); } catch { key = show(v); }
211
+ if (v instanceof RecordVal) {
212
+ const which = v.cls.alts ? v.f.get('which') : null;
213
+ const label = which ? `${article(which)} ${which} ${v.cls.py}` : `${article(v.cls.py)} ${v.cls.py}`;
214
+ let fields = null;
215
+ try { fields = JSON.parse(key); } catch { /* not JSON: compared whole */ }
216
+ return { key, label, group: label, fields };
217
+ }
218
+ const label = Array.isArray(v) ? `a list of ${v.length}` : typeof v === 'string' ? JSON.stringify(v) : show(v);
219
+ return { key, label, group: label };
220
+ } catch (e) {
221
+ if (e instanceof OutOfSteps || e instanceof RangeError) return { unknown: true };
222
+ const err = asPyErr(e);
223
+ const msg = explain(err);
224
+ if (err.pyType === 'Stop') return { key: `stop:${msg}`, label: `stops with "${msg}"`, group: `stops with "${stopShape(msg)}"` };
225
+ if (err.pyType === 'RuleBroken') return { key: `rule:${msg}`, label: `breaks a rule (${msg})`, group: `breaks a rule (${stopShape(msg)})` };
226
+ return { key: `fail:${msg}`, label: `fails (${msg})`, group: `fails (${stopShape(msg)})` };
227
+ }
228
+ }
229
+
230
+ const fieldWords = (k) => k.replace(/_/g, ' ');
231
+ const fieldValue = (v) => (typeof v === 'string' ? JSON.stringify(v) : v === null ? 'nothing' : String(v));
232
+
233
+ /**
234
+ * How two different answers differ, as a group key and words: another kind of answer ("now a review Refund
235
+ * instead of an approved Refund"), or the same kind with fields that changed ("its reason is now …").
236
+ */
237
+ function difference(oa, ob) {
238
+ if (oa.group !== ob.group) return { key: `${oa.group} -> ${ob.group}`, says: `now ${ob.group} instead of ${oa.group}`, otherKind: true };
239
+ if (oa.fields && ob.fields) {
240
+ const names = [...new Set([...Object.keys(oa.fields), ...Object.keys(ob.fields)])].filter((k) => JSON.stringify(oa.fields[k]) !== JSON.stringify(ob.fields[k]));
241
+ if (names.length) {
242
+ const shown = names.slice(0, 2).map((k) => `its ${fieldWords(k)} is now ${fieldValue(ob.fields[k])} instead of ${fieldValue(oa.fields[k])}`);
243
+ return { key: `${ob.group}: ${names.join(',')}`, says: `still ${ob.group}, but ${shown.join(', and ')}${names.length > 2 ? ` (and ${names.length - 2} more fields)` : ''}` };
244
+ }
245
+ }
246
+ return { key: `${oa.label} -> ${ob.label}`, says: `now ${ob.label} instead of ${oa.label}` };
247
+ }
248
+
249
+ const recordsInfoOf = (u) => new Map((u.result.info?.records ?? []).map((r) => [r.name, r]));
250
+
251
+ /** The arguments for one input on one side, or { refused } when this side can't make them (a Never rule, say). */
252
+ function argsFor(api, mod, plan, slots, idx) {
253
+ const args = [];
254
+ for (const step of plan) {
255
+ if ('fixed' in step && !step.rec) { args.push(step.fixed); continue; }
256
+ if (!step.rec) { const raw = slots[step.at].values[idx[step.at]]; args.push(raw === null ? null : step.p.type.k === 'list' ? raw.map((x) => inputValue(x, step.p.type.of, step.p.text, false)) : inputValue(raw, step.p.type.k === 'optional' ? step.p.type.of : step.p.type, step.p.text, false)); continue; }
257
+ const row = {};
258
+ const altAt = step.fields.find((x) => x.f.py === 'which' && 'at' in x);
259
+ const alt = altAt ? step.rec.alts.find((a) => a.name === slots[altAt.at].values[idx[altAt.at]]) : null;
260
+ for (const x of step.fields) {
261
+ if (x.f.py === 'which') { row.which = alt?.name; continue; }
262
+ if (alt && !alt.fields.some((af) => af.py === x.f.py)) { row[x.f.py] = null; continue; }
263
+ row[x.f.py] = 'fixed' in x ? x.fixed : slots[x.at].values[idx[x.at]];
264
+ }
265
+ const cls = mod.globals.get(step.rec.py);
266
+ try { args.push(api.record(cls, row)); } catch (e) { return { refused: explain(asPyErr(e)) }; }
267
+ }
268
+ return { args };
269
+ }
270
+
271
+ const fmtSlot = (s, v) => (v === null ? 'nothing' : s.kind === 'money' ? `$${v}` : s.kind === 'text' ? JSON.stringify(v) : s.kind === 'bool' ? (v ? 'yes' : 'no') : Array.isArray(v) ? `[${v.join(', ')}]` : String(v));
272
+
273
+ /** The inputs a function reads ("order's total", "amount"): shown first in an example. */
274
+ function readSlots(u, slots) {
275
+ const read = new Set();
276
+ const seen = new Set();
277
+ const walk = (x) => {
278
+ if (!x || typeof x !== 'object' || seen.has(x)) return;
279
+ seen.add(x);
280
+ if (Array.isArray(x)) { for (const y of x) walk(y); return; }
281
+ if (x.k === 'field' && x.obj?.ref?.kind === 'param') read.add(`${x.obj.text}'s ${x.name}`);
282
+ if (x.k === 'name' && x.ref?.kind === 'param') read.add(x.text);
283
+ for (const [k, v] of Object.entries(x)) if (!SKIP_KEYS.has(k)) walk(v);
284
+ };
285
+ walk(u.node.body);
286
+ return slots.map((sl, i) => (read.has(sl.label) ? i : -1)).filter((i) => i >= 0);
287
+ }
288
+
289
+ /** Run a function before and after on the same inputs. Gives { tried, unknown, changed, groups } or { why } when it isn't run. */
290
+ function compareRuns(A, B, a, b, lit, until = Infinity) {
291
+ for (const [s, u] of [[A, a], [B, b]]) {
292
+ const r = reach(s, u.id);
293
+ if ([...r].some((d) => d.startsWith('store:'))) return { why: 'it reads or changes saved data (a stored list), so it is not run here' };
294
+ if (r.has('http')) return { why: 'it calls another service, so it is not run here' };
295
+ if (engineOf(s).failed) return { why: `the ${s === A ? 'old' : 'new'} version has problems, so it can't be run` };
296
+ }
297
+ const sig = (u) => u.node.params.map((p) => JSON.stringify(p.type, ['k', 'of', 'name'])).join('|');
298
+ if (sig(a) !== sig(b)) return { why: 'its inputs changed, so the two versions take different values' };
299
+ const made = slotsFor(b.node.params, recordsInfoOf(b), lit);
300
+ if (made.why) return { why: made.why };
301
+ const madeA = slotsFor(a.node.params, recordsInfoOf(a), lit);
302
+ if (madeA.why) return { why: madeA.why };
303
+ const { slots, plan } = made;
304
+ const inputs = inputsFor(slots, b.id);
305
+ const apiA = engineOf(A), apiB = engineOf(B), modA = modOf(A, a), modB = modOf(B, b);
306
+ let unknown = 0, stopped = false;
307
+ const done = []; // [idx, group key or null (the same answer)]
308
+ const groups = new Map();
309
+ const deadline = Math.min(until, Date.now() + MS_PER_FUNCTION);
310
+ for (const idx of inputs) {
311
+ if (Date.now() > deadline) { stopped = true; break; }
312
+ const ga = argsFor(apiA, modA, madeA.plan, slots, idx), gb = argsFor(apiB, modB, plan, slots, idx);
313
+ if (ga.refused && gb.refused) continue;
314
+ const oa = ga.refused ? { key: `refused:${ga.refused}`, label: `not allowed (${ga.refused})`, group: 'not allowed' } : outcome(() => apiA.call(modA, a.node, ga.args));
315
+ const ob = gb.refused ? { key: `refused:${gb.refused}`, label: `not allowed (${gb.refused})`, group: 'not allowed' } : outcome(() => apiB.call(modB, b.node, gb.args));
316
+ if (oa.unknown || ob.unknown) { unknown++; continue; }
317
+ if (oa.key === ob.key) { done.push([idx, null]); continue; }
318
+ const d = difference(oa, ob);
319
+ if (!groups.has(d.key)) groups.set(d.key, { says: d.says, otherKind: !!d.otherKind, inputs: [] });
320
+ groups.get(d.key).inputs.push(idx);
321
+ done.push([idx, d.key]);
322
+ }
323
+ const read = readSlots(b, slots);
324
+ // Another kind of answer first (approved -> review), then changed fields; the most inputs first within each.
325
+ const list = [...groups.entries()].sort((x, y) => (y[1].otherKind - x[1].otherKind) || y[1].inputs.length - x[1].inputs.length).map(([key, g]) => ({ says: g.says, ...describeGroup(key, g, slots, done, read) }));
326
+ return { tried: done.length, unknown, stopped, changed: list.reduce((n, g) => n + g.count, 0), groups: list };
327
+ }
328
+
329
+ /**
330
+ * Where a group of changed answers happens. An input decides it when, with every other input held still, the
331
+ * changed answers are one unbroken run of its values with unchanged answers on at least one side; the run seen
332
+ * most often is given as the range tried ("amount is from $50.00 to $99.99"). And one example.
333
+ */
334
+ function describeGroup(key, g, slots, done, read) {
335
+ let best = null;
336
+ slots.forEach((s, si) => {
337
+ if (!['money', 'whole', 'number'].includes(s.kind)) return;
338
+ const lines = new Map();
339
+ for (const [idx, k] of done) {
340
+ const lineKey = idx.filter((_, i) => i !== si).join(',');
341
+ if (!lines.has(lineKey)) lines.set(lineKey, []);
342
+ lines.get(lineKey).push([idx[si], k === key]);
343
+ }
344
+ const runs = new Map();
345
+ for (const pts of lines.values()) {
346
+ if (pts.length < 3 || !pts.some((x) => x[1])) continue;
347
+ pts.sort((x, y) => x[0] - y[0]);
348
+ const inside = pts.map((x, i) => (x[1] ? i : -1)).filter((i) => i >= 0);
349
+ const lo = inside[0], hi = inside[inside.length - 1];
350
+ if (hi - lo + 1 !== inside.length || (lo === 0 && hi === pts.length - 1)) continue; // broken up, or the whole line
351
+ // open: the run reaches the lowest (or highest) value tried on its line, so it may go on past it.
352
+ const k = [pts[lo][0], pts[hi][0], lo === 0 ? 1 : 0, hi === pts.length - 1 ? 1 : 0, inside.length].join(' ');
353
+ runs.set(k, (runs.get(k) ?? 0) + 1);
354
+ }
355
+ const [top, n] = [...runs.entries()].sort((x, y) => y[1] - x[1])[0] ?? [];
356
+ if (!top) return;
357
+ const [lo, hi, openLo, openHi, width] = top.split(' ').map(Number);
358
+ // The input that explains the most: the widest run of values, then the run seen on the most lines.
359
+ if (!best || width > best.width || (width === best.width && n > best.n)) best = { si, n, lo, hi, openLo, openHi, width };
360
+ });
361
+ const first = g.inputs[0];
362
+ const order = [...new Set([...(best ? [best.si] : []), ...read, ...slots.map((_, i) => i)])];
363
+ const example = order.slice(0, 4).map((i) => `${slots[i].label} ${fmtSlot(slots[i], slots[i].values[first[i]])}`).join(', ');
364
+ let where = null;
365
+ if (best) {
366
+ const s = slots[best.si];
367
+ const lo = fmtSlot(s, s.values[best.lo]), hi = fmtSlot(s, s.values[best.hi]);
368
+ where = best.openHi && !best.openLo ? `${s.label} is ${lo} or more` : best.openLo && !best.openHi ? `${s.label} is ${hi} or less`
369
+ : lo === hi ? `${s.label} is ${lo}` : `${s.label} is from ${lo} to ${hi}`;
370
+ }
371
+ return { count: g.inputs.length, where, example };
372
+ }
373
+
374
+ function behaviourWords(run) {
375
+ if (run.why) return `Not run: ${run.why}.`;
376
+ const tried = `${run.tried} input${run.tried === 1 ? '' : 's'} tried`;
377
+ const notDone = [run.unknown ? `${run.unknown} more did not finish within the step limit` : '', run.stopped ? 'stopped there to stay within the time limit' : ''].filter(Boolean).map((x) => ` (${x})`).join('');
378
+ if (!run.changed) return `The same answer before and after on all ${tried}${notDone}.`;
379
+ const shown = run.groups.slice(0, MAX_SHOWN_GROUPS).map((g) => `${g.says}${g.where ? ` when ${g.where}` : ''} (${g.count} input${g.count === 1 ? '' : 's'}; for example ${g.example})`);
380
+ const more = run.groups.length > MAX_SHOWN_GROUPS ? `; and ${run.groups.length - MAX_SHOWN_GROUPS} more kinds of change` : '';
381
+ return `On ${tried}, ${run.changed} answer${run.changed === 1 ? '' : 's'} changed${notDone}: ${shown.join('; ')}${more}.`;
382
+ }
383
+
384
+ /** Run a test on one side: { passed, problem }, or null when it can't run. */
385
+ function runTest(s, u) {
386
+ const api = engineOf(s);
387
+ if (api.failed) return null;
388
+ const mod = modOf(s, u);
389
+ try { api.test(mod, u.node); return { passed: true }; } catch (e) {
390
+ if (e instanceof OutOfSteps) return null;
391
+ return { passed: false, problem: explain(asPyErr(e)) };
392
+ }
393
+ }
394
+
395
+ // ── The comparison ─────────────────────────────────────────────────────────────────────────────────────────────
396
+
397
+ const whereOf = (u) => ({ file: u.file, line: u.line });
398
+ const ref = (s, id) => { const u = s.units.get(id); return u ? { id, subject: u.subject, kind: u.kind, ...whereOf(u) } : null; };
399
+
400
+ /**
401
+ * What changed between two versions of a Thunder program, rule by rule (thunder-core-changes-v1):
402
+ * { schema, files, changes: [{ id, kind, subject, change, severity, file, line, says, before, after, behaviour?,
403
+ * through?, affects: [{ id, subject, kind, file, line, via, test? }] }], unchanged, problems }.
404
+ * change: added | removed | renamed | changed | affected (its own steps are the same, but something it uses changed)
405
+ * | not-compiled. severity: risk | meaning, as in thunder review. Only spacing changed: counted as unchanged.
406
+ */
407
+ export function coreChanges(oldFiles, newFiles) {
408
+ const A = side(oldFiles), B = side(newFiles);
409
+ const lit = literals([A, B]);
410
+ const changes = [];
411
+ // While a src/ file has problems, the tests that use it would only repeat them as names they can't find.
412
+ const srcBroken = B.results.some((r) => r.kind === 'src' && !r.ok);
413
+ const problems = B.results.filter((r) => !r.ok && !(srcBroken && r.kind === 'test')).map((r) => ({ file: r.path, diagnostics: (r.diagnostics ?? []).filter((d) => d.severity !== 'warning').map((d) => ({ line: d.line, code: d.code, message: d.message })) }));
414
+ for (const p of problems) {
415
+ const d = p.diagnostics[0];
416
+ changes.push({ id: `file:${p.file}`, kind: 'file', subject: p.file, change: 'not-compiled', severity: 'risk', file: p.file, line: d?.line ?? 1, before: null, after: null, affects: [],
417
+ says: `The new version has ${p.diagnostics.length} problem${p.diagnostics.length === 1 ? '' : 's'} (${d ? `line ${d.line}: ${d.message}` : 'it does not compile'}), so its behaviour can't be compared: fix ${p.diagnostics.length === 1 ? 'it' : 'them'} first.` });
418
+ }
419
+ const direct = new Set(); // new-side ids that changed themselves (or were added)
420
+ let unchanged = 0;
421
+ const entries = [];
422
+ for (const [a, b] of pair(A, B)) {
423
+ if (a && b && a.id === b.id && sameText(a.text, b.text)) { unchanged++; continue; }
424
+ if (a && b) { direct.add(b.id); entries.push({ a, b, change: a.id === b.id ? 'changed' : 'renamed' }); continue; }
425
+ if (b) { direct.add(b.id); entries.push({ a: null, b, change: 'added' }); continue; }
426
+ entries.push({ a, b: null, change: 'removed' });
427
+ }
428
+ // What depends on each change, on the new side (for a removed rule, what used it on the old side).
429
+ const affectsOf = (id, s) => [...dependents(s, new Set([id]))].map(([d, chain]) => ({ ...ref(s, d), via: chain.slice(1).map((x) => s.units.get(x)?.subject ?? x) }));
430
+ const runs = new Map();
431
+ const until = Date.now() + MS_IN_ALL;
432
+ const runOf = (a, b) => {
433
+ if (!runs.has(b.id)) runs.set(b.id, Date.now() > until ? { why: 'the comparison reached its time limit before this function' } : compareRuns(A, B, a, b, lit, until));
434
+ return runs.get(b.id);
435
+ };
436
+ for (const { a, b, change } of entries) {
437
+ const u = b ?? a;
438
+ const s = b ? B : A;
439
+ const affects = affectsOf(u.id, s);
440
+ let severity = 'meaning';
441
+ let says;
442
+ const kw = KIND_WORD[u.kind];
443
+ if (change === 'added') says = `New ${kw}${u.kind === 'never' ? `: values it refuses are no longer allowed` : ''}.`;
444
+ else if (change === 'removed') {
445
+ says = u.kind === 'never' ? `${u.record.text} no longer has this rule, so values it refused are now allowed.` : `Removed ${kw}.`;
446
+ if (u.kind === 'never' || u.kind === 'test' || affects.length) severity = 'risk';
447
+ if (affects.length && u.kind !== 'never') says += ` It was used by ${affects.slice(0, 3).map((x) => x.subject).join(', ')}${affects.length > 3 ? `, and ${affects.length - 3} more` : ''}.`;
448
+ } else if (change === 'renamed') says = `Renamed from ${a.subject}, with the same steps.`;
449
+ else if (u.kind === 'keep') { const value = (x) => x.text.join(' ').trim().replace(/^Keep\s+/i, '').replace(new RegExp(`^${x.node.text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s+(at|as|to)\\s+`, 'i'), ''); says = `Now ${value(b)} (was ${value(a)}).`; }
450
+ else if (u.kind === 'never') says = `The rule changed: "${a.node.text}" is now "${b.node.text}".`;
451
+ else if (u.kind === 'record') says = recordWords(a, b);
452
+ else says = 'Its steps changed.';
453
+ const entry = { id: u.id, kind: u.kind, subject: u.subject, change, severity, file: u.file, line: u.line, before: a?.text ?? null, after: b?.text ?? null, says, affects };
454
+ if ((change === 'changed' || change === 'renamed') && u.kind === 'function') {
455
+ const run = runOf(a, b);
456
+ entry.behaviour = run;
457
+ entry.says = `${says} ${behaviourWords(run)}`;
458
+ }
459
+ changes.push(entry);
460
+ }
461
+ // Functions whose own steps are the same, but which use something that changed: run them too.
462
+ const reached = dependents(B, direct);
463
+ for (const [id, chain] of reached) {
464
+ const b = B.units.get(id), a = A.units.get(id);
465
+ if (!a || b.kind !== 'function') continue;
466
+ const run = runOf(a, b);
467
+ if (!run.why && !run.changed) continue; // the same answers: it stays in the "look again" list of what changed
468
+ const through = chain.map((x) => B.units.get(x)?.subject ?? x);
469
+ changes.push({ id, kind: 'function', subject: b.subject, change: 'affected', severity: 'meaning', file: b.file, line: b.line, before: null, after: null, through,
470
+ says: `Its own steps are the same, but it uses ${through.slice().reverse().join(', which uses ')}, which changed. ${behaviourWords(run)}`, behaviour: run, affects: affectsOf(id, B) });
471
+ }
472
+ // Tests that reach a change: run before and after.
473
+ const touched = new Set([...direct, ...reached.keys()]);
474
+ for (const [id, u] of B.units) {
475
+ if (u.kind !== 'test' || !touched.has(id) || !A.units.has(id)) continue;
476
+ const before = runTest(A, A.units.get(id)), after = runTest(B, u);
477
+ if (!before || !after) continue;
478
+ const entry = changes.find((c) => c.id === id);
479
+ if (before.passed && !after.passed) {
480
+ if (entry) Object.assign(entry, { severity: 'risk', says: `${entry.says} It passed before and fails now: ${after.problem}` });
481
+ else changes.push({ id, kind: 'test', subject: u.subject, change: 'affected', severity: 'risk', file: u.file, line: u.line, before: null, after: null, affects: [], says: `Passed before and fails now: ${after.problem}` });
482
+ } else if (!before.passed && after.passed) {
483
+ if (entry) entry.says = `${entry.says} It failed before and passes now.`;
484
+ else changes.push({ id, kind: 'test', subject: u.subject, change: 'affected', severity: 'meaning', file: u.file, line: u.line, before: null, after: null, affects: [], says: `Failed before (${before.problem}) and passes now.` });
485
+ }
486
+ for (const c of changes) for (const x of c.affects ?? []) if (x.id === id) x.test = after.passed ? 'passes' : 'fails';
487
+ }
488
+ const order = { risk: 0, meaning: 1 };
489
+ changes.sort((x, y) => order[x.severity] - order[y.severity] || byText(String(x.file), String(y.file)) || x.line - y.line);
490
+ return { schema: CORE_CHANGES_SCHEMA, files: [...new Set([...A.files, ...B.files].map((f) => f.path))], changes, unchanged, problems };
491
+ }
492
+
493
+ function recordWords(a, b) {
494
+ const fa = new Map(a.node.fields.map((f) => [f.name, f])), fb = new Map(b.node.fields.map((f) => [f.name, f]));
495
+ const kind = (f) => JSON.stringify(f.type, ['k', 'of', 'name']);
496
+ const parts = [];
497
+ const added = [...fb.keys()].filter((k) => !fa.has(k) && k !== 'which'), removed = [...fa.keys()].filter((k) => !fb.has(k) && k !== 'which');
498
+ const changed = [...fb.keys()].filter((k) => fa.has(k) && kind(fa.get(k)) !== kind(fb.get(k)));
499
+ if (added.length) parts.push(`new field${added.length === 1 ? '' : 's'} ${added.map((k) => fb.get(k).text).join(', ')}`);
500
+ if (removed.length) parts.push(`field${removed.length === 1 ? '' : 's'} ${removed.map((k) => fa.get(k).text).join(', ')} removed`);
501
+ if (changed.length) parts.push(`${changed.map((k) => fb.get(k).text).join(', ')} changed kind`);
502
+ return parts.length ? `${parts.join('; ')}.`.replace(/^./, (c) => c.toUpperCase()) : 'Its fields changed.';
503
+ }
504
+
505
+ // ── affectedBy ─────────────────────────────────────────────────────────────────────────────────────────────────
506
+
507
+ /** A rule named the way a person would: its id, its subject ("decide refund", "POST /orders"), or a kept value's name. */
508
+ function resolve(s, name) {
509
+ if (s.units.has(name)) return [name];
510
+ const want = String(name).trim().toLowerCase();
511
+ return [...s.units.values()].filter((u) => u.subject.toLowerCase() === want || u.id.slice(u.id.indexOf(':') + 1).toLowerCase() === want).map((u) => u.id);
512
+ }
513
+
514
+ /**
515
+ * What to look at again when `change` changes (thunder-affected-v1): the functions and endpoints that use it, all
516
+ * the way up; the tests and the examples (Expect lines) that reach it; the Never rules and stored lists those
517
+ * functions rely on. `change` is a rule's id or name ("decide refund", "keep:review limit"), or a list of them.
518
+ * Each item cites its file and line and says how it is reached (via).
519
+ */
520
+ export function affectedBy(files, change) {
521
+ const s = side(files);
522
+ const names = Array.isArray(change) ? change : [change];
523
+ const roots = new Set();
524
+ const unknown = [];
525
+ for (const n of names) { const ids = resolve(s, n); if (ids.length) ids.forEach((id) => roots.add(id)); else unknown.push(String(n)); }
526
+ const via = dependents(s, roots);
527
+ const list = (kind) => [...via].filter(([id]) => s.units.get(id)?.kind === kind).map(([id, chain]) => ({ ...ref(s, id), via: chain.map((x) => s.units.get(x)?.subject ?? x) }));
528
+ const reachedIds = new Set([...roots, ...via.keys()]);
529
+ // Examples: each Expect line in an affected test that itself reaches a changed or affected rule.
530
+ const examples = [];
531
+ for (const [id] of via) {
532
+ const u = s.units.get(id);
533
+ if (u.kind !== 'test') continue;
534
+ for (const st of u.node.body ?? []) {
535
+ if (st.k !== 'expect') continue;
536
+ const uses = usesOf({ id: '', kind: 'expect', node: st }, s.units, s.records);
537
+ const hit = [...uses].find((d) => reachedIds.has(d));
538
+ if (hit) examples.push({ file: u.file, line: st.line, test: u.subject, says: st.raw ?? null, reaches: s.units.get(hit)?.subject ?? hit });
539
+ }
540
+ }
541
+ // The Never rules and stored lists the affected functions and endpoints rely on (not the tests: they only check).
542
+ const relied = new Map();
543
+ for (const id of reachedIds) for (const d of s.units.get(id)?.kind === 'test' ? [] : s.units.get(id)?.uses ?? []) {
544
+ const k = s.units.get(d)?.kind;
545
+ if ((k === 'never' || k === 'store') && !relied.has(d)) relied.set(d, { ...ref(s, d), usedBy: s.units.get(id).subject });
546
+ }
547
+ return {
548
+ schema: AFFECTED_SCHEMA,
549
+ of: [...roots].map((id) => ref(s, id)),
550
+ unknown,
551
+ functions: list('function'),
552
+ endpoints: list('endpoint'),
553
+ tests: list('test'),
554
+ examples,
555
+ rules: [...relied.values()].filter((x) => x.kind === 'never'),
556
+ stored: [...relied.values()].filter((x) => x.kind === 'store'),
557
+ };
558
+ }
559
+
560
+ /** affectedBy's answer as text for a terminal. */
561
+ export function renderAffected(r) {
562
+ const out = [];
563
+ for (const n of r.unknown) out.push(`No rule called "${n}" in these files. Name a function, endpoint ("POST /orders"), kept value, data type, stored list, or test.`);
564
+ if (!r.of.length) return out.join('\n');
565
+ out.push(`What to look at again if ${r.of.map((x) => `${x.subject} (${x.file}:${x.line})`).join(' and ')} change${r.of.length === 1 ? 's' : ''}:`);
566
+ // via starts at the rule that changes; the rules after it are the ones in between, nearest last.
567
+ const through = (x) => (x.via?.length > 1 ? ` (through ${x.via.slice(1).reverse().join(', ')})` : '');
568
+ const section = (title, list, fmt) => { if (list.length) out.push('', title, ...list.map(fmt)); };
569
+ section('Functions that use it', r.functions, (x) => ` ${x.subject} ${x.file}:${x.line}${through(x)}`);
570
+ section('Endpoints', r.endpoints, (x) => ` ${x.subject} ${x.file}:${x.line}${through(x)}`);
571
+ section('Tests', r.tests, (x) => ` ${x.subject} ${x.file}:${x.line}${through(x)}`);
572
+ section('Examples (Expect lines) that reach it', r.examples, (x) => ` ${x.file}:${x.line} ${x.says ?? ''}`);
573
+ section('Never rules they rely on', r.rules, (x) => ` ${x.subject} ${x.file}:${x.line} (used by ${x.usedBy})`);
574
+ section('Stored lists they use', r.stored, (x) => ` ${x.subject.replace(/^stored list /, '')} ${x.file}:${x.line} (used by ${x.usedBy})`);
575
+ if (!r.functions.length && !r.endpoints.length && !r.tests.length) out.push('', 'Nothing else in these files uses it.');
576
+ return out.join('\n');
577
+ }
578
+
579
+ /** One line for a change, as short as it can be said: its changed answers, or its first sentence. */
580
+ function shortWords(c) {
581
+ const run = c.behaviour;
582
+ if (run && !run.why && run.changed) return `${c.subject}: ${run.groups.slice(0, 2).map((g) => `${g.says}${g.where ? ` when ${g.where}` : ''}`).join('; ')} (on ${run.tried} inputs tried)`;
583
+ return `${c.subject}: ${c.says.split(/(?<=\.)\s/)[0]}`;
584
+ }
585
+
586
+ /**
587
+ * Thunder Trace impact with what changes in the answers of a changed Thunder Core endpoint (part 2 of roadmap 3.4):
588
+ * each route finding whose endpoint a Core change reaches gets `behaviour`: [{ id, subject, says, file, line }], the
589
+ * changes that reach it, said shortly. `byRepo`: Map(repository name -> coreChanges result). Pure.
590
+ */
591
+ export function withCoreBehaviour(impact, byRepo) {
592
+ let used = false;
593
+ const findings = impact.findings.map((f) => {
594
+ const cc = byRepo.get(f.at?.repo);
595
+ if (!cc || !String(f.at?.member ?? '').startsWith('endpoint:') || !/^route-/.test(f.kind)) return f;
596
+ const id = f.at.member;
597
+ const reaching = cc.changes.filter((c) => c.change !== 'not-compiled' && c.kind !== 'test' && (c.id === id || (c.affects ?? []).some((x) => x.id === id)));
598
+ if (!reaching.length) return f;
599
+ used = true;
600
+ return { ...f, behaviour: reaching.map((c) => ({ id: c.id, subject: c.subject, says: shortWords(c), file: c.file, line: c.line })) };
601
+ });
602
+ return used ? { ...impact, findings, note: `${String(impact.note).replace(' (no code was run)', '')} Thunder Core programs were run before and after, on the Thunder engine (no files, network, or saved data), to say what changes in their answers: tested on the inputs tried, not proven.` } : impact;
603
+ }