@skillstech/thunderlang 1.7.0 → 2.0.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 (73) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +15 -3
  3. package/dist/core.cjs +303 -41
  4. package/dist/index.cjs +9906 -1387
  5. package/dist/learn.cjs +1420 -93
  6. package/package.json +17 -15
  7. package/src/cli-main.mjs +381 -149
  8. package/src/core/ThunderRuntime.cs +22 -1
  9. package/src/core/check.mjs +320 -6
  10. package/src/core/cli.mjs +60 -8
  11. package/src/core/csharp-run.mjs +2 -2
  12. package/src/core/diagnostics.mjs +9 -0
  13. package/src/core/engine-core.mjs +148 -19
  14. package/src/core/engine-values.mjs +3 -0
  15. package/src/core/engine.mjs +131 -7
  16. package/src/core/from-python.mjs +1 -1
  17. package/src/core/go-run.mjs +5 -3
  18. package/src/core/index.mjs +12 -3
  19. package/src/core/java/thunder/ThunderRuntime.java +1 -0
  20. package/src/core/java-run.mjs +2 -2
  21. package/src/core/kind.mjs +6 -0
  22. package/src/core/lexer.mjs +16 -2
  23. package/src/core/parser.mjs +215 -29
  24. package/src/core/project-root.mjs +18 -0
  25. package/src/core/project.mjs +34 -16
  26. package/src/core/react-run.mjs +2 -2
  27. package/src/core/runtime-go/thunder_runtime.go +310 -2
  28. package/src/core/runtime-python.mjs +365 -3
  29. package/src/core/runtime-typescript.mjs +150 -5
  30. package/src/core/rust/thunder_runtime.rs +1 -0
  31. package/src/core/rust-run.mjs +2 -2
  32. package/src/core/serving.mjs +12 -0
  33. package/src/core/store-format.mjs +110 -0
  34. package/src/core/target-csharp.mjs +14 -0
  35. package/src/core/target-go.mjs +24 -3
  36. package/src/core/target-java.mjs +14 -0
  37. package/src/core/target-python.mjs +46 -5
  38. package/src/core/target-rust.mjs +14 -0
  39. package/src/core/target-typescript.mjs +76 -6
  40. package/src/core/typescript-run.mjs +6 -4
  41. package/src/core-changes-fs.mjs +28 -0
  42. package/src/core-changes.d.mts +67 -0
  43. package/src/core-changes.mjs +603 -0
  44. package/src/core-rules.mjs +146 -0
  45. package/src/core-services.d.mts +4 -0
  46. package/src/core-services.mjs +49 -0
  47. package/src/emit.mjs +3 -3
  48. package/src/evidence-words.d.mts +6 -0
  49. package/src/evidence-words.mjs +47 -0
  50. package/src/evidence.mjs +36 -1
  51. package/src/examples.d.mts +21 -0
  52. package/src/examples.mjs +175 -0
  53. package/src/index.d.ts +19 -0
  54. package/src/index.mjs +8 -1
  55. package/src/learn-lessons.mjs +1 -1
  56. package/src/lsp.mjs +110 -0
  57. package/src/mcp.mjs +47 -12
  58. package/src/obligations.d.mts +5 -0
  59. package/src/obligations.mjs +30 -2
  60. package/src/program.d.mts +7 -0
  61. package/src/program.mjs +7 -0
  62. package/src/read-repo-fs.mjs +2 -1
  63. package/src/review.mjs +75 -6
  64. package/src/same.mjs +16 -6
  65. package/src/scan-queries.mjs +2 -1
  66. package/src/symbols.d.mts +23 -0
  67. package/src/symbols.mjs +351 -0
  68. package/src/system.mjs +1 -1
  69. package/src/template.d.mts +31 -0
  70. package/src/template.mjs +189 -0
  71. package/src/trace-cli.mjs +8 -3
  72. package/src/trace-fs.mjs +29 -3
  73. package/src/trace.mjs +23 -7
