@skillstech/thunderlang 1.6.1 → 1.7.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.
- package/CHANGELOG.md +46 -0
- package/dist/core.cjs +31 -28
- package/dist/index.cjs +292 -59
- package/dist/learn.cjs +81 -22
- package/package.json +1 -1
- package/src/ai.mjs +2 -1
- package/src/atlas.mjs +2 -1
- package/src/behaviour.mjs +246 -0
- package/src/cli-main.mjs +2818 -0
- package/src/cli.mjs +9 -2799
- package/src/conflict.mjs +0 -0
- package/src/core/ThunderDotnet.cs +195 -0
- package/src/core/check.mjs +4 -4
- package/src/core/cli.mjs +7 -2
- package/src/core/csharp-run.mjs +29 -8
- package/src/core/diagnostics.mjs +3 -1
- package/src/core/engine-core.mjs +20 -1
- package/src/core/go-run.mjs +3 -2
- package/src/core/java-run.mjs +3 -3
- package/src/core/kind.mjs +42 -0
- package/src/core/parser.mjs +54 -7
- package/src/core/project.mjs +3 -0
- package/src/core/react-run.mjs +3 -3
- package/src/core/runtime-npm.mjs +79 -0
- package/src/core/runtime-react.mjs +2 -1
- package/src/core/runtime-typescript.mjs +7 -3
- package/src/core/rust-run.mjs +3 -2
- package/src/core/target-csharp.mjs +5 -1
- package/src/core/target-go.mjs +1 -1
- package/src/core/target-python.mjs +1 -1
- package/src/core/target-rust.mjs +1 -1
- package/src/core/target-typescript.mjs +33 -1
- package/src/core/typescript-run.mjs +9 -4
- package/src/decision.mjs +2 -1
- package/src/distributed.mjs +2 -1
- package/src/emit.mjs +2 -2
- package/src/focus.mjs +2 -1
- package/src/intent-atlas.mjs +4 -3
- package/src/mcp.mjs +10 -3
- package/src/passport-fs.mjs +2 -1
- package/src/passport.mjs +2 -1
- package/src/privacy.mjs +2 -1
- package/src/read-repo.mjs +3 -2
- package/src/report.mjs +3 -2
- package/src/review.mjs +2 -1
- package/src/select.mjs +2 -1
- package/src/semantic-diff.mjs +7 -6
- package/src/system.mjs +2 -1
- package/src/text-order.mjs +6 -0
- package/src/thunderize.mjs +2 -1
- package/src/trace-data.mjs +3 -2
- package/src/trace.mjs +4 -3
- package/src/write-across-cli.mjs +22 -4
- package/src/write-across.mjs +2 -1
- package/syntaxes/thunder.tmLanguage.json +196 -0
package/dist/learn.cjs
CHANGED
|
@@ -17187,6 +17187,9 @@ function sha256hex(input) {
|
|
|
17187
17187
|
}
|
|
17188
17188
|
var sha256 = (s) => `sha256:${sha256hex(String(s))}`;
|
|
17189
17189
|
|
|
17190
|
+
// src/text-order.mjs
|
|
17191
|
+
var byText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
17192
|
+
|
|
17190
17193
|
// src/style.mjs
|
|
17191
17194
|
var TOKEN_PATHS = [
|
|
17192
17195
|
"color.primary",
|
|
@@ -17250,7 +17253,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
|
|
|
17250
17253
|
var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
|
|
17251
17254
|
|
|
17252
17255
|
// src/emit.mjs
|
|
17253
|
-
var COMPILER_VERSION = "1.
|
|
17256
|
+
var COMPILER_VERSION = "1.7.0";
|
|
17254
17257
|
|
|
17255
17258
|
// src/lift.mjs
|
|
17256
17259
|
var IR_SCHEMA_VERSION = "0.1.0";
|
|
@@ -30060,7 +30063,7 @@ function callsSummary(model) {
|
|
|
30060
30063
|
else p.calls++;
|
|
30061
30064
|
if (p.examples.length < 3) p.examples.push({ from: a.id, to: b.id, says: l.kind === "sends-to" ? `${a.label} sends ${l.method ? `${l.method} ${l.path}` : l.event ? `the event ${l.event}` : `a task`} to ${b.label}` : `${a.label} calls ${b.label}` });
|
|
30062
30065
|
}
|
|
30063
|
-
return [...pairs2.values()].sort((x, y) => y.calls + y.sends - (x.calls + x.sends) || x.from
|
|
30066
|
+
return [...pairs2.values()].sort((x, y) => y.calls + y.sends - (x.calls + x.sends) || byText(x.from, y.from) || byText(x.to, y.to));
|
|
30064
30067
|
}
|
|
30065
30068
|
|
|
30066
30069
|
// src/flow/ts-parse.mjs
|
|
@@ -35704,7 +35707,8 @@ function paramGroups(ts) {
|
|
|
35704
35707
|
}
|
|
35705
35708
|
}
|
|
35706
35709
|
const k = g.findIndex((t) => isWord(t, "as"));
|
|
35707
|
-
|
|
35710
|
+
const raw = k < 0 ? g : g.slice(0, k);
|
|
35711
|
+
return { words: stripArticle(raw), raw, typeTokens: k < 0 ? null : g.slice(k + 1), defaultTokens };
|
|
35708
35712
|
});
|
|
35709
35713
|
}
|
|
35710
35714
|
var Stream = class {
|
|
@@ -36247,7 +36251,11 @@ function fillBlock(open, lines, n, ep, names) {
|
|
|
36247
36251
|
}
|
|
36248
36252
|
function nameWords2(ts, line, what) {
|
|
36249
36253
|
const words13 = stripArticle(ts);
|
|
36250
|
-
if (!words13.length)
|
|
36254
|
+
if (!words13.length) {
|
|
36255
|
+
const only = ts.length === 1 && ts[0].t === "word" ? ts[0].text : null;
|
|
36256
|
+
if (only) throw new CoreError(diag("TC108", line, `"${only}" can't be a name on its own: Thunder skips "a", "an", and "the" in names ("the total" is "total").`, `Use a word that says what it holds, like "first number" or "amount".`));
|
|
36257
|
+
throw new CoreError(diag("TC108", line, `${what} is missing a name.`));
|
|
36258
|
+
}
|
|
36251
36259
|
for (const t of words13) {
|
|
36252
36260
|
if (t.t !== "word") throw new CoreError(diag("TC105", line, `A name can only use words, but "${show(t)}" is not a word.`));
|
|
36253
36261
|
if (RESERVED2.has(t.lower)) throw new CoreError(diag("TC202", line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
|
|
@@ -36349,7 +36357,7 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36349
36357
|
let r = 0;
|
|
36350
36358
|
while (kids2[r] && isWord(kids2[r].tokens[0], "receive")) {
|
|
36351
36359
|
const kid = kids2[r];
|
|
36352
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.
|
|
36360
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
36353
36361
|
r++;
|
|
36354
36362
|
}
|
|
36355
36363
|
bodyNodes = kids2.slice(r);
|
|
@@ -36391,11 +36399,48 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36391
36399
|
if (w0 === "use") {
|
|
36392
36400
|
if (!ctx.top) fail2("TC402", '"Use" must be written at the left edge of the file.');
|
|
36393
36401
|
const asAt = rest2.findIndex((t) => isWord(t, "as"));
|
|
36394
|
-
|
|
36402
|
+
let modTs = asAt < 0 ? rest2 : rest2.slice(0, asAt);
|
|
36403
|
+
const fromAt = modTs.findIndex((t) => isWord(t, "from"));
|
|
36404
|
+
let ecosystem = "python";
|
|
36405
|
+
if (fromAt >= 0) {
|
|
36406
|
+
const eco = modTs.slice(fromAt + 1);
|
|
36407
|
+
const plain = (t) => t && typeof t.parts === "undefined" ? null : t && t.parts.every((x) => typeof x === "string") ? t.parts.join("") : null;
|
|
36408
|
+
const word0 = eco[0]?.t === "word" ? eco[0].text.toLowerCase() : "";
|
|
36409
|
+
let said = eco.length === 1 && eco[0].t === "word" ? word0 : "";
|
|
36410
|
+
if (eco.length === 2 && eco[0].t === "sym" && eco[0].text === "." && eco[1].t === "word" && eco[1].text.toLowerCase() === "net") said = "dotnet";
|
|
36411
|
+
if (word0 === "nuget") {
|
|
36412
|
+
const pkg = eco[1]?.t === "str" ? plain(eco[1]) : null;
|
|
36413
|
+
const ver2 = isWord(eco[2], "version") && eco[3]?.t === "str" ? plain(eco[3]) : null;
|
|
36414
|
+
if (!pkg || !ver2 || eco.length !== 4 || !/^[A-Za-z0-9_.-]+$/.test(pkg) || !/^\d+(\.\d+){1,3}([-+][\w.-]+)?$/.test(ver2)) fail2("TC108", 'Name the NuGet package and its version: Use "Humanizer.NumberToWordsExtension" from NuGet "Humanizer.Core" version "2.14.1" as words.');
|
|
36415
|
+
said = "nuget";
|
|
36416
|
+
modTs = modTs.slice(0, fromAt);
|
|
36417
|
+
ecosystem = said;
|
|
36418
|
+
var nuget = { package: pkg, version: ver2 };
|
|
36419
|
+
} else {
|
|
36420
|
+
if (!["python", "npm", "dotnet"].includes(said)) fail2("TC108", `A library comes from Python, npm, .NET, or NuGet, for example: Use csv from Python as csv, Use "date-fns" from npm as dates, or Use "System.IO.Path" from .NET as paths.`);
|
|
36421
|
+
ecosystem = said;
|
|
36422
|
+
modTs = modTs.slice(0, fromAt);
|
|
36423
|
+
}
|
|
36424
|
+
}
|
|
36425
|
+
if (ecosystem === "dotnet" || ecosystem === "nuget") {
|
|
36426
|
+
const t = modTs[0];
|
|
36427
|
+
const type = modTs.length === 1 && t.t === "str" && t.parts.every((x) => typeof x === "string") ? t.parts.join("") : null;
|
|
36428
|
+
if (type == null || !/^[A-Za-z_]\w*(\.[A-Za-z_]\w*)+$/.test(type)) fail2("TC108", 'Write a .NET type with its namespace, in quotes, for example: Use "System.IO.Path" from .NET as paths.');
|
|
36429
|
+
if (asAt < 0) fail2("TC108", `Give the type a name to use in Thunder: Use "${type}" from ${ecosystem === "nuget" ? "NuGet" : ".NET"} \u2026 as <name>.`);
|
|
36430
|
+
return { k: "use", module: type, ecosystem, ...ecosystem === "nuget" ? nuget : {}, ...nameWords2(rest2.slice(asAt + 1), line, '"Use"'), line };
|
|
36431
|
+
}
|
|
36432
|
+
if (ecosystem === "npm" || modTs[0]?.t === "str") {
|
|
36433
|
+
const t = modTs[0];
|
|
36434
|
+
const pkg = modTs.length === 1 && t.t === "str" && t.parts.every((x) => typeof x === "string") ? t.parts.join("") : null;
|
|
36435
|
+
if (pkg == null || !/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(\/[\w.-]+)*$|^node:[a-z_/]+$/i.test(pkg)) fail2("TC108", 'Write an npm package in quotes, for example: Use "date-fns" from npm as dates.');
|
|
36436
|
+
if (ecosystem !== "npm") fail2("TC108", `Say where "${pkg}" comes from: Use "${pkg}" from npm as <name>.`);
|
|
36437
|
+
if (asAt < 0) fail2("TC108", `Give the package a name to use in Thunder: Use "${pkg}" from npm as <name>.`);
|
|
36438
|
+
return { k: "use", module: pkg, ecosystem, ...nameWords2(rest2.slice(asAt + 1), line, '"Use"'), line };
|
|
36439
|
+
}
|
|
36395
36440
|
const module2 = modTs.map((t) => t.t === "word" ? t.text : t.t === "sym" && t.text === "." ? "." : "\0").join("");
|
|
36396
|
-
if (!module2 || module2.includes("\0") || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module2)) fail2("TC108", 'Write "Use <python module> as <name>", for example: Use csv as csv.');
|
|
36441
|
+
if (!module2 || module2.includes("\0") || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module2)) fail2("TC108", 'Write "Use <python module> as <name>", for example: Use csv as csv. For npm: Use "date-fns" from npm as dates.');
|
|
36397
36442
|
const alias = asAt < 0 ? { name: module2.split(".")[0].toLowerCase(), text: module2.split(".")[0] } : nameWords2(rest2.slice(asAt + 1), line, '"Use"');
|
|
36398
|
-
return { k: "use", module: module2, ...alias, line };
|
|
36443
|
+
return { k: "use", module: module2, ecosystem, ...alias, line };
|
|
36399
36444
|
}
|
|
36400
36445
|
if (w0 === "test") {
|
|
36401
36446
|
if (!ctx.top) fail2("TC402", 'A "Test" block must be written at the left edge of the file.');
|
|
@@ -36507,7 +36552,7 @@ function parseScreen(n, ep, names, diagnostics) {
|
|
|
36507
36552
|
while (kids2[k] && isWord(kids2[k].tokens[0], "receive")) {
|
|
36508
36553
|
const kid = kids2[k];
|
|
36509
36554
|
try {
|
|
36510
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.
|
|
36555
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
36511
36556
|
} catch (e) {
|
|
36512
36557
|
if (e instanceof CoreError) diagnostics.push(e.diagnostic);
|
|
36513
36558
|
else throw e;
|
|
@@ -36719,7 +36764,7 @@ var typeWords4 = (t) => {
|
|
|
36719
36764
|
case "optional":
|
|
36720
36765
|
return `${typeWords4(t.of)} or nothing`;
|
|
36721
36766
|
case "module":
|
|
36722
|
-
return "a
|
|
36767
|
+
return "a library";
|
|
36723
36768
|
default:
|
|
36724
36769
|
return "a value";
|
|
36725
36770
|
}
|
|
@@ -36789,14 +36834,14 @@ var Checker = class {
|
|
|
36789
36834
|
this.info.imported.add(k);
|
|
36790
36835
|
}
|
|
36791
36836
|
for (const m of inf.modules) {
|
|
36792
|
-
this.global.vars.set(m.name, { kind: "module", line: m.line, name: m.name, text: m.text, py: m.py, type: T("module") });
|
|
36837
|
+
this.global.vars.set(m.name, { kind: "module", line: m.line, name: m.name, text: m.text, py: m.py, ecosystem: m.ecosystem, type: T("module") });
|
|
36793
36838
|
this.info.imported.add(m);
|
|
36794
36839
|
}
|
|
36795
36840
|
}
|
|
36796
36841
|
for (const s of top) {
|
|
36797
36842
|
if (s.k === "record") this.declare(s, "record", s.line, { py: pyName(s.name, "pascal"), stmt: s });
|
|
36798
36843
|
else if (s.k === "func") this.declare(s, "func", s.line, { py: pyName(s.name), stmt: s, ret: UNKNOWN });
|
|
36799
|
-
else if (s.k === "use") this.declare(s, "module", s.line, { py: pyName(s.name), module: s.module, type: T("module") });
|
|
36844
|
+
else if (s.k === "use") this.declare(s, "module", s.line, { py: pyName(s.name), module: s.module, ecosystem: s.ecosystem, type: T("module") });
|
|
36800
36845
|
else if (s.k === "screen") {
|
|
36801
36846
|
const prev = this.screens.get(s.name);
|
|
36802
36847
|
if (prev) this.err("TC203", s.line, `There is already a screen called "${s.text}" (line ${prev.line}).`, "Give one of them a different name.");
|
|
@@ -37516,7 +37561,7 @@ var Checker = class {
|
|
|
37516
37561
|
}
|
|
37517
37562
|
case "dot": {
|
|
37518
37563
|
const ot = this.ex(e.obj, sc, o);
|
|
37519
|
-
if (ot.k !== "module") this.err("TC402", line, `"${e.attr}" with a dot reaches into a
|
|
37564
|
+
if (ot.k !== "module") this.err("TC402", line, `"${e.attr}" with a dot reaches into a library brought in with "Use". ${e.obj.k === "name" ? `"${e.obj.text}"` : "This"} is not one.`, 'Write "Use <module> as <name>" (Python) or Use "<package>" from npm as <name> at the top of the file first.');
|
|
37520
37565
|
for (const a of e.args ?? []) this.ex(a, sc, o);
|
|
37521
37566
|
return UNKNOWN;
|
|
37522
37567
|
}
|
|
@@ -38022,7 +38067,7 @@ var Gen = class {
|
|
|
38022
38067
|
if (this.needDataclass) head.push("from dataclasses import dataclass, field");
|
|
38023
38068
|
if (this.needDate) head.push("from datetime import date");
|
|
38024
38069
|
if (this.needDecimal) head.push("from decimal import Decimal");
|
|
38025
|
-
for (const m of this.info.modules.filter(own)) head.push(m.module === m.py || m.module.split(".")[0] === m.py && !m.module.includes(".") ? `import ${m.module}` : `import ${m.module} as ${m.py}`);
|
|
38070
|
+
for (const m of this.info.modules.filter((x) => own(x) && (x.ecosystem ?? "python") === "python")) head.push(m.module === m.py || m.module.split(".")[0] === m.py && !m.module.includes(".") ? `import ${m.module}` : `import ${m.module} as ${m.py}`);
|
|
38026
38071
|
head.push(`from thunder_runtime import ${[...this.rt].sort().join(", ")}`);
|
|
38027
38072
|
for (const m of srcModules) head.push(`from ${m} import *`);
|
|
38028
38073
|
head.push("", `THUNDER_SOURCE = ${py(this.source)}`, "", "");
|
|
@@ -40592,12 +40637,14 @@ var CONTAINER_KINDS = /* @__PURE__ */ new Set(["if", "each", "range", "times", "
|
|
|
40592
40637
|
var MAX_RECORDED = 2e4;
|
|
40593
40638
|
function pythonModulesUsed(results) {
|
|
40594
40639
|
const out = [];
|
|
40595
|
-
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line });
|
|
40640
|
+
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line, ecosystem: m.ecosystem ?? "python" });
|
|
40596
40641
|
return out;
|
|
40597
40642
|
}
|
|
40598
40643
|
function refusalText(uses) {
|
|
40599
40644
|
const u = uses[0];
|
|
40600
40645
|
const more = uses.length > 1 ? ` (and ${uses.length - 1} more)` : "";
|
|
40646
|
+
if (u.ecosystem === "dotnet" || u.ecosystem === "nuget") return `This program uses the .NET type "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as C#: --target csharp.`;
|
|
40647
|
+
if (u.ecosystem === "npm") return `This program uses the npm package "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as TypeScript: --target typescript.`;
|
|
40601
40648
|
return `This program uses the Python module "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it with Python: leave out --engine thunder.`;
|
|
40602
40649
|
}
|
|
40603
40650
|
var Module = class {
|
|
@@ -41294,7 +41341,17 @@ var Engine = class {
|
|
|
41294
41341
|
});
|
|
41295
41342
|
}
|
|
41296
41343
|
};
|
|
41344
|
+
function notCompiled(results) {
|
|
41345
|
+
const bad = results.filter((r) => r && r.ok === false);
|
|
41346
|
+
if (!bad.length) return null;
|
|
41347
|
+
const lines = bad.flatMap((r) => (r.diagnostics ?? []).filter((d) => d.severity !== "warning").map((d) => `${r.file ?? "main.thunder"}, line ${d.line ?? "?"}: ${d.message} [${d.code}]`));
|
|
41348
|
+
return { status: 2, stdout: "", stderr: `${lines.join("\n") || "The program has problems"}
|
|
41349
|
+
Nothing was run: fix the problems first.
|
|
41350
|
+
`, notCompiled: true, steps: [] };
|
|
41351
|
+
}
|
|
41297
41352
|
function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } = {}) {
|
|
41353
|
+
const broken = notCompiled([entry3]);
|
|
41354
|
+
if (broken) return broken;
|
|
41298
41355
|
const uses = pythonModulesUsed([entry3]);
|
|
41299
41356
|
if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
|
|
41300
41357
|
`, refused: uses };
|
|
@@ -41315,6 +41372,8 @@ function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } =
|
|
|
41315
41372
|
return { status, stdout: eng.out.join(""), stderr };
|
|
41316
41373
|
}
|
|
41317
41374
|
function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
41375
|
+
const broken = notCompiled(results);
|
|
41376
|
+
if (broken) return broken;
|
|
41318
41377
|
const uses = pythonModulesUsed(results);
|
|
41319
41378
|
if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
|
|
41320
41379
|
`, refused: uses };
|
|
@@ -42977,7 +43036,7 @@ function settingsIn(files) {
|
|
|
42977
43036
|
}
|
|
42978
43037
|
}
|
|
42979
43038
|
}
|
|
42980
|
-
return out.sort((a, b) => a.file
|
|
43039
|
+
return out.sort((a, b) => byText(a.file, b.file) || a.line - b.line || byText(a.key, b.key));
|
|
42981
43040
|
}
|
|
42982
43041
|
var NAME = '((?:[`"\\[]?[A-Za-z_][\\w$]*[`"\\]]?\\.){0,2}[`"\\[]?[A-Za-z_][\\w$]*[`"\\]]?)';
|
|
42983
43042
|
var NOT_TABLES = /* @__PURE__ */ new Set(["select", "set", "where", "values", "dual", "lateral", "unnest", "only", "table", "if", "exists", "not", "the", "a", "an", "my", "your", "this", "that", "each", "all", "json_table", "information_schema", "pg_catalog", "sys"]);
|
|
@@ -43047,7 +43106,7 @@ function tablesIn(files) {
|
|
|
43047
43106
|
if (seen.has(k)) return false;
|
|
43048
43107
|
seen.add(k);
|
|
43049
43108
|
return true;
|
|
43050
|
-
}).sort((a, b) => a.file
|
|
43109
|
+
}).sort((a, b) => byText(a.file, b.file) || a.line - b.line || byText(a.table, b.table));
|
|
43051
43110
|
}
|
|
43052
43111
|
var DEFINES = /* @__PURE__ */ new Set(["creates", "alters", "drops"]);
|
|
43053
43112
|
|
|
@@ -43192,8 +43251,8 @@ function linkRepos(read) {
|
|
|
43192
43251
|
return true;
|
|
43193
43252
|
});
|
|
43194
43253
|
};
|
|
43195
|
-
links.splice(0, links.length, ...once(links).sort((a, b) => sortKey(a)
|
|
43196
|
-
notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => sortKey(a)
|
|
43254
|
+
links.splice(0, links.length, ...once(links).sort((a, b) => byText(sortKey(a), sortKey(b))));
|
|
43255
|
+
notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => byText(sortKey(a), sortKey(b))));
|
|
43197
43256
|
const repos = read.map(({ unknown, ...r }) => ({ ...r, unknown: unknown ?? [], packages: pk(r), settings: r.settings ?? [], tables: tb(r) }));
|
|
43198
43257
|
const body2 = { schema: TRACE_SCHEMA, rulesVersion: TRACE_RULES_VERSION, repos, links, notLinked, shared };
|
|
43199
43258
|
return { ...body2, fingerprint: sha256(JSON.stringify(body2)) };
|
|
@@ -43341,7 +43400,7 @@ function writeRuleAcross(files, { decision, rule, when }) {
|
|
|
43341
43400
|
}
|
|
43342
43401
|
result.files[k] = source;
|
|
43343
43402
|
}
|
|
43344
|
-
result.plan.sort((a, b) => where(a)
|
|
43403
|
+
result.plan.sort((a, b) => byText(where(a), where(b)) || a.line - b.line);
|
|
43345
43404
|
if (problems.length) return { ...base2, files: {}, plan: [], rule: result.rule, notIncluded: result.notIncluded, tests: result.tests, problems: ["Nothing was changed: every implementation must be written exactly, or none is.", ...problems] };
|
|
43346
43405
|
return { ...result, ok: true };
|
|
43347
43406
|
}
|
|
@@ -44106,7 +44165,7 @@ function thunderReview(oldFiles, newFiles) {
|
|
|
44106
44165
|
for (const x of rest2) items.splice(items.indexOf(x), 1);
|
|
44107
44166
|
}
|
|
44108
44167
|
for (const x of items) if (x.also) x.subject = `${x.subject} and ${x.also.length} more`;
|
|
44109
|
-
items.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) || String(a.where.file)
|
|
44168
|
+
items.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) || byText(String(a.where.file), String(b.where.file)) || (a.where.line ?? 0) - (b.where.line ?? 0));
|
|
44110
44169
|
const count = (s) => items.filter((x) => x.severity === s).length;
|
|
44111
44170
|
const summary = { meaning: count("meaning"), risk: count("risk"), form: count("form"), unchanged, files: paths.filter((p) => A.sources.get(p) !== B.sources.get(p)).length };
|
|
44112
44171
|
const onlyNotRead = !items.length && summary.files && notRead.length === summary.files;
|
|
@@ -44173,7 +44232,7 @@ function assemblePassport({ parts, change = null, runs = [], purpose = null, ext
|
|
|
44173
44232
|
notRead.push({ part: p.name, file: u.file, line: u.line, what: owner ? `${owner.label}: ${u.why}` : u.why });
|
|
44174
44233
|
}
|
|
44175
44234
|
}
|
|
44176
|
-
const order2 = (a, b) => `${a.part}/${a.file}
|
|
44235
|
+
const order2 = (a, b) => byText(`${a.part}/${a.file}`, `${b.part}/${b.file}`) || (a.lines?.[0] ?? a.line ?? 0) - (b.lines?.[0] ?? b.line ?? 0);
|
|
44177
44236
|
behavior.sort(order2);
|
|
44178
44237
|
effects.sort(order2);
|
|
44179
44238
|
notRead.sort(order2);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skillstech/thunderlang",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.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
|
|
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
|
|
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
|
+
}
|