@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillstech/thunderlang",
3
- "version": "1.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Thunder™, the human programming language: the deterministic ThunderLang™ compiler, CLI, and Language Server. No AI required. Reads code in seventeen languages into Thunder, changes TypeScript, JavaScript, Python, and Go code from Thunder with a proof, compiles rules to six languages, and executes them: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/ai.mjs CHANGED
@@ -14,6 +14,7 @@ import { slug } from './parse.mjs';
14
14
  // Pure, browser-safe helpers live in ai-core.mjs (no Node deps). Re-exported here so
15
15
  // the main API is unchanged; browser consumers can import '@skillstech/thunderlang/core'.
16
16
  import { COMMENT_PREFIX, HIGH_RISK, blocksProduction } from './ai-core.mjs';
17
+ import { byText } from './text-order.mjs';
17
18
  export {
18
19
  IMPLEMENTATION_STATES, RISK_LEVELS, HIGH_RISK, blocksProduction,
19
20
  COMMENT_PREFIX, INTENT_AI_EVENTS, makeEvent, PROOF_CHECK_KEYS,
@@ -309,7 +310,7 @@ export function buildManifest(files, opts = {}) {
309
310
  mustNotModify: impl.mustNotModify || [`${f.ast.mission}.contract`],
310
311
  });
311
312
  }
312
- implementations.sort((a, b) => a.id.localeCompare(b.id));
313
+ implementations.sort((a, b) => byText(a.id, b.id));
313
314
  return {
314
315
  schemaVersion: MANIFEST_SCHEMA_VERSION,
315
316
  projectId: opts.projectId || null,
package/src/atlas.mjs CHANGED
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { parseIntent, slug } from './parse.mjs';
12
12
  import { sha256 } from './emit.mjs';
13
+ import { byText } from './text-order.mjs';
13
14
 
14
15
  // Feature area convention: an explicit `# area: X` comment wins; otherwise the
15
16
  // header comment `# <Name>.intent , <Product> / <Area>` is used; else uncategorized.
@@ -92,7 +93,7 @@ export function buildMissionIndex(files, opts = {}) {
92
93
  };
93
94
  }).filter((m) => m.mission);
94
95
 
95
- missions.sort((a, b) => a.mission.localeCompare(b.mission));
96
+ missions.sort((a, b) => byText(a.mission, b.mission));
96
97
 
97
98
  const byArea = {};
