@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
@@ -0,0 +1,465 @@
1
+ // Proof by running: run real code, record what actually happened, and compare it with the flow Thunder drew.
2
+ //
3
+ // A reading is checked by sampling and by its own self-checks (the faithfulness gate). Running the code turns
4
+ // "carefully read" into "shown to be right": the recorders in ./runners (Python: sys.monitoring and `ast`; JavaScript:
5
+ // V8's debugger) note, for every question the code reached, where it went next, and how each call ended. Here that
6
+ // record meets Thunder's flow:
7
+ //
8
+ // * a question: when the code's condition held, the side Thunder says it takes then (Yes, or No for a question asked
9
+ // the positive way round of a negated condition: node.whenTrue) must hold the next step the run reached; when it
10
+ // did not hold, the other side (or carrying straight on, when Thunder shows nothing there) must;
11
+ // * a loop: entering it must reach its "For each" steps, and leaving it must not;
12
+ // * a case, an error handler: the run's case or handler must hold the step that ran;
13
+ // * an ending: a `return` line must be one of Thunder's endings (and a rule's answer must be the value given back);
14
+ // a `raise` / `throw` line must be a Stop, of the error Thunder names; reaching the end of a function without
15
+ // returning needs a "Done" ending.
16
+ //
17
+ // Each member is then **executed** (ran, and every claim the run reached matched), **contradicted** (some claim did
18
+ // not: each mismatch says which question, which side, which line), **not checked** (ran, but reached nothing Thunder
19
+ // claims), or **not run**. Only "executed" is written into the model (member.completeness.level), and only by a run.
20
+ // Node-only (child processes); the comparison itself, compareRun, is pure.
21
+ import { spawnSync } from 'node:child_process';
22
+ import { mkdtempSync, readdirSync, readFileSync, rmSync, existsSync, statSync, realpathSync } from 'node:fs';
23
+ import { tmpdir } from 'node:os';
24
+ import { join, dirname } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ import { collectReadableFiles } from './read-repo-fs.mjs';
27
+ import { thunderModel } from './model.mjs';
28
+
29
+ export const EXECUTED_SCHEMA = 'thunder-executed-v1';
30
+ const HERE = dirname(fileURLToPath(import.meta.url));
31
+ export const PY_TRACER = join(HERE, 'runners', 'thunder_trace.py');
32
+ export const JS_TRACER = join(HERE, 'runners', 'thunder-trace.cjs');
33
+ const JS_GENERATE = join(HERE, 'runners', 'thunder-generate.mjs');
34
+ const TEST_PATH = /(^|\/)(test|tests|testing|__tests__|spec|specs|fixtures?)\/|(^|\/)test_[^/]*\.py$|_test\.py$|(^|\/)conftest\.py$|\.(test|spec)\.[cm]?[jt]sx?$/;
35
+ const LANGS = { python: ['python'], js: ['javascript', 'typescript'] };
36
+
37
+ // ── Reading the flow ─────────────────────────────────────────────────────────────────────────────────────
38
+
39
+ /** Every block in a flow by its node id, and the node ids under each block (its sides, body, cases, handlers). */
40
+ function indexFlow(flow) {
41
+ const block = new Map();
42
+ const walk = (blocks) => {
43
+ for (const b of blocks || []) {
44
+ block.set(b.id, b);
45
+ walk(b.yes); walk(b.no); walk(b.each); walk(b.body);
46
+ for (const c of b.cases || []) walk(c.blocks);
47
+ for (const h of b.handlers || []) { block.set(h.id, h); walk(h.blocks); }
48
+ if (b.always) { block.set(b.always.id, b.always); walk(b.always.blocks); }
49
+ }
50
+ };
51
+ walk(flow.blocks);
52
+ return block;
53
+ }
54
+
55
+ /** The node ids in a list of blocks, at any depth. */
56
+ function idsIn(blocks, out = new Set()) {
57
+ for (const b of blocks || []) {
58
+ out.add(b.id);
59
+ idsIn(b.yes, out); idsIn(b.no, out); idsIn(b.each, out); idsIn(b.body, out);
60
+ for (const c of b.cases || []) idsIn(c.blocks, out);
61
+ for (const h of b.handlers || []) { out.add(h.id); idsIn(h.blocks, out); }
62
+ if (b.always) { out.add(b.always.id); idsIn(b.always.blocks, out); }
63
+ }
64
+ return out;
65
+ }
66
+
67
+ const firstText = (flow, blocks) => { const n = blocks?.length ? flow.nodes.find((x) => x.id === blocks[0].id) : null; return n ? `"${String(n.text).slice(0, 70)}"${n.line ? ` (line ${n.line})` : ''}` : 'nothing (it carries on)'; };
68
+ const sideName = (s) => (s === 'yes' ? 'Yes' : s === 'no' ? 'No' : s);
69
+
70
+ /**
71
+ * Compare a run's record with the model. `trace` is { files: { path: { functions, decisions, returns } } } as the
72
+ * recorders write it. `languages` limits which members are judged (others are left out of the result).
73
+ */
74
+ export function compareRun(model, trace, { languages = null } = {}) {
75
+ const members = [];
76
+ for (const m of model.members) {
77
+ if (languages && !languages.includes(m.language)) continue;
78
+ const t = trace.files?.[m.file];
79
+ members.push(judgeMember(m, t, model));
80
+ }
81
+ const count = (s) => members.filter((x) => x.status === s).length;
82
+ const questions = members.reduce((a, x) => a + x.questions.drawn, 0);
83
+ const checked = members.reduce((a, x) => a + x.questions.checked, 0);
84
+ const summary = {
85
+ members: members.length, run: members.filter((x) => x.status !== 'not run').length,
86
+ executed: count('executed'), contradicted: count('contradicted'), notChecked: count('not checked'), notRun: count('not run'),
87
+ questions, questionsChecked: checked,
88
+ claims: { matched: members.reduce((a, x) => a + x.matched, 0), mismatched: members.reduce((a, x) => a + x.mismatches.length, 0), notDrawn: members.reduce((a, x) => a + x.notDrawn, 0) },
89
+ };
90
+ return { schema: EXECUTED_SCHEMA, members, summary };
91
+ }
92
+
93
+ function functionFor(m, t) {
94
+ if (!t) return null;
95
+ const fns = t.functions || {};
96
+ if (fns[m.lines[0]]) return fns[m.lines[0]];
97
+ // A recorder may place a function where its header starts (a decorator, a multi-line signature): the nearest
98
+ // function line at or after the member's first line, inside its lines.
99
+ const near = Object.keys(fns).map(Number).filter((l) => l >= m.lines[0] && l <= Math.min(m.lines[1], m.lines[0] + 3)).sort((a, b) => a - b)[0];
100
+ return near != null ? fns[near] : null;
101
+ }
102
+
103
+ function judgeMember(m, t, model) {
104
+ const flow = m.flow;
105
+ const byId = new Map(flow.nodes.map((n) => [n.id, n]));
106
+ const block = indexFlow(flow);
107
+ const fn = functionFor(m, t);
108
+ const encl = t?.returns || {};
109
+ const runs = fn?.runs ?? 0;
110
+ const decisions = [], mismatches = [];
111
+ let matched = 0, notDrawn = 0;
112
+ const nodesAt = (line) => flow.nodes.filter((n) => n.line === line);
113
+ // A rule's answer is drawn on its question's line; the `return` that gives it is on that line or below it, before the
114
+ // next question. Python's recorder says which `if` / `case` holds each return (encl); otherwise the nearest answer above.
115
+ const answers = flow.nodes.filter((n) => n.kind === 'end' && n.answer && n.line != null);
116
+ const questionLines = flow.nodes.filter((n) => n.kind === 'decision' && n.line != null).map((n) => n.line);
117
+ const answerFor = (R) => {
118
+ if (encl[R] != null) return answers.find((n) => n.line === encl[R]) ?? null;
119
+ const above = answers.filter((n) => n.line <= R).sort((a, b) => b.line - a.line)[0];
120
+ return above && !questionLines.some((q) => q > above.line && q <= R) ? above : null;
121
+ };
122
+ const holds = (ids, N) => N != null && [...ids].some((id) => { const n = byId.get(id); return n && (n.line === N || (n.kind === 'end' && n.answer && answerFor(N) === n)); });
123
+ const outside = (N, ...sets) => N != null && flow.nodes.some((n) => n.line === N && n.kind !== 'start' && !sets.some((s) => s.has(n.id)));
124
+ const lineWords = (N) => (N == null ? 'the end of the function' : `line ${N}`);
125
+ // A line the run reached that the picture leaves out altogether: no node of any member of the file is on it, and no
126
+ // step shown as one piece (code, or a statement drawn without its inside) holds it. Needs the recorder's spans.
127
+ const spans = t?.spans;
128
+ const fileNodes = new Set(model.members.filter((x) => x.file === m.file).flatMap((x) => x.flow.nodes.map((n) => n.line)));
129
+ const parents = new Set();
130
+ for (const b of block.values()) for (const k of ['yes', 'no', 'each', 'body', 'blocks']) if (b[k]?.length) parents.add(b.id);
131
+ for (const b of block.values()) if (b.cases?.some((c) => c.blocks.length) || b.handlers?.length || b.always) parents.add(b.id);
132
+ // (Only code holds lines honestly: a step in words with nothing under it, such as a `with` read as "Calls with",
133
+ // has dropped what is inside it.)
134
+ const dropped = (L) => !!spans && !fileNodes.has(L) && !flow.nodes.some((n) => n.line != null && n.line < L && (spans[n.line] ?? n.line) >= L && !parents.has(n.id) && (n.kind === 'code' || n.code));
135
+ const miss = (x) => { if (!mismatches.some((y) => y.line === x.line && y.side === x.side && y.observed === x.observed)) mismatches.push(x); };
136
+
137
+ // ── Questions, loops, cases, handlers ──
138
+ // (A function inside this one that Thunder draws as its own member — a getter passed to defineProperty, a callback —
139
+ // is judged there, not here.)
140
+ const inner = model.members.filter((x) => x !== m && x.file === m.file && x.lines[0] > m.lines[0] && x.lines[1] <= m.lines[1]);
141
+ const obsAt = new Map(Object.entries(t?.decisions || {}).map(([l, d]) => [Number(l), d]).filter(([l]) => l >= m.lines[0] && l <= m.lines[1] && !inner.some((x) => l >= x.lines[0] && l <= x.lines[1] && !flow.nodes.some((n) => n.line === l))));
142
+ // A `match` Thunder drew as a chain of questions (a rule) is checked question by question: case P taken = the
143
+ // question at line P answered Yes.
144
+ for (const [L, d] of [...obsAt]) {
145
+ if (d.kind !== 'match' || nodesAt(L).some((n) => n.kind === 'decision')) continue;
146
+ for (const [k, c] of Object.entries(d.obs)) {
147
+ const [where, N] = k.split('|');
148
+ const P = where.startsWith('case:') ? Number(where.slice(5)) : null;
149
+ if (P == null || !nodesAt(P).some((n) => n.kind === 'decision')) continue;
150
+ const tgt = obsAt.get(P) || { kind: 'if', obs: {} };
151
+ tgt.obs[`body|${N}`] = (tgt.obs[`body|${N}`] || 0) + c;
152
+ obsAt.set(P, tgt);
153
+ }
154
+ obsAt.delete(L);
155
+ }
156
+ const checkedNodes = new Set();
157
+ for (const [L, d] of obsAt) {
158
+ const here = nodesAt(L);
159
+ const node = d.kind === 'handler' ? here.find((n) => n.handler) : here.find((n) => n.kind === 'decision' && !n.handler) ?? here.find((n) => n.kind === 'loop');
160
+ if (!node) {
161
+ const n = Object.values(d.obs).reduce((a, b) => a + b, 0);
162
+ if (dropped(L)) { miss({ line: L, question: null, side: 'missing', expected: 'Thunder: the picture shows nothing at this line', observed: `the run reached ${d.kind === 'handler' ? 'an error handler' : `a question (${d.kind})`} at line ${L}`, times: n }); decisions.push({ line: L, question: null, kind: d.kind, observed: {}, result: 'contradicted' }); }
163
+ else notDrawn += n;
164
+ continue;
165
+ }
166
+ const b = block.get(node.id) || {};
167
+ const seen = {};
168
+ let ok = 0, bad = 0;
169
+ for (const [k, count] of Object.entries(d.obs)) {
170
+ const [where, nRaw] = k.split('|');
171
+ const N = nRaw === '' ? null : Number(nRaw);
172
+ let verdict, side, expected;
173
+ if (node.kind === 'loop' || (d.kind === 'for' && node.kind !== 'decision')) {
174
+ const each = idsIn(b.each);
175
+ side = where === 'body' ? 'each' : 'done';
176
+ expected = side === 'each' ? `its "For each" steps start with ${firstText(flow, b.each)}` : 'it leaves the loop';
177
+ if (node.kind !== 'loop') verdict = 'mismatch';
178
+ else if (side === 'each') verdict = holds(each, N) ? 'match' : outside(N, each) ? 'mismatch' : 'unclaimed';
179
+ else verdict = holds(each, N) && N !== L ? 'mismatch' : 'match';
180
+ } else if (node.cases) {
181
+ const P = where.startsWith('case:') ? Number(where.slice(5)) : null;
182
+ const all = (b.cases || []).map((c) => ({ c, ids: idsIn(c.blocks) }));
183
+ const mine = P != null ? all.find((x) => x.c.line === P) : null;
184
+ side = mine ? mine.c.label : 'None of these';
185
+ expected = mine ? `the case "${mine.c.label}" starts with ${firstText(flow, mine.c.blocks)}` : 'no case runs';
186
+ if (P == null) verdict = all.some((x) => holds(x.ids, N)) ? 'mismatch' : 'match';
187
+ else if (!mine) verdict = 'unclaimed';
188
+ else if (holds(mine.ids, N)) verdict = 'match';
189
+ else if (all.some((x) => x !== mine && holds(x.ids, N))) verdict = 'mismatch';
190
+ else verdict = !mine.ids.size ? 'match' : outside(N, mine.ids) ? 'mismatch' : 'unclaimed';
191
+ } else if (node.handler) {
192
+ const ids = idsIn(b.blocks);
193
+ side = 'handled';
194
+ expected = `the handler does ${firstText(flow, b.blocks)}`;
195
+ verdict = holds(ids, N) ? 'match' : outside(N, ids) ? 'mismatch' : ids.size ? 'unclaimed' : 'match';
196
+ } else {
197
+ // A question. The side for "the condition held" is node.whenTrue (rules: always Yes).
198
+ const yesWhen = node.whenTrue || 'yes';
199
+ const noWhen = yesWhen === 'yes' ? 'no' : 'yes';
200
+ const held = where === 'body';
201
+ side = held ? yesWhen : noWhen;
202
+ const exp = idsIn(b[side]), other = idsIn(b[held ? noWhen : yesWhen]);
203
+ expected = `the ${sideName(side)} side ${exp.size ? `starts with ${firstText(flow, b[side])}` : 'carries straight on'}`;
204
+ if (holds(other, N) && !holds(exp, N) && N !== L) verdict = 'mismatch';
205
+ else if (holds(exp, N)) verdict = 'match';
206
+ else if (!exp.size) verdict = held || where === 'orelse' ? (outside(N, other) && N !== L ? 'mismatch' : 'unclaimed') : 'match';
207
+ else if (N == null) verdict = where === 'end' ? 'mismatch' : 'unclaimed';
208
+ else verdict = outside(N, exp, other) && N !== L ? 'mismatch' : 'unclaimed';
209
+ }
210
+ seen[sideName(side)] = (seen[sideName(side)] || 0) + count;
211
+ if (verdict === 'match') { ok += count; matched += count; }
212
+ else if (verdict === 'mismatch') {
213
+ bad += count;
214
+ miss({ line: L, question: node.text, side: sideName(side), expected: `Thunder: ${expected}`, observed: `the run went to ${lineWords(N)}${node.kind === 'loop' || node.cases || node.handler ? '' : where === 'body' ? ' (the condition held)' : ' (the condition did not hold)'}`, times: count });
215
+ } else notDrawn += count;
216
+ }
217
+ if (ok || bad) checkedNodes.add(node.id);
218
+ decisions.push({ line: L, question: node.text, kind: d.kind, observed: seen, result: bad ? 'contradicted' : ok ? 'matched' : 'not drawn' });
219
+ }
220
+
221
+ // ── Endings ──
222
+ const endings = [];
223
+ if (fn) {
224
+ for (const [R, e] of Object.entries(fn.returns || {})) {
225
+ const line = Number(R);
226
+ // Every ending drawn for this return (a one-line `return x` read as a yes/no rule has both answers on it).
227
+ const ends = [...new Set([...flow.nodes.filter((n) => n.kind === 'end' && n.line === line), answerFor(line)].filter(Boolean))];
228
+ const end = ends[0];
229
+ const stop = flow.nodes.find((n) => n.kind === 'stop' && n.line === line);
230
+ let result = 'not drawn';
231
+ if (end) {
232
+ result = 'matched';
233
+ // A rule's text answer is kept without its quotes ("big"): it is text when the code returns quoted text there.
234
+ const quoted = /\breturn\s+(["'])/.test(sourceLine(model, m.file, line));
235
+ const wants = ends.map((x) => literal(x.value) ?? (quoted && x.value != null ? String(x.value) : undefined));
236
+ const got = e.values.map(literal);
237
+ if (wants.every((w) => w !== undefined) && e.values.length && got.every((g) => g !== undefined) && got.some((g) => !wants.some((w) => sameValue(g, w)))) {
238
+ result = 'contradicted';
239
+ miss({ line, question: null, side: 'ending', expected: `Thunder: it gives back ${ends.map((x) => x.value).join(' or ')} here`, observed: `the run gave back ${e.values.join(', ')}`, times: e.count });
240
+ }
241
+ } else if (stop) {
242
+ result = 'contradicted';
243
+ miss({ line, question: null, side: 'ending', expected: `Thunder: ${stop.text} (line ${line})`, observed: 'the run returned there', times: e.count });
244
+ }
245
+ if (result === 'not drawn' && dropped(line)) { result = 'contradicted'; miss({ line, question: null, side: 'missing', expected: 'Thunder: the picture shows nothing at this line', observed: 'the run returned there', times: e.count }); }
246
+ if (result === 'matched') matched += e.count; else if (result === 'not drawn') notDrawn += e.count;
247
+ endings.push({ line, kind: 'return', count: e.count, values: e.values, result });
248
+ }
249
+ for (const [R, e] of Object.entries(fn.raises || {})) {
250
+ const line = Number(R);
251
+ const stop = flow.nodes.find((n) => n.kind === 'stop' && n.line === line);
252
+ const other = flow.nodes.find((n) => n.line === line && (n.kind === 'end'));
253
+ let result = 'not drawn';
254
+ if (stop) {
255
+ result = 'matched';
256
+ const named = stopType(stop.text, sourceLine(model, m.file, line));
257
+ const types = Object.entries(e.types);
258
+ // `from .exceptions import SSLError as RequestsSSLError`: the code's name for a class may be an alias.
259
+ const also = named ? aliasesOf(model, m.file, named) : [];
260
+ if (named && types.length && types.some(([, mro]) => !mro.includes(named) && !also.some((a) => mro.includes(a)))) {
261
+ result = 'contradicted';
262
+ miss({ line, question: null, side: 'Stop', expected: `Thunder: it stops with ${named}`, observed: `the run raised ${types.map(([n]) => n).join(', ')}`, times: e.count });
263
+ }
264
+ } else if (other) {
265
+ result = 'contradicted';
266
+ miss({ line, question: null, side: 'ending', expected: `Thunder: ${other.text} (line ${line})`, observed: `the run raised ${Object.keys(e.types).join(', ')} there`, times: e.count });
267
+ }
268
+ if (result === 'not drawn' && dropped(line)) { result = 'contradicted'; miss({ line, question: null, side: 'missing', expected: 'Thunder: the picture shows nothing at this line', observed: `the run raised ${Object.keys(e.types).join(', ')} there`, times: e.count }); }
269
+ if (result === 'matched') matched += e.count; else if (result === 'not drawn') notDrawn += e.count;
270
+ endings.push({ line, kind: 'raise', count: e.count, types: Object.keys(e.types), result });
271
+ }
272
+ if (fn.fellOff) {
273
+ // Reaching the end of the body matches "Done", or an ending drawn on the last line that ran (a web handler's
274
+ // `res.send(…)` is how it answers: Thunder draws it as the ending)
275
+ const done = flow.nodes.find((n) => n.kind === 'end' && n.line == null);
276
+ const lastLines = Object.keys(fn.fellOffAt || {}).map(Number);
277
+ // (or a Stop: Express's `next(err)` hands the error on, and that is how the path ends.)
278
+ const endedThere = lastLines.length && lastLines.every((l) => flow.nodes.some((n) => (n.kind === 'end' || n.kind === 'stop') && n.line === l));
279
+ const ok = !!done || !!endedThere;
280
+ if (ok) matched += fn.fellOff;
281
+ else miss({ line: lastLines[0] ?? m.lines[1], question: null, side: 'ending', expected: 'Thunder: every path ends with an answer or a Stop', observed: `the run reached the end of the function without giving anything back${lastLines.length ? ` (after line ${lastLines.join(', ')})` : ''}`, times: fn.fellOff });
282
+ endings.push({ line: null, kind: 'end of function', count: fn.fellOff, ...(lastLines.length ? { after: lastLines } : {}), result: ok ? 'matched' : 'contradicted' });
283
+ }
284
+ }
285
+
286
+ const drawnQuestions = flow.nodes.filter((n) => (n.kind === 'decision' || n.kind === 'loop') && n.line != null && !n.code);
287
+ const status = runs === 0 && !matched && !mismatches.length ? 'not run' : mismatches.length ? 'contradicted' : matched ? 'executed' : 'not checked';
288
+ return {
289
+ id: m.id, file: m.file, name: m.name, lines: m.lines, language: m.language, status, runs,
290
+ questions: { drawn: drawnQuestions.length, checked: drawnQuestions.filter((n) => checkedNodes.has(n.id)).length },
291
+ matched, notDrawn, decisions, endings, mismatches,
292
+ };
293
+ }
294
+
295
+ function sourceLine(model, file, line) { return model._sources?.get(file)?.[line - 1] ?? ''; }
296
+
297
+ /** The original names a file imports under `name`: `import { A as name }`, `from m import A as name`. */
298
+ function aliasesOf(model, file, name) {
299
+ const text = (model._sources?.get(file) || []).join('\n');
300
+ return [...text.matchAll(new RegExp(`\\b([A-Za-z_$][\\w$]*)\\s+as\\s+${name}\\b`, 'g'))].map((x) => x[1]);
301
+ }
302
+
303
+ /** The error type a Stop names, when the code's own raise / throw line names that type too. */
304
+ function stopType(text, code) {
305
+ const m = String(text).match(/^Stop:\s*([A-Z][A-Za-z0-9_]*)(?=:|\s*$|\s*\()/);
306
+ if (!m) return null;
307
+ return new RegExp(`\\b(?:raise|throw\\s+new|throw)\\s+(?:[\\w.]+\\.)?${m[1]}\\b`).test(code) ? m[1] : null;
308
+ }
309
+
310
+ /** A plain literal as a value: numbers, quoted text, yes/no, nothing. undefined when it is not a literal. */
311
+ function literal(v) {
312
+ const s = String(v ?? '').trim();
313
+ if (v == null || s === '') return undefined;
314
+ if (/^-?\d+(?:\.\d+)?(?:e-?\d+)?$/i.test(s)) return Number(s);
315
+ if (/^(True|true)$/.test(s)) return true;
316
+ if (/^(False|false)$/.test(s)) return false;
317
+ if (/^(None|null|nil)$/.test(s)) return null;
318
+ if (s === 'undefined') return 'undefined';
319
+ const q = s.match(/^(["'])((?:\\.|(?!\1).)*)\1$/);
320
+ if (q) { try { return JSON.parse(`"${q[2].replace(/\\'/g, "'").replace(/"/g, '\\"')}"`); } catch { return q[2]; } }
321
+ return undefined;
322
+ }
323
+ const sameValue = (a, b) => (typeof a === 'number' && typeof b === 'number' ? Math.abs(a - b) < 1e-9 : a === b);
324
+
325
+ /** Write "executed" into the model for every member a run proved, with the reason. Returns the model. */
326
+ export function markExecuted(model, result) {
327
+ const byId = new Map(result.members.map((r) => [r.id, r]));
328
+ for (const m of model.members) {
329
+ const r = byId.get(m.id);
330
+ if (!r || r.status !== 'executed') continue;
331
+ m.completeness = { level: 'executed', reasons: [`Ran ${r.runs} time${r.runs === 1 ? '' : 's'}; every question and ending the runs reached matched this flow (${r.questions.checked} of ${r.questions.drawn} questions checked).`] };
332
+ }
333
+ return model;
334
+ }
335
+
336
+ // ── Running ──────────────────────────────────────────────────────────────────────────────────────────────
337
+
338
+ /** Add one record into another (counts add up; values are kept once). */
339
+ export function mergeTraces(into, add) {
340
+ into.files ||= {};
341
+ for (const [file, f] of Object.entries(add.files || {})) {
342
+ const t = (into.files[file] ||= { functions: {}, decisions: {}, returns: {} });
343
+ Object.assign(t.returns, f.returns || {});
344
+ if (f.spans) t.spans = { ...(t.spans || {}), ...f.spans };
345
+ for (const [l, d] of Object.entries(f.decisions || {})) {
346
+ const x = (t.decisions[l] ||= { kind: d.kind, obs: {} });
347
+ for (const [k, c] of Object.entries(d.obs)) x.obs[k] = (x.obs[k] || 0) + c;
348
+ }
349
+ for (const [l, fn] of Object.entries(f.functions || {})) {
350
+ const x = (t.functions[l] ||= { runs: 0, returns: {}, raises: {}, fellOff: 0, unwound: 0 });
351
+ x.runs += fn.runs; x.fellOff += fn.fellOff || 0; x.unwound += fn.unwound || 0;
352
+ for (const [l, c] of Object.entries(fn.fellOffAt || {})) (x.fellOffAt ||= {})[l] = (x.fellOffAt[l] || 0) + c;
353
+ for (const [r, e] of Object.entries(fn.returns || {})) { const y = (x.returns[r] ||= { count: 0, values: [] }); y.count += e.count; for (const v of e.values) if (!y.values.includes(v) && y.values.length < 6) y.values.push(v); }
354
+ for (const [r, e] of Object.entries(fn.raises || {})) { const y = (x.raises[r] ||= { count: 0, types: {} }); y.count += e.count; Object.assign(y.types, e.types); }
355
+ }
356
+ }
357
+ (into.runs ||= []).push(...(add.runs || []));
358
+ return into;
359
+ }
360
+
361
+ const scratch = () => mkdtempSync(join(tmpdir(), 'thunder-run-'));
362
+
363
+ /**
364
+ * Run Python code under the recorder. mode: 'generate' (made-up inputs for functions that look free of side
365
+ * effects), 'discover' (call test_* functions under `tests`), or 'pytest' (pytest in the same process; it must be
366
+ * installed for `python`). Returns a record with `runs: [{ how, ... }]`.
367
+ */
368
+ export function runPython(root, { mode = 'generate', tests, pytestArgs = [], python = 'python3', maxSeconds = 120, maxCalls = 200, cwd } = {}) {
369
+ const dir = scratch();
370
+ const out = join(dir, 'trace.json');
371
+ const args = ['-I', '-B', PY_TRACER, '--root', root, '--out', out, '--max-seconds', String(maxSeconds), '--max-calls', String(maxCalls)];
372
+ if (mode === 'generate') args.push('--generate');
373
+ else if (mode === 'discover') args.push('--discover', tests);
374
+ else args.push('--pytest', '--', ...pytestArgs);
375
+ const began = Date.now();
376
+ // Generated inputs and test discovery run from a scratch folder, so nothing in the code's folder is picked up by
377
+ // accident; pytest runs in the code's folder so its configuration applies.
378
+ const r = spawnSync(python, args, { cwd: mode === 'pytest' ? cwd || root : dir, encoding: 'utf8', timeout: (maxSeconds + 60) * 1000, maxBuffer: 64 * 1024 * 1024 });
379
+ let trace = { files: {}, meta: {} };
380
+ try { trace = JSON.parse(readFileSync(out, 'utf8')); } catch { trace.meta = { errors: [`The Python recorder did not finish: ${(r.error?.message || r.stderr || '').slice(-400)}`] }; }
381
+ rmSync(dir, { recursive: true, force: true });
382
+ trace.runs = [{ how: mode === 'generate' ? 'generated inputs' : mode === 'discover' ? `test functions in ${tests}` : `pytest ${pytestArgs.join(' ')}`.trim(), language: 'python', seconds: (Date.now() - began) / 1000, ...trace.meta, exit: r.status }];
383
+ return trace;
384
+ }
385
+
386
+ /**
387
+ * Run JavaScript under the recorder: `command` (a shell command, e.g. the project's test runner, run in the code's
388
+ * folder with the recorder loaded into every Node process it starts) or made-up inputs for exported functions that
389
+ * look free of side effects.
390
+ */
391
+ export function runJs(root, { mode = 'generate', command, node = process.execPath, maxSeconds = 120, maxCalls = 200, cwd } = {}) {
392
+ const dir = scratch();
393
+ const env = { ...process.env, THUNDER_TRACE_ROOT: root, THUNDER_TRACE_OUT: dir, THUNDER_TRACE_MAX_SECONDS: String(maxSeconds), NODE_OPTIONS: `${process.env.NODE_OPTIONS || ''} --require ${JSON.stringify(JS_TRACER)}`.trim() };
394
+ const began = Date.now();
395
+ const r = mode === 'command'
396
+ ? spawnSync(command, { shell: true, cwd: cwd || root, env, encoding: 'utf8', timeout: (maxSeconds + 60) * 1000, maxBuffer: 64 * 1024 * 1024 })
397
+ : spawnSync(node, [JS_GENERATE, root, String(maxCalls)], { cwd: dir, env, encoding: 'utf8', timeout: (maxSeconds + 60) * 1000, maxBuffer: 64 * 1024 * 1024 });
398
+ const trace = { files: {}, runs: [] };
399
+ const metas = [];
400
+ for (const f of existsSync(dir) ? readdirSync(dir).filter((x) => /^trace-\d+\.json$/.test(x)) : []) {
401
+ try { const t = JSON.parse(readFileSync(join(dir, f), 'utf8')); mergeTraces(trace, t); metas.push(t.meta); } catch { /* a process that died mid-write */ }
402
+ }
403
+ rmSync(dir, { recursive: true, force: true });
404
+ const calls = mode === 'generate' ? (() => { try { return JSON.parse(r.stdout).calls; } catch { return 0; } })() : undefined;
405
+ trace.runs = [{ how: mode === 'command' ? command : 'generated inputs', language: 'js', seconds: (Date.now() - began) / 1000, processes: metas.length, pauses: metas.reduce((a, x) => a + (x?.pauses || 0), 0), undecided: metas.reduce((a, x) => a + (x?.undecided || 0), 0), capped: metas.some((x) => x?.capped), ...(calls != null ? { calls } : {}), exit: r.status, ...(r.status && !metas.length ? { errors: [String(r.stderr || r.error?.message || '').slice(-400)] } : {}) }];
406
+ return trace;
407
+ }
408
+
409
+ /** Which language a folder is mostly written in, of the two Thunder can run. */
410
+ export function languageOf(root) {
411
+ let py = 0, js = 0;
412
+ for (const f of collectReadableFiles(root, { maxFiles: 3000 })) { if (/\.py$/.test(f.path)) py++; else if (/\.[cm]?[jt]sx?$/.test(f.path)) js++; }
413
+ return py >= js ? 'python' : 'js';
414
+ }
415
+
416
+ /**
417
+ * Read a folder, run it (its tests when given, and made-up inputs), and compare. Options: lang ('python' | 'js'),
418
+ * tests (a folder of test_* functions, Python), pytest (arguments; runs pytest), command (JS: a shell command such as
419
+ * the project's test runner), cwd (where pytest or the command runs; default the folder: lets one project's tests
420
+ * exercise another folder's code), trace (a saved record to compare again instead of running), generate (default
421
+ * true), python, maxSeconds, maxCalls.
422
+ */
423
+ export function verifyRun(root, opts = {}) {
424
+ root = realpathSync(root);
425
+ if (!statSync(root).isDirectory()) throw new Error(`${root} is not a folder.`);
426
+ const lang = opts.lang || languageOf(root);
427
+ if (!LANGS[lang]) throw new Error(`Thunder runs python or js code; got "${lang}".`);
428
+ const trace = { files: {}, runs: [] };
429
+ if (opts.trace) mergeTraces(trace, typeof opts.trace === 'string' ? JSON.parse(readFileSync(opts.trace, 'utf8')) : opts.trace);
430
+ else if (lang === 'python') {
431
+ if (opts.pytest != null) mergeTraces(trace, runPython(root, { ...opts, mode: 'pytest', pytestArgs: [].concat(opts.pytest).flatMap((a) => String(a).split(/\s+/)).filter(Boolean) }));
432
+ const tests = opts.tests ?? ['tests', 'test'].map((d) => join(root, d)).find((d) => existsSync(d));
433
+ if (tests && opts.pytest == null) mergeTraces(trace, runPython(root, { ...opts, mode: 'discover', tests }));
434
+ if (opts.generate !== false) mergeTraces(trace, runPython(root, { ...opts, mode: 'generate' }));
435
+ } else {
436
+ if (opts.command) mergeTraces(trace, runJs(root, { ...opts, mode: 'command' }));
437
+ if (opts.generate !== false) mergeTraces(trace, runJs(root, { ...opts, mode: 'generate' }));
438
+ }
439
+ const files = collectReadableFiles(root, { maxFiles: 5000 }).filter((f) => f.source && !TEST_PATH.test(f.path) && LANGS[lang].includes(langOfPath(f.path)));
440
+ const model = thunderModel(files, { name: root.split('/').pop() });
441
+ Object.defineProperty(model, '_sources', { value: new Map(files.map((f) => [f.path, f.source.split('\n')])), enumerable: false });
442
+ const result = compareRun(model, trace, { languages: LANGS[lang] });
443
+ result.language = lang;
444
+ result.runs = trace.runs;
445
+ markExecuted(model, result);
446
+ return { result, model, trace };
447
+ }
448
+
449
+ const langOfPath = (p) => (/\.py$/.test(p) ? 'python' : /\.[cm]?tsx?$/.test(p) ? 'typescript' : /\.[cm]?jsx?$/.test(p) ? 'javascript' : null);
450
+
451
+ /** The result in words, for a person: totals, then every contradiction with its question, side, and line. */
452
+ export function executedText(result, { all = false } = {}) {
453
+ const s = result.summary;
454
+ const out = [];
455
+ for (const r of result.runs || []) out.push(` ran: ${r.how} (${r.language}, ${r.seconds}s${r.calls != null ? `, ${r.calls} calls` : ''}${r.capped ? ', stopped at the time cap' : ''}${r.errors?.length ? `, ${r.errors.length} could not run` : ''})`);
456
+ out.push(` ${s.members} members: ${s.executed} executed, ${s.contradicted} contradicted, ${s.notChecked} ran with nothing to check, ${s.notRun} not run`);
457
+ out.push(` questions: ${s.questionsChecked} of ${s.questions} checked by a run; claims matched ${s.claims.matched}, contradicted ${s.claims.mismatched}, not drawn ${s.claims.notDrawn}`);
458
+ for (const m of result.members) {
459
+ if (m.status === 'contradicted') {
460
+ out.push(` contradicted ${m.file}:${m.lines[0]} ${m.name}`);
461
+ for (const x of m.mismatches) out.push(` line ${x.line}${x.question ? ` "${x.question}"` : ''} ${x.side}: ${x.expected}; ${x.observed}${x.times > 1 ? ` (${x.times} times)` : ''}`);
462
+ } else if (all) out.push(` ${m.status.padEnd(12)} ${m.file}:${m.lines[0]} ${m.name}${m.runs ? ` (${m.runs} runs; ${m.questions.checked} of ${m.questions.drawn} questions checked)` : ''}`);
463
+ }
464
+ return out.join('\n');
465
+ }
@@ -0,0 +1,137 @@
1
+ // The faithfulness gate: words that say what code does must account for every operator in that code.
2
+ //
3
+ // A reading that drops a `!`, an `||` term, or a comparison is worse than no reading: it tells a person the
4
+ // opposite of what the code does, with Thunder's confidence. So before a condition (or a value) is put into
5
+ // words, the words are checked against the code: the same number of negations (`!`, `not`, `!=`, `unless`, …),
6
+ // the same number of `and` / `or` terms, and at least as many comparisons. When they do not match, the code is
7
+ // shown as code, marked "not explained", instead of a paraphrase. Vague but true beats precise but false.
8
+ //
9
+ // Everything here is linear in the length of the text: single passes and regexes with no nested quantifiers.
10
+ import { exprCounts } from './meaning.mjs';
11
+
12
+ /** Text with every quoted string replaced by Q (so operators inside strings are not counted). */
13
+ export const stripQuoted = (s) => String(s).replace(/(["'`])(?:\\.|(?!\1)[^\\\n])*\1/g, 'Q');
14
+
15
+ /** Skip a quoted string starting at i; returns the index of its closing quote (or the end). */
16
+ function skipQuote(s, i) {
17
+ const q = s[i];
18
+ for (let j = i + 1; j < s.length; j++) { if (s[j] === '\\') { j++; continue; } if (s[j] === q) return j; }
19
+ return s.length - 1;
20
+ }
21
+
22
+ /** Index of the bracket that closes the one at `open` (quote-aware), or -1. */
23
+ export function closeOf(s, open) {
24
+ const pairs = { '(': ')', '[': ']', '{': '}' };
25
+ const want = pairs[s[open]];
26
+ if (!want) return -1;
27
+ let depth = 0;
28
+ for (let i = open; i < s.length; i++) {
29
+ const c = s[i];
30
+ if (c === '"' || c === "'" || c === '`') { i = skipQuote(s, i); continue; }
31
+ if (c === '(' || c === '[' || c === '{') depth++;
32
+ else if (c === ')' || c === ']' || c === '}') { depth--; if (depth === 0) return c === want ? i : -1; }
33
+ }
34
+ return -1;
35
+ }
36
+
37
+ /** True when the whole text is one bracketed group: `(a || b)`. */
38
+ export const wrapped = (s) => { const t = String(s).trim(); return t.startsWith('(') && closeOf(t, 0) === t.length - 1; };
39
+
40
+ /** Brackets and quotes balanced in this text. */
41
+ export function balancedText(s) {
42
+ let d = 0;
43
+ for (let i = 0; i < s.length; i++) {
44
+ const c = s[i];
45
+ if (c === '"' || c === "'" || c === '`') { const e = skipQuote(s, i); if (e >= s.length - 1 && s[e] !== c) return false; i = e; continue; }
46
+ if (c === '(' || c === '[' || c === '{') d++;
47
+ else if (c === ')' || c === ']' || c === '}') { if (--d < 0) return false; }
48
+ }
49
+ return d === 0;
50
+ }
51
+
52
+ /**
53
+ * Split a condition at its top-level `and` / `or` (`&&`, `||`, `and`, `or`, `andalso`), outside brackets and
54
+ * quotes. Returns { terms, ops } (ops[i] joins terms[i] and terms[i + 1]), or null when the text has a top-level
55
+ * ternary or an unbalanced bracket (it cannot be split safely).
56
+ */
57
+ export function splitLogic(text) {
58
+ const s = String(text);
59
+ const terms = [], ops = [];
60
+ let depth = 0, from = 0;
61
+ for (let i = 0; i < s.length; i++) {
62
+ const c = s[i];
63
+ if (c === '"' || c === "'" || c === '`') {
64
+ // A Ruby/Rust lifetime or char like 'a is not a string start we can close; give up on a lone quote.
65
+ const e = skipQuote(s, i);
66
+ if (s[e] !== c) return null;
67
+ i = e; continue;
68
+ }
69
+ if (c === '(' || c === '[' || c === '{') { depth++; continue; }
70
+ if (c === ')' || c === ']' || c === '}') { if (--depth < 0) return null; continue; }
71
+ if (depth) continue;
72
+ let op = null, len = 0;
73
+ if ((c === '&' && s[i + 1] === '&') || (c === '|' && s[i + 1] === '|')) { op = c === '&' ? 'and' : 'or'; len = 2; }
74
+ else if (/\s/.test(c)) {
75
+ const w = /^\s(and|or)(?=\s)/.exec(s.slice(i, i + 5));
76
+ if (w) { op = w[1]; len = 1 + w[1].length; }
77
+ } else if (c === '?' && /\s/.test(s[i - 1] || '') && /\s/.test(s[i + 1] || '')) return null; // a ? b : c
78
+ if (op) { terms.push(s.slice(from, i).trim()); ops.push(op); from = i + len; i += len - 1; }
79
+ }
80
+ if (depth !== 0) return null;
81
+ terms.push(s.slice(from).trim());
82
+ if (terms.some((t) => !t)) return null;
83
+ return { terms, ops };
84
+ }
85
+
86
+ const KEYWORD = /^(?:not|and|or|is|in|instanceof|typeof|true|false|null|nil|None|undefined|this|self|new|await)$/;
87
+ const wordsOf = (name) => String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().split(/\s+/).filter(Boolean);
88
+ const NEG_WORD = /^(?:not|no|non|never|cannot|none)$/;
89
+
90
+ /** Negations in names (`notFound`, `no_cache`): kept as words, so they count on both sides. */
91
+ function nameNegations(code) {
92
+ let n = 0;
93
+ for (const id of code.match(/[A-Za-z_][\w]*/g) || []) if (!KEYWORD.test(id)) for (const w of wordsOf(id)) if (NEG_WORD.test(w)) n++;
94
+ return n;
95
+ }
96
+
97
+ /**
98
+ * Operator counts in one code condition. Negations: `!`, `not`, `!=`, `!==`, `<>`, `is not`, `not in`; a loose
99
+ * `!= null` / `!= nil` / `is not None` reads as "is set" (the negation is part of the meaning), so it is not
100
+ * counted. Logic: `&&`, `||`, `and`, `or`. Comparisons: `==`, `!=`, `<`, `>`, `<=`, `>=`, `is`, `in`, `instanceof`.
101
+ */
102
+ export function codeCounts(code) {
103
+ let s = stripQuoted(code);
104
+ s = s.replace(/(?<![!=])!=\s*(?:null|nil|None|undefined)\b/g, ' SET ').replace(/\bis\s+not\s+None\b/g, ' SET ').replace(/!==\s*(?:nil|None)\b/g, ' SET ');
105
+ const neg = (s.match(/!==?|<>|!(?!=)|\bnot\b/g) || []).length + nameNegations(s);
106
+ const logic = (s.match(/&&|\|\||\band\b|\bor\b/g) || []).length;
107
+ const compare = (s.match(/===?|!==?|<=|>=|<>|(?<![-=<])<(?![=<-])|(?<![-=>])>(?![=>])|\bis\b|\bin\b|\binstanceof\b|\bSET\b/g) || []).length;
108
+ return { neg, logic, compare };
109
+ }
110
+
111
+ /** The same counts in the words Thunder wrote. */
112
+ export function wordCounts(said) {
113
+ const s = stripQuoted(String(said).replace(/`[^`]*`/g, 'Q'));
114
+ // (`None` written as a value is Python's empty value, not a negation.)
115
+ const neg = (s.match(/\b(?:[Nn]ot|[Nn]o|[Nn]on|[Nn]ever|[Cc]annot|none)\b|n't\b/g) || []).length;
116
+ const logic = (s.match(/\band\b|\bor\b/g) || []).length;
117
+ const compare = (s.match(/\b(?:is|are|was|has|have|does|than|at least|at most|in|instanceof|equals?|matches|set|empty|null|undefined|nil|true|false)\b|[<>=]/g) || []).length;
118
+ return { neg, logic, compare };
119
+ }
120
+
121
+ /**
122
+ * True when the words keep every negation and every and/or of the code, and do not drop a comparison. With `tree`
123
+ * (the condition's meaning tree, meaning.mjs) the code's operators are counted from the tree, which knows exactly
124
+ * which `!` is a negation (not a TypeScript non-null claim) and which words are inside strings.
125
+ */
126
+ export function accountsFor(code, said, tree = null) {
127
+ // Operators left as symbols mean the code was not put into words.
128
+ const bare = stripQuoted(String(said).replace(/`[^`]*`/g, 'Q'));
129
+ if (/&&|\|\||[!=]==?|<=|>=|\s[<>]\s|^\s*[<>]|\bis is\b/.test(bare)) return false;
130
+ const c = tree && tree.kind !== 'code' ? exprCounts(tree) : codeCounts(code), w = wordCounts(said);
131
+ return c.neg === w.neg && c.logic === w.logic && w.compare >= c.compare;
132
+ }
133
+
134
+ /** A piece of code shown as code: in backticks, shortened visibly when it is long. */
135
+ export const asCodeWords = (code, n = 120) => { const t = String(code).replace(/\s+/g, ' ').trim(); return `\`${t.length > n ? `${t.slice(0, n - 1)}…` : t}\``; };
136
+ /** True when a condition's words are the code itself (the gate fell back). */
137
+ export const isCodeWords = (said) => /^`[^]*`$/.test(String(said).trim());
@@ -0,0 +1,35 @@
1
+ // Which infrastructure or delivery format a file is (spec section 12), from its path and, when the path is not
2
+ // enough, its first lines. One table, so readers for later formats plug in by turning their row on. Browser-safe.
3
+
4
+ const base = (p) => p.slice(p.lastIndexOf('/') + 1);
5
+ const isYaml = (p) => /\.ya?ml$/i.test(p);
6
+
7
+ /**
8
+ * Formats, in the order they are checked. `reader: true` means Thunder reads it today; the others are hooks for the
9
+ * readers in spec section 12, recognized but not read yet (readableFile gives null for them).
10
+ */
11
+ export const FORMAT_FILES = [
12
+ { format: 'dockerfile', reader: true, match: (p) => (/^(Dockerfile|Containerfile)(\.[\w.-]+)?$/i.test(base(p)) && !/\.(md|txt|dockerignore)$/i.test(p)) || /\.dockerfile$/i.test(p) },
13
+ { format: 'github-actions', reader: true, match: (p) => /(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/i.test(p) },
14
+ { format: 'terraform', reader: true, match: (p) => /\.tf$/i.test(p) },
15
+ { format: 'bicep', reader: true, match: (p) => /\.bicep$/i.test(p) },
16
+ { format: 'docker-compose', reader: true, match: (p) => /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/i.test(base(p)) || /\.compose\.ya?ml$/i.test(base(p)) },
17
+ // Hooks for the next readers (not read yet):
18
+ { format: 'azure-pipelines', reader: false, match: (p) => /(^|\/)azure-pipelines(\.[\w-]+)?\.ya?ml$/i.test(p) },
19
+ { format: 'helm', reader: false, match: (p) => /(^|\/)Chart\.ya?ml$/.test(p) },
20
+ // Kubernetes YAML is known by its content: `apiVersion:` and `kind:` near the top.
21
+ { format: 'kubernetes', reader: true, match: (p, head) => isYaml(p) && /^apiVersion:\s*\S/m.test(head) && /^kind:\s*\S/m.test(head) },
22
+ ];
23
+
24
+ /** The infrastructure or delivery format of a file, read or not (null when it is none of them). */
25
+ export function formatOf(path, head = '') {
26
+ const p = String(path).replace(/\\/g, '/');
27
+ for (const f of FORMAT_FILES) if (f.match(p, String(head ?? ''))) return f;
28
+ return null;
29
+ }
30
+
31
+ /** The format Thunder reads for this path today, or null. */
32
+ export function readableFormat(path, head = '') {
33
+ const f = formatOf(path, head);
34
+ return f?.reader ? f.format : null;
35
+ }