@@ -0,0 +1,351 @@
1
+ // Names in Thunder files, where each is defined and used: go to definition, find references, and rename (roadmap
2
+ // 2.4). Browser-safe: it reads nothing itself; give it the files ([{ path, source }]).
3
+ //
4
+ // Thunder Core programs (names can be several words: "decide refund", "review limit"):
5
+ // functions To decide refund: used as decide refund with order and $10
6
+ // data types A Refund is one of: / A Customer has: as Refund, a Customer with …, list of Customers
7
+ // alternatives Approved with … (in a data type) a approved Refund, Approved:, refund is approved
8
+ // values Keep review limit at $100, Store orders as …, a Set at the top of a file
9
+ // inputs, locals Receive order as Order, Set left to …, For each item in … (only inside their function)
10
+ // A project's tests/ files see its src/ files, as in thunder test, so a function's references include its tests.
11
+ // Fields are not covered yet: a field is written without its data type ("with amount $5"), so renaming one safely
12
+ // needs the checker's types. Endpoints are named by their route and are not renamed.
13
+ //
14
+ // Missions (names are single identifiers): decisions, lifecycles, data, services, events and the other named blocks,
15
+ // rules inside a decision, and the fields listed under input, output, and data. A name is used wherever the same
16
+ // identifier stands as a whole word outside text and comments in that file.
17
+ //
18
+ // Every position here is 1-based (line, col), like the compiler's diagnostics. A rename is refused, with the reason,
19
+ // when the new name is not a valid name, is already used, or would make any file have more problems than before.
20
+
21
+ import { compileCore, parseCore, seedFrom } from './core/index.mjs';
22
+ import { RESERVED } from './core/parser.mjs';
23
+ import { fileKind } from './core/kind.mjs';
24
+
25
+ const isTestPath = (p) => /(^|\/)tests\//.test(p);
26
+ const projectOf = (p) => { const m = /^(.*?)(?:^|\/)(?:src|tests)\//.exec(p); return m ? m[1] : ''; };
27
+ const isCore = (f) => /\.thunder$/i.test(f.path) && fileKind(f.source).kind === 'program';
28
+ const KIND_WORDS = { function: 'function', type: 'data type', alternative: 'alternative', value: 'value', local: 'value', input: 'input' };
29
+
30
+ // ------------------------------------------------------------------ spans
31
+
32
+ /** The length of the name written at `col` on `text` (its words, any spacing, any case), or null if it is not there. */
33
+ function spanAt(text, col, name, plural = false) {
34
+ const words = String(name).trim().split(/\s+/);
35
+ let i = col - 1;
36
+ if (i < 0) return null;
37
+ for (let w = 0; w < words.length; w++) {
38
+ if (w > 0) { const sp = /^\s+/.exec(text.slice(i)); if (!sp) return null; i += sp[0].length; }
39
+ const word = words[w];
40
+ if (text.slice(i, i + word.length).toLowerCase() !== word.toLowerCase()) return null;
41
+ i += word.length;
42
+ }
43
+ let isPlural = false;
44
+ if (plural && /^s(?![\p{L}\p{N}_])/u.test(text.slice(i))) { i += 1; isPlural = true; }
45
+ if (/^[\p{L}\p{N}_]/u.test(text.slice(i))) return null;
46
+ return { length: i - (col - 1), plural: isPlural };
47
+ }
48
+
49
+ // ------------------------------------------------------------------ Thunder Core
50
+
51
+ function compileProject(coreFiles) {
52
+ const results = [];
53
+ // The checker rewrites parts of the tree (Depending on becomes an If chain), so names are read from a tree
54
+ // straight from the parser (`parsed`); the compiled result gives the diagnostics.
55
+ for (const f of coreFiles.filter((x) => !isTestPath(x.path))) results.push({ ...compileCore(f.source, { file: f.path }), parsed: parseCore(f.source), path: f.path, source: f.source, kind: 'src' });
56
+ for (const f of coreFiles.filter((x) => isTestPath(x.path))) {
57
+ const root = projectOf(f.path);
58
+ const seen = results.filter((r) => r.kind === 'src' && projectOf(r.path) === root);
59
+ results.push({ ...compileCore(f.source, { file: f.path, imported: seen }), parsed: parseCore(f.source, { seed: seedFrom(seen) }), path: f.path, source: f.source, kind: 'test' });
60
+ }
61
+ return results;
62
+ }
63
+
64
+ /** Names a function sets or receives: its locals. */
65
+ function localsOf(fn) {
66
+ const out = new Set(fn.params.map((p) => p.name));
67
+ const walk = (n) => {
68
+ if (Array.isArray(n)) return n.forEach(walk);
69
+ if (!n || typeof n !== 'object') return;
70
+ if (n.k === 'set' && n.target?.k === 'name') out.add(n.target.name);
71
+ if (n.k === 'each') for (const v of n.vars ?? []) out.add(v.name);
72
+ if (n.k === 'range' && n.v) out.add(n.v.name);
73
+ for (const v of Object.values(n)) if (v && typeof v === 'object') walk(v);
74
+ };
75
+ walk(fn.body);
76
+ return out;
77
+ }
78
+
79
+ function coreOccurrences(coreFiles) {
80
+ const results = compileProject(coreFiles);
81
+ const occ = [];
82
+ // Global names, across the files (a project's names are shared, as in thunder build).
83
+ const values = new Set();
84
+ const altRecords = new Map(); // alternative -> [data types]
85
+ for (const r of results) for (const s of r.parsed?.body ?? []) {
86
+ if (s.k === 'keep' || s.k === 'store') values.add(s.name);
87
+ if (s.k === 'set' && s.target?.k === 'name') values.add(s.target.name);
88
+ if (s.k === 'each') for (const v of s.vars ?? []) values.add(v.name);
89
+ if (s.k === 'record' && s.alts) for (const a of s.alts) altRecords.set(a.name, [...(altRecords.get(a.name) ?? []), s.name]);
90
+ }
91
+ for (const r of results) {
92
+ const lines = r.source.replace(/\r\n?/g, '\n').split('\n');
93
+ const add = (o) => {
94
+ if (o.col == null || o.line == null || !o.text) return;
95
+ const sp = spanAt(lines[o.line - 1] ?? '', o.col, o.text, o.kind === 'type');
96
+ if (!sp) return;
97
+ const dup = occ.find((x) => x.id === o.id && x.path === r.path && x.line === o.line && x.col === o.col);
98
+ if (dup) { dup.def = dup.def || o.def; return; }
99
+ occ.push({ ...o, path: r.path, length: sp.length, plural: sp.plural, written: (lines[o.line - 1] ?? '').substr(o.col - 1, sp.length) });
100
+ };
101
+ const altOf = (alt, record) => {
102
+ const recs = record ? [record] : altRecords.get(alt) ?? [];
103
+ return recs.length === 1 ? recs[0] : null;
104
+ };
105
+ const walk = (n, ctx) => {
106
+ if (Array.isArray(n)) { n.forEach((x) => walk(x, ctx)); return; }
107
+ if (!n || typeof n !== 'object') return;
108
+ const skip = new Set();
109
+ const nameRef = (node, def) => {
110
+ const local = ctx.locals?.has(node.name);
111
+ if (local) add({ id: `local:${r.path}:${ctx.fn.name}:${node.name}`, kind: ctx.params?.has(node.name) ? 'input' : 'local', name: node.name, text: node.text, line: node.line, col: node.col, def, ...(ctx.fn.endpoint && ctx.params?.has(node.name) ? { endpoint: ctx.fn.text } : {}) });
112
+ else if (values.has(node.name)) add({ id: `value:${node.name}`, kind: 'value', name: node.name, text: node.text, line: node.line, col: node.col, def });
113
+ };
114
+ switch (n.k) {
115
+ case 'func': {
116
+ if (!n.endpoint) add({ id: `function:${n.name}`, kind: 'function', name: n.name, text: n.text, line: n.line, col: n.col, def: true });
117
+ const locals = localsOf(n);
118
+ const inner = { fn: n, locals, params: new Set(n.params.map((p) => p.name)) };
119
+ for (const p of n.params) {
120
+ add({ id: `local:${r.path}:${n.name}:${p.name}`, kind: 'input', name: p.name, text: p.text, line: p.line, col: p.col, def: true, ...(n.endpoint ? { endpoint: n.text } : {}) });
121
+ walk(p.type, inner); walk(p.dflt, inner);
122
+ }
123
+ walk(n.body, inner);
124
+ return;
125
+ }
126
+ case 'record':
127
+ if (Array.isArray(n.fields)) {
128
+ add({ id: `type:${n.name}`, kind: 'type', name: n.name, text: n.text, line: n.line, col: n.col, def: true });
129
+ for (const a of n.alts ?? []) {
130
+ add({ id: `alternative:${n.name}:${a.name}`, kind: 'alternative', name: a.name, text: a.text, line: a.line, col: a.col, def: true });
131
+ for (const f of a.fields) walk(f.type, ctx);
132
+ }
133
+ for (const f of n.fields) if (!f.hidden && !n.alts) walk(f.type, ctx);
134
+ walk(n.rules, ctx);
135
+ return;
136
+ }
137
+ add({ id: `type:${n.name}`, kind: 'type', name: n.name, text: n.name, line: n.line, col: n.col, def: false });
138
+ return;
139
+ case 'new':
140
+ if (n.recordCol) add({ id: `type:${n.record}`, kind: 'type', name: n.record, text: n.record, line: n.line, col: n.recordCol, def: false });
141
+ if (n.alt && n.altCol) add({ id: `alternative:${n.record}:${n.alt}`, kind: 'alternative', name: n.alt, text: n.altText ?? n.alt, line: n.line, col: n.altCol, def: false });
142
+ for (const f of n.fields ?? []) walk(f.e, ctx);
143
+ return;
144
+ case 'isAlt': {
145
+ const rec = altOf(n.alt);
146
+ if (rec) add({ id: `alternative:${rec}:${n.alt}`, kind: 'alternative', name: n.alt, text: n.text, line: n.line, col: n.col, def: false });
147
+ walk(n.e, ctx);
148
+ return;
149
+ }
150
+ case 'depending':
151
+ walk(n.subject, ctx);
152
+ for (const c of n.cases) {
153
+ const rec = altOf(c.alt);
154
+ if (rec) add({ id: `alternative:${rec}:${c.alt}`, kind: 'alternative', name: c.alt, text: c.text, line: c.line, col: c.col, def: false });
155
+ walk(c.body, ctx);
156
+ }
157
+ walk(n.otherwise, ctx);
158
+ return;
159
+ case 'set':
160
+ if (n.target?.k === 'name') { nameRef(n.target, true); skip.add('target'); }
161
+ break;
162
+ case 'keep': case 'store':
163
+ add({ id: `value:${n.name}`, kind: 'value', name: n.name, text: n.text, line: n.line, col: n.col, def: true });
164
+ break;
165
+ case 'each':
166
+ for (const v of n.vars ?? []) nameRef({ ...v, line: n.line }, true);
167
+ skip.add('vars');
168
+ break;
169
+ case 'range':
170
+ if (n.v) nameRef({ ...n.v, line: n.line }, true);
171
+ skip.add('v');
172
+ break;
173
+ case 'name':
174
+ nameRef(n, false);
175
+ return;
176
+ case 'call':
177
+ add({ id: `function:${n.name}`, kind: 'function', name: n.name, text: n.text, line: n.line, col: n.col, def: false });
178
+ break;
179
+ default:
180
+ }
181
+ for (const [k, v] of Object.entries(n)) if (!skip.has(k) && v && typeof v === 'object') walk(v, ctx);
182
+ };
183
+ walk(r.parsed?.body ?? [], {});
184
+ }
185
+ return { occ, results };
186
+ }
187
+
188
+ // ------------------------------------------------------------------ missions
189
+
190
+ const MISSION_BLOCKS = /^(decision|lifecycle|data|service|event|api|scenario|property|capability|component|interface|command|database|artifact|evaluation|metric|outcome|persona|experience|pattern|release|result|learning)\s+([A-Za-z_][\w]*)\s*$/;
191
+ const FIELD_BLOCKS = new Set(['input', 'output', 'data']);
192
+ const PROSE_BLOCKS = new Set(['goal', 'why', 'note', 'guarantees', 'never', 'assumptions', 'risks', 'problem', 'evidence', 'scope', 'non_goal', 'question', 'unknown', 'assumption', 'title', 'customer', 'persona', 'owner']);
193
+
194
+ /** A mission line with its text and comments blanked out, so only code words remain (columns kept). */
195
+ const codeOnly = (line) => {
196
+ let out = '', q = null;
197
+ for (let i = 0; i < line.length; i++) {
198
+ const c = line[i];
199
+ if (q) { out += ' '; if (c === q) q = null; continue; }
200
+ if (c === '"' || c === '`') { q = c; out += ' '; continue; }
201
+ if (c === '#') { out += ' '.repeat(line.length - i); break; }
202
+ out += c;
203
+ }
204
+ return out;
205
+ };
206
+
207
+ function missionOccurrences(file) {
208
+ const lines = file.source.replace(/\r\n?/g, '\n').split('\n');
209
+ const decls = new Map(); // name -> { line, col, kind }
210
+ let block = null, prose = false;
211
+ lines.forEach((raw, i) => {
212
+ const text = codeOnly(raw);
213
+ if (!text.trim()) return;
214
+ const top = !/^\s/.test(raw);
215
+ if (top) {
216
+ const head = text.trim();
217
+ const word = head.split(/\s+/)[0];
218
+ block = FIELD_BLOCKS.has(head) ? head : MISSION_BLOCKS.test(head) ? word : word;
219
+ prose = PROSE_BLOCKS.has(word);
220
+ const m = MISSION_BLOCKS.exec(head);
221
+ if (m && !decls.has(m[2])) decls.set(m[2], { line: i + 1, col: raw.indexOf(m[2], raw.indexOf(m[1]) + m[1].length) + 1, kind: m[1] });
222
+ if (word === 'data' && m) block = 'data';
223
+ return;
224
+ }
225
+ const rule = /^\s+rule\s+([A-Za-z_]\w*)\s*$/.exec(text);
226
+ if (rule && block === 'decision' && !decls.has(rule[1])) decls.set(rule[1], { line: i + 1, col: text.indexOf(rule[1], text.indexOf('rule') + 4) + 1, kind: 'rule' });
227
+ const field = /^\s+([A-Za-z_]\w*)\s*:/.exec(text);
228
+ if (field && FIELD_BLOCKS.has(block) && !decls.has(field[1])) decls.set(field[1], { line: i + 1, col: text.indexOf(field[1]) + 1, kind: `${block} field` });
229
+ });
230
+ const occ = [];
231
+ block = null; prose = false;
232
+ lines.forEach((raw, i) => {
233
+ const text = codeOnly(raw);
234
+ if (!/^\s/.test(raw) && text.trim()) prose = PROSE_BLOCKS.has(text.trim().split(/\s+/)[0]);
235
+ // Prose: a block of sentences, a "because" line, and a case or scenario's own title.
236
+ if (prose || /^\s*(?:because|case|scenario)\b/.test(text)) return;
237
+ for (const m of text.matchAll(/[A-Za-z_]\w*/g)) {
238
+ const d = decls.get(m[0]);
239
+ if (!d) continue;
240
+ const col = m.index + 1;
241
+ occ.push({ id: `mission:${file.path}:${m[0]}`, kind: 'mission', what: d.kind, name: m[0], text: m[0], path: file.path, line: i + 1, col, length: m[0].length, def: d.line === i + 1 && d.col === col, written: m[0] });
242
+ }
243
+ });
244
+ return occ;
245
+ }
246
+
247
+ // ------------------------------------------------------------------ the index
248
+
249
+ /** Every name occurrence in the files: { occurrences, results } (results: the compiled Core files). */
250
+ export function symbolIndex(files) {
251
+ const list = (files ?? []).filter((f) => f && typeof f.source === 'string');
252
+ const core = list.filter(isCore);
253
+ const { occ, results } = core.length ? coreOccurrences(core) : { occ: [], results: [] };
254
+ for (const f of list.filter((x) => !isCore(x))) occ.push(...missionOccurrences(f));
255
+ return { occurrences: occ, results };
256
+ }
257
+
258
+ /** The name at a position (1-based line and col), with every place it occurs, or null. */
259
+ export function symbolAt(files, path, { line, col }, index = symbolIndex(files)) {
260
+ const here = index.occurrences.find((o) => o.path === path && o.line === line && col >= o.col && col < o.col + o.length)
261
+ ?? index.occurrences.find((o) => o.path === path && o.line === line && col === o.col + o.length);
262
+ if (!here) return null;
263
+ const all = index.occurrences.filter((o) => o.id === here.id).sort((a, b) => (a.path === b.path ? a.line - b.line || a.col - b.col : a.path < b.path ? -1 : 1));
264
+ const defs = all.filter((o) => o.def);
265
+ // A value set more than once is defined where it is first set.
266
+ const definitions = here.kind === 'local' || here.kind === 'value' ? defs.slice(0, 1) : defs;
267
+ return { id: here.id, kind: here.kind, what: KIND_WORDS[here.kind] ?? here.what, name: here.name, at: here, definitions, references: all };
268
+ }
269
+
270
+ const article = (w) => `${/^[aeiou]/i.test(w) ? 'an' : 'a'} ${w}`;
271
+ const loc = (o) => ({ path: o.path, line: o.line, col: o.col, length: o.length });
272
+
273
+ /** Where the name at a position is defined: [{ path, line, col, length }] (empty when it is not a name Thunder knows). */
274
+ export function definitionsAt(files, path, pos) {
275
+ const s = symbolAt(files, path, pos);
276
+ return s ? s.definitions.map(loc) : [];
277
+ }
278
+
279
+ /** Every place the name at a position is used, its definition included unless { declaration: false }. */
280
+ export function referencesAt(files, path, pos, { declaration = true } = {}) {
281
+ const s = symbolAt(files, path, pos);
282
+ if (!s) return [];
283
+ return s.references.filter((o) => declaration || !o.def).map(loc);
284
+ }
285
+
286
+ const problems = (files) => {
287
+ const out = new Map();
288
+ const { results } = symbolIndex(files);
289
+ for (const r of results) out.set(r.path, (r.diagnostics ?? []).filter((d) => d.severity !== 'warning' && d.code !== 'TC120').length);
290
+ return out;
291
+ };
292
+
293
+ /** Keep the first letter's case of what was written: "Approved:" stays capitalised, "a approved Refund" does not. */
294
+ function cased(newName, written) {
295
+ const first = written[0] ?? '';
296
+ if (first && first === first.toUpperCase() && first !== first.toLowerCase()) return newName[0].toUpperCase() + newName.slice(1);
297
+ if (first && first === first.toLowerCase() && first !== first.toUpperCase()) return newName[0].toLowerCase() + newName.slice(1);
298
+ return newName;
299
+ }
300
+
301
+ /**
302
+ * Rename the name at a position everywhere it is used. Returns { ok: true, symbol, edits: [{ path, line, col, length,
303
+ * newText }] } or { ok: false, problem } with why it was refused. Nothing is changed: the caller applies the edits.
304
+ */
305
+ export function renameAt(files, path, pos, newName) {
306
+ const index = symbolIndex(files);
307
+ const s = symbolAt(files, path, pos, index);
308
+ if (!s) return { ok: false, problem: 'There is no name here that Thunder can rename: put the cursor on a function, data type, alternative, value, or input (in a mission: a decision, rule, field, or other named block).' };
309
+ const endpoint = s.references.find((o) => o.endpoint)?.endpoint;
310
+ if (endpoint) return { ok: false, problem: `${s.at.written} is what callers send to ${endpoint}, so renaming it here would change the API. Go to definition and find references still work.` };
311
+ const wanted = String(newName ?? '').trim().replace(/\s+/g, ' ');
312
+ if (s.kind === 'mission') {
313
+ if (!/^[A-Za-z_]\w*$/.test(wanted)) return { ok: false, problem: `"${wanted}" can't be a name in a mission: use one word of letters, digits, and _ (like ${s.name}).` };
314
+ } else {
315
+ if (!/^[\p{L}_][\p{L}\p{N}_]*(?: [\p{L}_][\p{L}\p{N}_]*)*$/u.test(wanted)) return { ok: false, problem: `"${wanted}" can't be a name: use words of letters and digits, separated by spaces.` };
316
+ if (/^(?:a|an|the) /i.test(wanted)) return { ok: false, problem: `Thunder skips "a", "an", and "the" at the start of a name, so "${wanted}" would not be the name you see.` };
317
+ const reserved = wanted.split(' ').find((w) => RESERVED.has(w.toLowerCase()));
318
+ if (reserved) return { ok: false, problem: `A name can't contain the word "${reserved}", because it belongs to Thunder.` };
319
+ }
320
+ const key = s.kind === 'mission' ? wanted : wanted.toLowerCase();
321
+ if (key === s.name) return { ok: false, problem: `It is already called ${s.at.written}.` };
322
+ // Already used? Global names clash with every global name; an input or local value with its function's names.
323
+ const scopeOf = (o) => (o.kind === 'local' || o.kind === 'input' ? o.id.split(':').slice(0, 3).join(':') : o.kind === 'mission' ? `mission:${o.path}` : 'global');
324
+ const clash = index.occurrences.find((o) => o.name === key && o.def && (o.kind === 'mission' ? scopeOf(o) === scopeOf(s.at) : s.kind === 'mission' ? false : scopeOf(o) === 'global' || scopeOf(o) === scopeOf(s.at)));
325
+ if (clash) return { ok: false, problem: `"${wanted}" is already the name of ${article(KIND_WORDS[clash.kind] ?? clash.what)} (${clash.path}, line ${clash.line}). Choose another name.` };
326
+
327
+ const edits = s.references.map((o) => ({ ...loc(o), newText: cased(wanted, o.written) + (o.plural ? 's' : '') }));
328
+ // Check: the renamed files must not have more problems than before.
329
+ if (s.kind !== 'mission') {
330
+ const before = problems(files);
331
+ const after = problems(applyRename(files, edits));
332
+ for (const [p, n] of after) {
333
+ if (n > (before.get(p) ?? 0)) return { ok: false, problem: `Renaming to "${wanted}" would give ${p} a problem it does not have now, so nothing was renamed. Choose another name.` };
334
+ }
335
+ }
336
+ return { ok: true, symbol: { id: s.id, kind: s.kind, what: s.what, name: s.name }, edits };
337
+ }
338
+
339
+ /** Apply edits (from renameAt) to files, returning new files. Edits on one line are applied right to left. */
340
+ export function applyRename(files, edits) {
341
+ return files.map((f) => {
342
+ const mine = edits.filter((e) => e.path === f.path);
343
+ if (!mine.length) return f;
344
+ const lines = f.source.split('\n');
345
+ for (const e of [...mine].sort((a, b) => b.line - a.line || b.col - a.col)) {
346
+ const t = lines[e.line - 1];
347
+ lines[e.line - 1] = t.slice(0, e.col - 1) + e.newText + t.slice(e.col - 1 + e.length);
348
+ }
349
+ return { ...f, source: lines.join('\n') };
350
+ });
351
+ }
package/src/system.mjs CHANGED
@@ -927,7 +927,7 @@ export function serviceFacts(model, files) {
927
927
  return { routes, listeners, requests, publishes, unknown };
928
928
  }
929
929
 
930
- export { segsMatch };
930
+ export { segsMatch, routeSegs, requestTarget };
931
931
 
932
932
  // ── The app's map: which areas call which ────────────────────────────────────────────────────────────
933
933
 
@@ -0,0 +1,31 @@
1
+ export const TEMPLATE_SCHEMA: 'thunder-template-v1';
2
+ export interface ThunderTemplateField {
3
+ /** The field's name in the data definition. */
4
+ name: string;
5
+ /** Its kind in words: "money", "list of Tree". */
6
+ kind: string;
7
+ /** The value the template takes it out into ("left", or "tree left" when the field's own name is taken). */
8
+ local: string;
9
+ /** How it leads back to the same data type: the function calls itself for it. */
10
+ recursion: 'self' | 'list of self' | null;
11
+ }
12
+ export interface ThunderTemplate {
13
+ schema: 'thunder-template-v1';
14
+ ok: true;
15
+ type: { name: string; text: string; form: 'atomic' | 'compound' | 'alternatives'; recursive: boolean };
16
+ function: { name: string; input: string; gives: string | null };
17
+ /** One per alternative (alternatives), or one with alternative null (compound and atomic). */
18
+ cases: Array<{ alternative: string | null; fields: ThunderTemplateField[] }>;
19
+ /** Other data types its fields use; each has a template of its own. */
20
+ related: string[];
21
+ /** The function, in Thunder, ending in a newline. */
22
+ text: string;
23
+ /** Added to the file, is it a draft whose only problems are holes? Lines are the template's own (1 = "To …:"). */
24
+ check: { draft: boolean; holes: number; problems: Array<{ line: number; code: string; message: string }> };
25
+ }
26
+ export interface ThunderTemplateMissing { schema: 'thunder-template-v1'; ok: false; problem: string; known: string[] }
27
+ /**
28
+ * The Design Recipe's template step: the shape of a function that takes `type` (a data type in `source`, or number,
29
+ * whole number, text, money, yes/no, date), with holes for the answers. Deterministic.
30
+ */
31
+ export function templateOf(source: string, type: string, options?: { name?: string | null; gives?: string | null; file?: string }): ThunderTemplate | ThunderTemplateMissing;
@@ -0,0 +1,189 @@
1
+ // templateOf(source, type): the Design Recipe's template step (roadmap D.4). A data definition decides the shape of
2
+ // every function that takes it, so Thunder writes that shape for you: one case per alternative, each field taken
3
+ // out by name, a call to the function itself for each part that is the same data type again (the natural
4
+ // recursion), and a hole where the answer goes. You fill in the holes; Thunder never fills them in.
5
+ //
6
+ // A Tree is one of: To handle tree:
7
+ // Leaf Receive tree as Tree
8
+ // Branch with left as Tree and -> Depending on tree:
9
+ // value as number and right as Tree Leaf:
10
+ // Give ?
11
+ // Branch:
12
+ // Set left to tree's left
13
+ // Set value to tree's value
14
+ // Set right to tree's right
15
+ // Set left result to handle tree with left
16
+ // Set right result to handle tree with right
17
+ // Give ?
18
+ //
19
+ // Four forms, after How to Design Programs (Felleisen, Findler, Flatt, Krishnamurthi):
20
+ // atomic number, whole number, text, money, yes/no, date: the input and a hole
21
+ // compound "A Customer has:": one Set line per field
22
+ // alternatives "A Payment is one of:": Depending on, one case per alternative, its fields under it
23
+ // recursive a field of the same data type (or a list of it): a call to the function itself for it
24
+ //
25
+ // Deterministic: the same definition and options always give the same text, character for character. The template
26
+ // is checked before it is returned: added to the file, it must be a draft whose only problems are its holes.
27
+ // Shape: thunder-template-v1.
28
+
29
+ import { parseCore, compileCore } from './core/index.mjs';
30
+ import { typeWords } from './core/check.mjs';
31
+ import { fileKind } from './core/kind.mjs';
32
+
33
+ export const TEMPLATE_SCHEMA = 'thunder-template-v1';
34
+
35
+ /** The kinds of value that are not made of parts, and the input name each template uses for one. */
36
+ const ATOMIC = {
37
+ number: { input: 'number', type: { k: 'number' }, text: 'number' },
38
+ 'whole number': { input: 'count', type: { k: 'whole' }, text: 'whole number' },
39
+ text: { input: 'text', type: { k: 'text' }, text: 'text' },
40
+ money: { input: 'amount', type: { k: 'money' }, text: 'money' },
41
+ 'yes/no': { input: 'answer', type: { k: 'bool' }, text: 'yes/no' },
42
+ date: { input: 'date', type: { k: 'date' }, text: 'date' },
43
+ };
44
+
45
+ const key = (s) => String(s ?? '').trim().toLowerCase().replace(/\s+/g, ' ').replace(/^(?:a|an|the)\s+/, '');
46
+ /** A kind in words, with each data type named as it is written ("list of Tree", not "list of tree"). */
47
+ function kindText(t, textOf) {
48
+ const name = (x) => (x?.k === 'record' ? { ...x, text: textOf.get(x.name) ?? x.text } : x?.of ? { ...x, of: name(x.of) } : x);
49
+ return typeWords(name(t)).replace(/^an? /, '');
50
+ }
51
+
52
+ /** How a field leads back to the same data type: 'self', 'list of self', or null. */
53
+ function recursion(type, self) {
54
+ const t = type?.k === 'optional' ? type.of : type;
55
+ if (t?.k === 'record' && t.name === self) return 'self';
56
+ if (t?.k === 'list' && t.of?.k === 'record' && t.of.name === self) return 'list of self';
57
+ return null;
58
+ }
59
+
60
+ /** Other data types a field uses (not the same one): their own templates may help. */
61
+ function related(type, self, out) {
62
+ const t = type?.k === 'optional' ? type.of : type;
63
+ if (t?.k === 'record' && t.name !== self) out.add(t.text ?? t.name);
64
+ if ((t?.k === 'list' || t?.k === 'optional') && t.of) related(t.of, self, out);
65
+ }
66
+
67
+ /** One item of a list field, by name: "children" -> "child", "branches" -> "branch", else "<name> item". */
68
+ function singular(list, taken) {
69
+ const last = list.split(' ').pop();
70
+ const one = last === 'children' ? 'child' : /(?:ches|shes|xes|sses)$/.test(last) ? last.slice(0, -2) : /[^s]s$/.test(last) ? last.slice(0, -1) : null;
71
+ const name = one ? list.replace(/\S+$/, one) : `${list} item`;
72
+ return taken.includes(name) ? `${list} item` : name;
73
+ }
74
+
75
+ /** The lines of one case: a Set line per field, a call to the function itself per recursive part, the answer hole. */
76
+ function caseLines(fields, { input, fn, hole, prefix, indent }) {
77
+ const lines = [];
78
+ const recursive = [];
79
+ const out = fields.map((f) => {
80
+ const local = prefix ? `${input} ${f.name}` : f.name;
81
+ lines.push(`${indent}Set ${local} to ${input}'s ${f.name}`);
82
+ const r = recursion(f.type, fn.self);
83
+ if (r) recursive.push({ local, r });
84
+ return { name: f.name, kind: kindText(f.type, fn.textOf), local, recursion: r };
85
+ });
86
+ for (const { local, r } of recursive) {
87
+ if (r === 'self') lines.push(`${indent}Set ${local} result to ${fn.name} with ${local}`);
88
+ else {
89
+ const item = singular(local, out.map((x) => x.local));
90
+ lines.push(`${indent}For each ${item} in ${local}:`, `${indent} Set ${item} result to ${fn.name} with ${item}`);
91
+ }
92
+ }
93
+ lines.push(`${indent}Give ${hole}`);
94
+ return { lines, fields: out };
95
+ }
96
+
97
+ function build(def, opts, prefix) {
98
+ const { fnName, hole, textOf } = opts;
99
+ const fn = { name: fnName, self: def.name, textOf };
100
+ const head = [`To ${fnName}:`, ` Receive ${def.input} as ${def.text}`];
101
+ const cases = [];
102
+ if (def.form === 'atomic') {
103
+ cases.push({ alternative: null, fields: [] });
104
+ return { text: [...head, ` Give ${hole}`].join('\n') + '\n', cases };
105
+ }
106
+ if (def.form === 'compound') {
107
+ const c = caseLines(def.fields, { input: def.input, fn, hole, prefix, indent: ' ' });
108
+ cases.push({ alternative: null, fields: c.fields });
109
+ return { text: [...head, ...c.lines].join('\n') + '\n', cases };
110
+ }
111
+ const body = [` Depending on ${def.input}:`];
112
+ for (const a of def.alts) {
113
+ const c = caseLines(a.fields, { input: def.input, fn, hole, prefix, indent: ' ' });
114
+ body.push(` ${a.text}:`, ...c.lines);
115
+ cases.push({ alternative: a.text, fields: c.fields });
116
+ }
117
+ return { text: [...head, ...body].join('\n') + '\n', cases };
118
+ }
119
+
120
+ /** Add the template to the file and check it: a draft whose only problems are holes, at lines inside the template. */
121
+ function check(source, text, file) {
122
+ const base = source.trim() ? `${source.replace(/\s+$/, '')}\n\n` : '';
123
+ const offset = base ? base.split('\n').length - 1 : 0;
124
+ const r = compileCore(base + text, { file });
125
+ const mine = (r.diagnostics ?? []).filter((d) => d.line > offset && d.severity !== 'warning');
126
+ const holes = mine.filter((d) => d.code === 'TC120').length;
127
+ const problems = mine.filter((d) => d.code !== 'TC120').map((d) => ({ line: d.line - offset, code: d.code, message: d.message }));
128
+ return { draft: problems.length === 0, holes, problems };
129
+ }
130
+
131
+ /**
132
+ * The template for a function that takes `type`, a data type defined in `source` ("Payment", "a Tree") or an atomic
133
+ * kind ("money"). Options: `name` (the function's name; default "handle <type>"), `gives` (the answer's kind, so each
134
+ * hole is ?<gives>), `file`. Returns { schema, ok, type, function, cases, related, text, check } or, when the type is
135
+ * not found, { schema, ok: false, problem, known }.
136
+ */
137
+ export function templateOf(source, type, { name = null, gives = null, file = 'main.thunder' } = {}) {
138
+ const src = String(source ?? '');
139
+ const want = key(type);
140
+ const fail = (problem, known = []) => ({ schema: TEMPLATE_SCHEMA, ok: false, problem, known });
141
+ if (!want) return fail('Say which data type to write a template for, for example: Payment.');
142
+ if (src.trim() && fileKind(src).kind === 'mission') return fail('Templates are for Thunder Core programs; this file is a mission.');
143
+
144
+ const records = (parseCore(src, { file }).body ?? []).filter((s) => s.k === 'record');
145
+ const known = [...records.map((r) => r.text), ...Object.values(ATOMIC).map((a) => a.text)];
146
+ let def;
147
+ if (ATOMIC[want]) {
148
+ const a = ATOMIC[want];
149
+ def = { form: 'atomic', name: want, text: a.text, input: a.input, recursive: false };
150
+ } else {
151
+ const rec = records.find((r) => r.name === want) ?? records.find((r) => r.name === want.replace(/s$/, ''));
152
+ if (!rec) {
153
+ const names = records.map((r) => r.text);
154
+ return fail(names.length
155
+ ? `There is no data type "${type}" in this file. Its data types are ${names.join(', ')}; the atomic kinds are ${Object.keys(ATOMIC).join(', ')}.`
156
+ : `There is no data type "${type}" in this file. Define one first ("A ${type} has:" or "A ${type} is one of:"), or use an atomic kind: ${Object.keys(ATOMIC).join(', ')}.`, known);
157
+ }
158
+ const fields = (rec.fields ?? []).filter((f) => !f.hidden);
159
+ def = rec.alts
160
+ ? { form: 'alternatives', name: rec.name, text: rec.text, input: rec.name, alts: rec.alts }
161
+ : { form: 'compound', name: rec.name, text: rec.text, input: rec.name, fields };
162
+ def.recursive = (rec.alts ? rec.alts.flatMap((a) => a.fields) : fields).some((f) => recursion(f.type, rec.name));
163
+ }
164
+
165
+ const fnName = key(name) || `handle ${def.input}`;
166
+ const givesKey = gives == null ? null : String(gives).trim();
167
+ const textOf = new Map(records.map((r) => [r.name, r.text]));
168
+ const opts = { fnName, hole: givesKey ? `?${givesKey}` : '?', textOf };
169
+ // Each field becomes a value named like the field. When a name is already taken (the input, the function, or a
170
+ // name in the file), every field is named after the input instead: "tree left".
171
+ const allFields = def.form === 'alternatives' ? def.alts.flatMap((a) => a.fields) : def.fields ?? [];
172
+ let prefix = allFields.some((f) => f.name === def.input || f.name === fnName);
173
+ let out = build(def, opts, prefix);
174
+ let checked = check(src, out.text, file);
175
+ if (!checked.draft && !prefix && allFields.length) {
176
+ const again = build(def, opts, true);
177
+ const c = check(src, again.text, file);
178
+ if (c.draft) { prefix = true; out = again; checked = c; }
179
+ }
180
+
181
+ const rel = new Set();
182
+ for (const f of allFields) related(f.type, def.name, rel);
183
+ return {
184
+ schema: TEMPLATE_SCHEMA, ok: true,
185
+ type: { name: def.name, text: def.text, form: def.form, recursive: def.recursive },
186
+ function: { name: fnName, input: def.input, gives: givesKey },
187
+ cases: out.cases, related: [...rel].map((n) => textOf.get(n) ?? n).sort(), text: out.text, check: checked,
188
+ };
189
+ }
package/src/trace-cli.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // thunder trace impact --diff [--base <ref>] <folder…> what the current changes (branch + uncommitted) can affect
5
5
  import { writeFileSync } from 'node:fs';
6
6
  import { buildTrace, renderTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
7
- import { readRepoDir, gitChanges } from './trace-fs.mjs';
7
+ import { readRepoDir, gitChanges, coreBehaviourOf } from './trace-fs.mjs';
8
+ import { withCoreBehaviour } from './core-changes.mjs';
8
9
 
9
10
  const USAGE = `usage: thunder trace <folder> <folder> … [--json] [--out graph.json]
10
11
  thunder trace impact "<POST /api/orders | event name | table:orders | setting:KEY | package:name | repo:file[:line]>" <folder> … [--json]
@@ -43,11 +44,15 @@ export function traceMain(argv) {
43
44
  return r.matched.length ? 0 : 1;
44
45
  }
45
46
  const changes = [], notes = [];
47
+ const behaviour = new Map();
46
48
  for (const repo of repos) {
47
49
  const g = gitChanges(repo, a.base);
48
- if (!g.base) notes.push(g.why); else changes.push(...g.changes);
50
+ if (!g.base) { notes.push(g.why); continue; }
51
+ changes.push(...g.changes);
52
+ const cc = coreBehaviourOf(repo, g);
53
+ if (cc) behaviour.set(repo.name, cc);
49
54
  }
50
- const r = traceImpact(trace, changes);
55
+ const r = withCoreBehaviour(traceImpact(trace, changes), behaviour);
51
56
  if (a.json) console.log(JSON.stringify({ ...r, notes }, null, 2));
52
57
  else {
53
58
  console.log(`${changes.length ? `${changes.length} changed file${changes.length === 1 ? '' : 's'} across ${new Set(changes.map((c) => c.repo)).size} of ${repos.length} repositories.` : 'No changes found.'}`);