98
99
  for (const m of missions) {
@@ -0,0 +1,246 @@
1
+ // The behaviour check: run a Python function before and after a change on inputs made from the function's own code,
2
+ // and say which answers changed. It is evidence of the kind "Tested", never a proof: it covers the inputs it tried.
3
+ //
4
+ // It RUNS the code (the file's top level and the function), so it is opt-in: thunder write --behaviour, the MCP
5
+ // tool's behaviour option, and the read/write benchmark. Each call has a time limit, and the whole run has one too.
6
+ //
7
+ // The inputs: for every number written in the function, the number and one either side (100 -> 99, 100, 101), the
8
+ // text it compares with, and the usual edges (0, 1, -1, yes, no, nothing, "", an empty list). Every combination
9
+ // when there are few, otherwise a fixed sample, so the same code always gets the same inputs.
10
+
11
+ import { spawnSync } from 'node:child_process';
12
+
13
+ /**
14
+ * Python 3.10 or newer: THUNDER_PYTHON, python3, or python. Its own small finder (not core/project.mjs), so the
15
+ * site's MCP route can use this file without bundling the Core project builder and its runtime files.
16
+ */
17
+ function findPython() {
18
+ for (const cmd of [process.env.THUNDER_PYTHON, 'python3', 'python'].filter(Boolean)) {
19
+ const r = spawnSync(cmd, ['-c', 'import sys; print("%d.%d" % sys.version_info[:2])'], { encoding: 'utf8' });
20
+ if (r.status !== 0 || !r.stdout) continue;
21
+ const [maj, min] = r.stdout.trim().split('.').map(Number);
22
+ if (maj > 3 || (maj === 3 && min >= 10)) return { cmd, version: r.stdout.trim() };
23
+ return { error: `the behaviour check needs Python 3.10 or newer, but "${cmd}" is Python ${r.stdout.trim()}` };
24
+ }
25
+ return { error: 'the behaviour check needs Python 3.10 or newer, and none was found (tried THUNDER_PYTHON, python3, python)' };
26
+ }
27
+
28
+ export const BEHAVIOUR_SCHEMA = 'thunder-behaviour-v1';
29
+ const MAX_INPUTS = 400;
30
+
31
+ /** The parameters of `def name(...)` in Python source, or null when there is no such top-level function. */
32
+ export function pythonParams(source, name) {
33
+ const re = new RegExp(`^def\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\(`, 'm');
34
+ const m = re.exec(source);
35
+ if (!m) return null;
36
+ let i = m.index + m[0].length, depth = 1, text = '';
37
+ for (; i < source.length && depth; i++) {
38
+ const c = source[i];
39
+ if (c === '(' || c === '[' || c === '{') depth++;
40
+ else if (c === ')' || c === ']' || c === '}') depth--;
41
+ if (depth) text += c;
42
+ }
43
+ const parts = [];
44
+ depth = 0; let cur = '';
45
+ for (const c of text) {
46
+ if ('([{'.includes(c)) depth++;
47
+ if (')]}'.includes(c)) depth--;
48
+ if (c === ',' && !depth) { parts.push(cur); cur = ''; } else cur += c;
49
+ }
50
+ parts.push(cur);
51
+ const params = [];
52
+ for (const raw of parts.map((p) => p.trim()).filter(Boolean)) {
53
+ if (raw === '/' || raw === '*') continue;
54
+ if (raw.startsWith('*')) return { unsupported: `it takes ${raw.startsWith('**') ? 'named extras' : 'extra values'} (${raw})` };
55
+ const pname = raw.split(/[:=]/)[0].trim();
56
+ params.push({ name: pname, hasDefault: raw.includes('=') });
57
+ }
58
+ return { params };
59
+ }
60
+
61
+ /** The body of a top-level Python function: its lines up to the next line at the left edge. */
62
+ export function pythonBody(source, name) {
63
+ const lines = source.split('\n');
64
+ const start = lines.findIndex((l) => new RegExp(`^def\\s+${name}\\s*\\(`).test(l));
65
+ if (start < 0) return '';
66
+ let end = start + 1;
67
+ while (end < lines.length && (lines[end].trim() === '' || /^\s/.test(lines[end]))) end++;
68
+ return lines.slice(start, end).join('\n');
69
+ }
70
+
71
+ /** The values to try, from the code of the function before and after (a number used only after counts too). */
72
+ export function probeValues(...bodies) {
73
+ const nums = new Set(), strs = new Set();
74
+ for (const body of bodies) {
75
+ const code = body.replace(/#.*$/gm, '');
76
+ for (const m of code.matchAll(/(?<![\w.])(\d+(?:\.\d+)?)(?![\w.])/g)) nums.add(m[1]);
77
+ for (const m of code.matchAll(/(["'])((?:(?!\1)[^\\\n]){0,40})\1/g)) strs.add(m[2]);
78
+ }
79
+ const values = [];
80
+ values.fromCode = new Set();
81
+ const add = (v, fromCode = false) => { if (!values.some((x) => JSON.stringify(x) === JSON.stringify(v))) values.push(v); if (fromCode) values.fromCode.add(JSON.stringify(v)); };
82
+ for (const n of [...nums].slice(0, 6)) {
83
+ const isInt = !n.includes('.');
84
+ const x = Number(n);
85
+ if (isInt) { add(x - 1, true); add(x, true); add(x + 1, true); } else { add(x, true); add(Math.round((x - 0.01) * 100) / 100, true); add(Math.round((x + 0.01) * 100) / 100, true); }
86
+ }
87
+ for (const v of [0, 1, -1, true, false, null]) add(v);
88
+ for (const s of [...strs].slice(0, 4)) add(s);
89
+ add('');
90
+ add([]);
91
+ return values;
92
+ }
93
+
94
+ /** What each input looks like in the code: compared with a number, compared with text, or used as a yes/no. */
95
+ export function inputKinds(body, params) {
96
+ return Object.fromEntries(params.map((p) => {
97
+ const n = p.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
98
+ if (new RegExp(`\\b${n}\\s*(?:[<>]=?|==|!=)\\s*-?\\d|-?\\d[\\d.]*\\s*(?:[<>]=?|==|!=)\\s*${n}\\b|\\b${n}\\s*[-+*/%]|[-+*/%]\\s*${n}\\b|\\b${n}\\s*[<>]=?\\s*[A-Za-z_]|[A-Za-z_]\\w*\\s*[<>]=?\\s*${n}\\b|range\\([^)]*\\b${n}\\b`).test(body)) return [p.name, 'number'];
99
+ if (new RegExp(`\\b${n}\\s*(?:==|!=)\\s*["']|["']\\s*(?:==|!=)\\s*${n}\\b|\\b${n}\\s+(?:not\\s+)?in\\s*[(\\[{]\\s*["']`).test(body)) return [p.name, 'text'];
100
+ if (new RegExp(`(?:\\bif|\\band|\\bor|\\bnot|\\belif)\\s+${n}\\s*(?::|\\band\\b|\\bor\\b|$)`, 'm').test(body)) return [p.name, 'bool'];
101
+ return [p.name, null];
102
+ }));
103
+ }
104
+
105
+ /**
106
+ * The inputs to try, using what the code shows about each input: a number input gets the code's numbers and the
107
+ * edges, a text input the code's text, a yes/no input yes, no, and nothing. Every combination of those (or a fixed
108
+ * sample when there are too many), then each input once with every other kind of value, to catch changes in how odd
109
+ * values are handled.
110
+ */
111
+ export function typedInputs(params, values, kinds, { odd = true } = {}) {
112
+ const pool = (k) => {
113
+ if (k === 'number') return values.filter((v) => typeof v === 'number');
114
+ if (k === 'text') return values.filter((v) => typeof v === 'string' || v === null);
115
+ if (k === 'bool') return [true, false];
116
+ return values;
117
+ };
118
+ const pools = params.map((p) => pool(kinds[p.name]));
119
+ const key = (a) => JSON.stringify(a);
120
+ const seen = new Set(), out = [];
121
+ const push = (a) => { const k = key(a); if (!seen.has(k)) { seen.add(k); out.push(a); } };
122
+ const total = pools.reduce((n, p) => n * p.length, 1);
123
+ if (total <= MAX_INPUTS) {
124
+ for (let k = 0; k < total; k++) { const args = []; let r = k; for (const p of pools) { args.push(p[r % p.length]); r = Math.floor(r / p.length); } push(args); }
125
+ } else {
126
+ let seed = 20261127;
127
+ const rand = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648; };
128
+ for (let j = 0; j < params.length; j++) for (const v of pools[j]) push(pools.map((p, i) => (i === j ? v : p[0])));
129
+ while (out.length < MAX_INPUTS) push(pools.map((p) => p[Math.floor(rand() * p.length)]));
130
+ }
131
+ // Odd values, one input at a time, the others at a typical value.
132
+ if (odd) for (let j = 0; j < params.length; j++) for (const v of values) if (!pools[j].some((x) => key(x) === key(v))) push(pools.map((p, i) => (i === j ? v : p[0])));
133
+ return out;
134
+ }
135
+
136
+ const HARNESS = String.raw`
137
+ import json, sys, signal, io, contextlib, types, os
138
+ job = json.loads(sys.stdin.read())
139
+ # The file's own folder, so its imports of neighbouring modules work as they would for the program.
140
+ sys.path.insert(0, os.path.dirname(os.path.abspath(job["path"])))
141
+ class TimeUp(Exception):
142
+ pass
143
+ def on_alarm(signum, frame):
144
+ raise TimeUp()
145
+ if hasattr(signal, "SIGALRM"):
146
+ signal.signal(signal.SIGALRM, on_alarm)
147
+ def limit(seconds):
148
+ if hasattr(signal, "SIGALRM"):
149
+ signal.setitimer(signal.ITIMER_REAL, seconds)
150
+ def unlimit():
151
+ if hasattr(signal, "SIGALRM"):
152
+ signal.setitimer(signal.ITIMER_REAL, 0)
153
+ def load(src):
154
+ mod = types.ModuleType("thunder_behaviour_subject")
155
+ mod.__file__ = job["path"]
156
+ out = io.StringIO()
157
+ try:
158
+ limit(5)
159
+ with contextlib.redirect_stdout(out):
160
+ exec(compile(src, job["path"], "exec"), mod.__dict__)
161
+ unlimit()
162
+ except BaseException as e:
163
+ unlimit()
164
+ return None, "%s: %s" % (type(e).__name__, e)
165
+ fn = getattr(mod, job["name"], None)
166
+ if not callable(fn):
167
+ return None, "the file has no function named %s" % job["name"]
168
+ return fn, None
169
+ def call(fn, args):
170
+ out = io.StringIO()
171
+ try:
172
+ limit(1)
173
+ with contextlib.redirect_stdout(out):
174
+ value = fn(*args)
175
+ unlimit()
176
+ return {"value": repr(value), "printed": out.getvalue()}
177
+ except TimeUp:
178
+ return {"error": "took longer than a second", "printed": out.getvalue()}
179
+ except BaseException as e:
180
+ unlimit()
181
+ return {"error": "%s: %s" % (type(e).__name__, e), "printed": out.getvalue()}
182
+ result = {}
183
+ for side in ("before", "after"):
184
+ fn, problem = load(job[side])
185
+ if problem:
186
+ result[side] = {"problem": problem}
187
+ continue
188
+ result[side] = {"results": [call(fn, list(a)) for a in job["inputs"]]}
189
+ print(json.dumps(result))
190
+ `;
191
+
192
+ /** A JSON value as Python source (for argument lists): true -> True, null -> None. */
193
+ export const pyLiteral = (v) => (v === null ? 'None' : v === true ? 'True' : v === false ? 'False' : Array.isArray(v) ? `[${v.map(pyLiteral).join(', ')}]` : typeof v === 'string' ? JSON.stringify(v) : String(v));
194
+
195
+ /**
196
+ * Argument lists (Python source) for a function, made from its code: typed inputs only, no odd values, because a
197
+ * round trip compares like with like. [] when an input's kind cannot be told from the code.
198
+ */
199
+ export function generatedArgs(source, name, { max = 120 } = {}) {
200
+ const sig = pythonParams(source, name);
201
+ if (!sig || sig.unsupported) return [];
202
+ const body = pythonBody(source, name);
203
+ const kinds = inputKinds(body, sig.params);
204
+ if (sig.params.some((p) => !kinds[p.name])) return [];
205
+ return typedInputs(sig.params, probeValues(body), kinds, { odd: false }).slice(0, max).map((a) => a.map(pyLiteral).join(', '));
206
+ }
207
+
208
+ const show = (v) => (v === null ? 'None' : v === true ? 'True' : v === false ? 'False' : typeof v === 'string' ? JSON.stringify(v) : Array.isArray(v) ? '[]' : String(v));
209
+ const outcome = (r) => (r.error ? `error (${r.error})` : `${r.value}${r.printed ? ` and printed ${JSON.stringify(r.printed.trimEnd())}` : ''}`);
210
+
211
+ /**
212
+ * Run `name` from `path` before and after a change on inputs made from its code.
213
+ * Returns { schema, status: 'same' | 'changed' | 'broken' | 'not-run', function, inputs, changes, says, reason? }.
214
+ */
215
+ export function behaviourCheck({ path, name, before, after, python = null, timeoutMs = 60000 }) {
216
+ const base = { schema: BEHAVIOUR_SCHEMA, function: `${path}#${name}`, inputs: 0, changes: [] };
217
+ if (!/\.py$/.test(path)) return { ...base, status: 'not-run', reason: 'the behaviour check runs Python functions only for now', says: `Behaviour not checked: ${path} is not Python (the behaviour check runs Python only for now).` };
218
+ const sig = pythonParams(after, name) ?? pythonParams(before, name);
219
+ if (!sig) return { ...base, status: 'not-run', reason: `${name} is not a top-level function (methods need an object to run on)`, says: `Behaviour not checked: ${name} is not a top-level function.` };
220
+ if (sig.unsupported) return { ...base, status: 'not-run', reason: sig.unsupported, says: `Behaviour not checked: ${name} ${sig.unsupported}.` };
221
+ const py = python ?? findPython();
222
+ if (py.error) return { ...base, status: 'not-run', reason: py.error, says: `Behaviour not checked: ${py.error}` };
223
+ const values = probeValues(pythonBody(before, name), pythonBody(after, name));
224
+ const body = pythonBody(after, name) || pythonBody(before, name);
225
+ const kind = inputKinds(body, sig.params);
226
+ const inputs = typedInputs(sig.params, values, kind);
227
+ const run = spawnSync(py.cmd, ['-I', '-c', HARNESS], { input: JSON.stringify({ path, name, before, after, inputs }), encoding: 'utf8', timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 });
228
+ if (run.error || run.status !== 0) return { ...base, status: 'not-run', reason: run.error ? `the run stopped: ${run.error.message}` : `Python failed: ${(run.stderr || '').trim().split('\n').pop()}`, says: 'Behaviour not checked: the run did not finish.' };
229
+ const res = JSON.parse(run.stdout);
230
+ if (res.after.problem) return { ...base, status: 'broken', inputs: 0, reason: res.after.problem, says: `Behaviour: the changed file does not load: ${res.after.problem}.` };
231
+ if (res.before.problem) return { ...base, status: 'not-run', reason: `the original file does not load: ${res.before.problem}`, says: `Behaviour not checked: the original file does not load (${res.before.problem}).` };
232
+ const changes = [];
233
+ inputs.forEach((args, i) => {
234
+ const b = res.before.results[i], a = res.after.results[i];
235
+ if (outcome(b) !== outcome(a)) changes.push({ inputs: Object.fromEntries(sig.params.map((p, j) => [p.name, args[j]])), before: outcome(b), after: outcome(a) });
236
+ });
237
+ // The example shown first: the change whose inputs look most like real ones (the code's own numbers, yes/no).
238
+ const fits = (pname, v) => (kind[pname] === 'bool' ? typeof v === 'boolean' : kind[pname] === 'text' ? typeof v === 'string' && v !== '' : kind[pname] === 'number' ? typeof v === 'number' && values.fromCode.has(JSON.stringify(v)) : values.fromCode.has(JSON.stringify(v)) || typeof v === 'boolean');
239
+ const likeReal = (c) => Object.entries(c.inputs).filter(([k, v]) => fits(k, v)).length;
240
+ changes.sort((x, y) => likeReal(y) - likeReal(x));
241
+ const said = (c) => `${sig.params.length ? sig.params.map((p) => `${p.name} ${show(c.inputs[p.name])}`).join(', ') : 'no inputs'}: before ${c.before}, after ${c.after}`;
242
+ const says = changes.length
243
+ ? `Behaviour: ran ${name} before and after on ${inputs.length} inputs made from its code; ${changes.length} gave a different answer, e.g. ${said(changes[0])}.`
244
+ : `Behaviour: ran ${name} before and after on ${inputs.length} inputs made from its code; every answer is the same.`;
245
+ return { ...base, status: changes.length ? 'changed' : 'same', inputs: inputs.length, changes, says, example: changes[0] ? said(changes[0]) : null, examples: changes.slice(0, 5).map(said) };
246
+ }