@skillstech/thunderlang 1.0.4 → 1.1.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 (66) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/dist/core.cjs +2568 -462
  3. package/dist/index.cjs +7562 -5084
  4. package/dist/learn.cjs +1963 -315
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/mcp.mjs +23 -0
  33. package/src/meaning.mjs +45 -6
  34. package/src/model.d.mts +7 -3
  35. package/src/model.mjs +19 -6
  36. package/src/money.d.mts +18 -0
  37. package/src/money.mjs +124 -0
  38. package/src/plain-contract.mjs +18 -2
  39. package/src/read.d.mts +11 -0
  40. package/src/read.mjs +40 -6
  41. package/src/review-comment.d.mts +16 -0
  42. package/src/review-comment.mjs +145 -0
  43. package/src/say-less.mjs +1432 -0
  44. package/src/system.mjs +153 -44
  45. package/src/target-cs.mjs +39 -34
  46. package/src/target-elixir.mjs +40 -30
  47. package/src/target-go.mjs +41 -36
  48. package/src/target-java.mjs +34 -27
  49. package/src/target-kotlin.mjs +43 -35
  50. package/src/target-py.mjs +57 -55
  51. package/src/target-result.d.mts +48 -0
  52. package/src/target-result.mjs +112 -0
  53. package/src/target-rust.mjs +42 -38
  54. package/src/target-scala.mjs +45 -35
  55. package/src/target-ts.mjs +37 -45
  56. package/src/target-types.mjs +41 -5
  57. package/src/target-util.mjs +55 -2
  58. package/src/trace-cli.mjs +58 -0
  59. package/src/trace-fs.mjs +76 -0
  60. package/src/trace.mjs +261 -0
  61. package/src/translate.d.mts +3 -0
  62. package/src/translate.mjs +62 -32
  63. package/src/why-cli.mjs +31 -0
  64. package/src/why.d.mts +28 -0
  65. package/src/why.mjs +532 -0
  66. package/src/write-steps.mjs +22 -5
@@ -2,36 +2,41 @@
2
2
  // typed static method (using the same exprToJava translator the codegen uses), calls every test
3
3
  // case with typed literal arguments, and prints the results as one JSON line. It runs through the
4
4
  // JDK 11+ single-file source launcher (`java ThunderTarget.java`) , no separate javac step , so a
5
- // live Java run grades real executed code. Returns null (skip cleanly) when no usable JDK exists.
5
+ // live Java run grades real executed code.
6
+ //
7
+ // Results are honest (see target-result.mjs): a missing toolchain, a compile failure, a crash, or a
8
+ // timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
9
+ // translate is refused ('not-translated'). Money inputs are java.math.BigDecimal, never double.
6
10
  import { spawnSync } from 'node:child_process';
7
11
  import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
12
  import { join } from 'node:path';
9
13
  import { tmpdir } from 'node:os';
10
14
  import { exprToJava } from './expr.mjs';
11
- import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
15
+ import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
12
16
 
13
- const JAVA_TYPE = { number: 'double', bool: 'boolean', string: 'String' };
17
+ const JAVA_TYPE = { number: 'double', bool: 'boolean', string: 'String', money: 'java.math.BigDecimal' };
18
+ const JAVA_RUN = { translate: exprToJava, target: 'Java', dialect: 'java' };
19
+ const JAVA_RUNTIME = /Exception in thread|\n\s+at ThunderTarget\./;
14
20
 
15
21
  // The emitted Java source (also usable for display / `gen`-parity).
16
- export function emitJavaModule(ast, cases = buildCases(ast)) {
22
+ export function emitJavaModule(ast, cases = prepareRun(ast, JAVA_RUN).cases, plans = plansFor(ast, exprToJava, 'Java')) {
17
23
  const L = [
18
24
  'import java.util.LinkedHashMap;',
19
25
  'import java.util.Map;',
20
26
  '',
21
27
  'public class ThunderTarget {',
22
28
  ];
23
- const typesByDec = {};
24
- for (const d of ast.decisions || []) {
25
- const names = inputNames(d);
26
- const types = inferInputTypes(ast, d);
27
- typesByDec[d.name] = types;
28
- const params = names.map((n) => `${JAVA_TYPE[types[n]] || 'String'} ${n}`).join(', ');
29
- L.push(` static String ${d.name}(${params}) {`);
30
- for (const r of d.rules || []) {
31
- let cond; try { cond = exprToJava(r.when, { inputs: names }); } catch { cond = 'false'; }
32
- L.push(` if (${cond}) return ${strLit(r.result)};`);
29
+ if ([...plans.values()].some((p) => p.refused)) {
30
+ L.push(' // IL-GEN-001: a rule Thunder could not translate throws instead of guessing.');
31
+ L.push(' static boolean thunderUntranslated(String message) { throw new UnsupportedOperationException(message); }');
32
+ }
33
+ for (const p of plans.values()) {
34
+ const params = p.names.map((n) => `${JAVA_TYPE[p.types[n]] || 'String'} ${n}`).join(', ');
35
+ L.push(` static String ${p.decision.name}(${params}) {`);
36
+ for (const { rule: r, code, message } of p.rules) {
37
+ L.push(` if (${code ?? `thunderUntranslated(${strLit(message)})`}) return ${strLit(r.result)};`);
33
38
  }
34
- L.push(` return ${d.default == null ? 'null' : strLit(d.default)};`, ' }');
39
+ L.push(` return ${p.decision.default == null ? 'null' : strLit(p.decision.default)};`, ' }');
35
40
  }
36
41
  L.push(' static String j(String s) {');
37
42
  L.push(' if (s == null) return "null";');
@@ -43,10 +48,9 @@ export function emitJavaModule(ast, cases = buildCases(ast)) {
43
48
  L.push(' public static void main(String[] args) {');
44
49
  L.push(' Map<String,String> out = new LinkedHashMap<>();');
45
50
  for (const c of cases) {
46
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
47
- if (!dec) continue;
48
- const types = typesByDec[c.fn];
49
- const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
51
+ const p = plans.get(c.fn);
52
+ if (!p) continue;
53
+ const argList = p.names.map((n) => argLit(c, p, n, litFor)).join(', ');
50
54
  L.push(` out.put(${strLit(c.key)}, ${c.fn}(${argList}));`);
51
55
  }
52
56
  L.push(' StringBuilder sb = new StringBuilder("{"); boolean first = true;');
@@ -71,17 +75,20 @@ export function javaAvailable() {
71
75
  });
72
76
  }
73
77
 
74
- // Run every decision test case through generated, compiled Java. Returns { "Test / case": actual }
75
- // or null when no usable JDK is present.
78
+ // Run every decision test case through generated, compiled Java. Returns { status: 'ok', results }
79
+ // or a whole-run { status: 'error', kind, message }.
76
80
  export function runJavaTarget(ast) {
77
- if (!javaAvailable()) return null;
78
- const cases = buildCases(ast);
81
+ if (!javaAvailable()) return runFailure('missing-toolchain', 'No usable JDK (java single-file launcher) on this machine.');
82
+ const { plans, cases, refused } = prepareRun(ast, JAVA_RUN);
83
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
79
84
  const dir = mkdtempSync(join(tmpdir(), 'tl-java-'));
80
85
  try {
81
86
  const f = join(dir, 'ThunderTarget.java');
82
- writeFileSync(f, emitJavaModule(ast, cases));
83
- const r = spawnSync('java', [f], { encoding: 'utf8', timeout: 120000 });
84
- if (r.status !== 0) return null;
85
- return parseLastJsonObject(r.stdout);
87
+ writeFileSync(f, emitJavaModule(ast, cases, plans));
88
+ const out = spawnStep('java', [f], { timeout: 120000 }, (r) => classifySpawn(r, { tool: 'java', phase: 'build+run', runtimePattern: JAVA_RUNTIME }));
89
+ if (!out.ok) return out.failure;
90
+ const parsed = parseLastJsonObject(out.stdout);
91
+ if (!parsed) return runFailure('runtime-error', 'java ran but printed no results.');
92
+ return finishRun({ cases, parsed, refused, target: 'Java' });
86
93
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
87
94
  }
@@ -2,44 +2,48 @@
2
2
  // a typed fun (using the same exprToKotlin translator the codegen uses), calls every test case with
3
3
  // typed literal arguments, and prints the results as one JSON line. It runs through the Kotlin
4
4
  // script runner (`kotlinc -script`), so a live Kotlin run grades real compiled + executed code.
5
- // Returns null (skip cleanly) when no usable Kotlin toolchain exists.
6
- import { spawnSync } from 'node:child_process';
5
+ //
6
+ // Results are honest (see target-result.mjs): a missing toolchain, a compile failure, a crash, or a
7
+ // timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
8
+ // translate is refused ('not-translated'). Kotlin has no exact Money wiring yet, so a rule that
9
+ // compares Money is refused rather than run as a Double.
7
10
  import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
11
  import { join } from 'node:path';
9
12
  import { tmpdir } from 'node:os';
10
13
  import { exprToKotlin } from './expr.mjs';
11
- import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
14
+ import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
12
15
 
13
16
  const KOTLIN_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
17
+ const KOTLIN_RUN = { translate: exprToKotlin, target: 'Kotlin', dialect: 'kotlin' };
18
+ const KOTLIN_RUNTIME = /Exception in thread|\n\s+at [\w.$]+\(/;
14
19
  // Double params reject bare integer literals, so numeric args carry an explicit decimal.
15
20
  const kotlinLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}${Number.isInteger(Number(v)) ? '.0' : ''}` : litFor(type, v));
21
+ // Kotlin string templates treat `$` specially, so a message literal escapes it.
22
+ const ktStr = (s) => strLit(s).replace(/\$/g, '\\$');
16
23
 
17
- // Write `source` to a .kts file in `dir` and run it with the Kotlin script runner. Returns stdout,
18
- // or null on any failure.
24
+ // Write `source` to a .kts file in `dir` and run it with the Kotlin script runner.
25
+ // Returns { ok, stdout } or { ok: false, failure }.
19
26
  function kotlinRun(dir, source) {
20
27
  const f = join(dir, 'main.kts');
21
28
  writeFileSync(f, source);
22
29
  const env = { ...process.env };
23
- const r = spawnSync('kotlinc', ['-script', f], { encoding: 'utf8', timeout: 300000, env });
24
- if (r.status !== 0) return null;
25
- return r.stdout;
30
+ return spawnStep('kotlinc', ['-script', f], { timeout: 300000, env }, (r) => classifySpawn(r, { tool: 'kotlinc', phase: 'build+run', runtimePattern: KOTLIN_RUNTIME }));
26
31
  }
27
32
 
28
33
  // The emitted Kotlin source (also usable for display / `gen`-parity).
29
- export function emitKotlinModule(ast, cases = buildCases(ast)) {
34
+ export function emitKotlinModule(ast, cases = prepareRun(ast, KOTLIN_RUN).cases, plans = plansFor(ast, exprToKotlin, 'Kotlin')) {
30
35
  const L = [];
31
- const typesByDec = {};
32
- for (const d of ast.decisions || []) {
33
- const names = inputNames(d);
34
- const types = inferInputTypes(ast, d);
35
- typesByDec[d.name] = types;
36
- const params = names.map((n) => `${n}: ${KOTLIN_TYPE[types[n]] || 'String'}`).join(', ');
37
- L.push(`fun ${d.name}(${params}): String {`);
38
- for (const r of d.rules || []) {
39
- let cond; try { cond = exprToKotlin(r.when, { inputs: names }); } catch { cond = 'false'; }
40
- L.push(` if (${cond}) return ${strLit(r.result)}`);
36
+ if ([...plans.values()].some((p) => p.refused)) {
37
+ L.push('// IL-GEN-001: a rule Thunder could not translate throws instead of guessing.');
38
+ L.push('fun thunderUntranslated(message: String): Boolean = throw UnsupportedOperationException(message)', '');
39
+ }
40
+ for (const p of plans.values()) {
41
+ const params = p.names.map((n) => `${n}: ${KOTLIN_TYPE[p.types[n]] || 'String'}`).join(', ');
42
+ L.push(`fun ${p.decision.name}(${params}): String {`);
43
+ for (const { rule: r, code, message } of p.rules) {
44
+ L.push(` if (${code ?? `thunderUntranslated(${ktStr(message)})`}) return ${strLit(r.result)}`);
41
45
  }
42
- L.push(` return ${d.default == null ? '""' : strLit(d.default)}`, '}', '');
46
+ L.push(` return ${p.decision.default == null ? '""' : strLit(p.decision.default)}`, '}', '');
43
47
  }
44
48
  L.push('fun j(s: String?): String {');
45
49
  L.push(' if (s == null) return "null"');
@@ -54,14 +58,14 @@ export function emitKotlinModule(ast, cases = buildCases(ast)) {
54
58
  L.push('}');
55
59
  L.push('');
56
60
  L.push('val sb = StringBuilder("{")');
57
- cases.forEach((c, idx) => {
58
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
59
- if (!dec) return;
60
- const types = typesByDec[c.fn];
61
- const argList = inputNames(dec).map((n) => kotlinLit(types[n], c.given[n])).join(', ');
62
- const sep = idx === 0 ? '' : ',';
63
- L.push(`sb.append(${JSON.stringify(sep)}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
64
- });
61
+ let first = true;
62
+ for (const c of cases) {
63
+ const p = plans.get(c.fn);
64
+ if (!p) continue;
65
+ const argList = p.names.map((n) => argLit(c, p, n, kotlinLit)).join(', ');
66
+ L.push(`sb.append(${JSON.stringify(first ? '' : ',')}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
67
+ first = false;
68
+ }
65
69
  L.push('sb.append("}")');
66
70
  L.push('println(sb.toString())');
67
71
  return L.join('\n');
@@ -73,19 +77,23 @@ export function kotlinAvailable() {
73
77
  try {
74
78
  const src = 'println("{\\"ok\\":\\"1\\"}")';
75
79
  const out = kotlinRun(dir, src);
76
- return !!out && /"ok"/.test(out);
80
+ return out.ok && /"ok"/.test(out.stdout);
77
81
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
78
82
  });
79
83
  }
80
84
 
81
- // Run every decision test case through generated, compiled Kotlin. Returns { "Test / case": actual }
82
- // or null when no usable Kotlin toolchain is present.
85
+ // Run every decision test case through generated, compiled Kotlin. Returns { status: 'ok', results }
86
+ // or a whole-run { status: 'error', kind, message }.
83
87
  export function runKotlinTarget(ast) {
84
- if (!kotlinAvailable()) return null;
85
- const cases = buildCases(ast);
88
+ if (!kotlinAvailable()) return runFailure('missing-toolchain', 'No usable Kotlin toolchain (kotlinc -script) on this machine.');
89
+ const { plans, cases, refused } = prepareRun(ast, KOTLIN_RUN);
90
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
86
91
  const dir = mkdtempSync(join(tmpdir(), 'tl-kt-'));
87
92
  try {
88
- const out = kotlinRun(dir, emitKotlinModule(ast, cases));
89
- return out == null ? null : parseLastJsonObject(out);
93
+ const out = kotlinRun(dir, emitKotlinModule(ast, cases, plans));
94
+ if (!out.ok) return out.failure;
95
+ const parsed = parseLastJsonObject(out.stdout);
96
+ if (!parsed) return runFailure('runtime-error', 'kotlinc ran but printed no results.');
97
+ return finishRun({ cases, parsed, refused, target: 'Kotlin' });
90
98
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
91
99
  }
package/src/target-py.mjs CHANGED
@@ -1,22 +1,17 @@
1
1
  // Python target adapter. Compiles each decision into an executable Python function using the
2
2
  // SAME expression translator the codegen uses (exprToPython), then runs the test cases through a
3
3
  // real `python3` child process and returns actual outputs. Like the TypeScript adapter, this makes
4
- // conformance "grade a live target" rather than "grade fed results" — the generated Python is
5
- // executed for real. Returns null (not a partial result) when python3 is unavailable, so callers
6
- // can report the target as skipped rather than failing.
4
+ // conformance "grade a live target" rather than "grade fed results" , the generated Python is
5
+ // executed for real.
6
+ //
7
+ // Results are honest: the run is { status: 'ok', results } with one { status: 'ok', value } or
8
+ // { status: 'error', kind, message } per case, or { status: 'error', kind, message } for the whole
9
+ // run (python3 missing, a crash, a timeout). An exception in one case is that case's
10
+ // 'runtime-error', never a None answer. A decision with a rule Thunder cannot translate is refused
11
+ // ('not-translated'). Money inputs are decimal.Decimal, never float.
7
12
  import { spawnSync } from 'node:child_process';
8
13
  import { exprToPython } from './expr.mjs';
9
-
10
- const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
11
-
12
- function coerceVal(v) {
13
- if (v == null || typeof v !== 'string') return v;
14
- const s = v.trim();
15
- if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
16
- if (s === 'true') return true;
17
- if (s === 'false') return false;
18
- return v;
19
- }
14
+ import { prepareRun, plansFor, argLit, okResult, errorResult, runFailure, classifySpawn, parseLastJsonObject } from './target-util.mjs';
20
15
 
21
16
  // True when a runnable python3 interpreter is present on this machine.
22
17
  export function pythonAvailable() {
@@ -28,14 +23,27 @@ export function pythonAvailable() {
28
23
  }
29
24
  }
30
25
 
26
+ // A Python literal for a coerced example value.
27
+ function pyLit(type, v) {
28
+ if (v == null) return 'None';
29
+ if (typeof v === 'boolean') return v ? 'True' : 'False';
30
+ if (typeof v === 'number') return String(v);
31
+ return JSON.stringify(String(v)); // JSON string escapes are valid Python string escapes
32
+ }
33
+
31
34
  // The emitted Python source (for display / gen-parity).
32
- export function emitPythonModule(ast) {
35
+ export function emitPythonModule(ast, plans = plansFor(ast, exprToPython, 'Python')) {
33
36
  const L = ['# Executable Python target compiled from the decision(s). Deterministic, no AI.'];
34
- for (const d of ast.decisions || []) {
35
- L.push(`def ${d.name}(${inputNames(d).join(', ')}):`);
36
- for (const r of d.rules || []) {
37
- let cond; try { cond = exprToPython(r.when, { inputs: inputNames(d) }); } catch { cond = 'False'; }
38
- L.push(` if ${cond}: return ${JSON.stringify(r.result)}`);
37
+ const list = [...plans.values()];
38
+ if (list.some((p) => Object.keys(p.money).length)) L.push('from decimal import Decimal');
39
+ if (list.some((p) => p.refused)) {
40
+ L.push('def _thunder_untranslated(message):', ' raise NotImplementedError(message)', '');
41
+ }
42
+ for (const p of list) {
43
+ const d = p.decision;
44
+ L.push(`def ${d.name}(${p.names.join(', ')}):`);
45
+ for (const { rule: r, code, message } of p.rules) {
46
+ L.push(` if ${code ?? `_thunder_untranslated(${JSON.stringify(message)})`}: return ${JSON.stringify(r.result)}`);
39
47
  }
40
48
  L.push(` return ${d.default == null ? 'None' : JSON.stringify(d.default)}`);
41
49
  L.push('');
@@ -43,48 +51,42 @@ export function emitPythonModule(ast) {
43
51
  return L.join('\n');
44
52
  }
45
53
 
46
- // Run every decision test case through generated Python. Returns { "Test / case": actual },
47
- // or null if python3 is unavailable or the interpreter failed to run the program.
54
+ // Run every decision test case through generated Python. See the header for the result shape.
48
55
  export function runPythonTarget(ast) {
49
- if (!pythonAvailable()) return null;
56
+ if (!pythonAvailable()) return runFailure('missing-toolchain', 'python3 is not installed or not on PATH.');
57
+ const { plans, cases, refused } = prepareRun(ast, { translate: exprToPython, target: 'Python', dialect: 'python' });
58
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
50
59
 
51
- // Build the list of calls to make, one per test case, in a stable order.
52
- const cases = [];
53
- for (const t of ast.tests || []) {
54
- const dec = (ast.decisions || []).find((d) => d.name === t.name);
55
- if (!dec) continue;
56
- const names = inputNames(dec);
57
- for (const c of t.cases || []) {
58
- cases.push({
59
- key: `${t.name} / ${c.name || 'case'}`,
60
- fn: t.name,
61
- args: names.map((n) => coerceVal((c.given || {})[n])),
62
- });
63
- }
64
- }
65
-
66
- // Emit a self-contained program: decision defs + a driver that runs each case and prints JSON.
67
- // Cases (with already-coerced arg types) are handed in as a JSON literal parsed by json.loads,
68
- // so Python receives real ints/floats/bools/strings rather than stringified values.
60
+ // Each case is a zero-argument lambda with literal, already-typed arguments (Decimal for Money),
61
+ // run under its own try so one failing case reports an error instead of a None answer.
69
62
  const program = [
70
- 'import json',
71
- emitPythonModule(ast),
72
- `CASES = json.loads(${JSON.stringify(JSON.stringify(cases))})`,
63
+ 'import json, traceback',
64
+ emitPythonModule(ast, plans),
65
+ 'CASES = [',
66
+ ...cases.map((c) => {
67
+ const p = plans.get(c.fn);
68
+ return ` (${JSON.stringify(c.key)}, lambda: ${c.fn}(${p.names.map((n) => argLit(c, p, n, pyLit)).join(', ')})),`;
69
+ }),
70
+ ']',
73
71
  'out = {}',
74
- 'for c in CASES:',
75
- ' fn = globals().get(c["fn"])',
72
+ 'for key, call in CASES:',
76
73
  ' try:',
77
- ' out[c["key"]] = fn(*c["args"]) if callable(fn) else None',
78
- ' except Exception:',
79
- ' out[c["key"]] = None',
80
- 'print(json.dumps(out))',
74
+ ' out[key] = {"ok": call()}',
75
+ ' except Exception as e:',
76
+ ' out[key] = {"error": type(e).__name__ + ": " + str(e)}',
77
+ 'print(json.dumps(out, default=str))',
81
78
  ].join('\n');
82
79
 
83
80
  const res = spawnSync('python3', ['-'], { input: program, encoding: 'utf8', timeout: 30000 });
84
- if (res.status !== 0 || !res.stdout) return null;
85
- try {
86
- return JSON.parse(res.stdout.trim().split('\n').pop());
87
- } catch {
88
- return null;
81
+ if (res.status !== 0 || res.error) return classifySpawn(res, { tool: 'python3', phase: 'build+run', runtimePattern: /Traceback|Error:/ });
82
+ const parsed = parseLastJsonObject(res.stdout);
83
+ if (!parsed) return runFailure('runtime-error', `python3 ran but printed no results: ${(res.stderr || res.stdout || '').trim().slice(-400)}`);
84
+ const results = { ...refused };
85
+ for (const c of cases) {
86
+ const r = parsed[c.key];
87
+ if (r && Object.prototype.hasOwnProperty.call(r, 'ok')) results[c.key] = okResult(r.ok);
88
+ else if (r && r.error) results[c.key] = errorResult('runtime-error', `The generated Python raised while running ${c.key}: ${r.error}`);
89
+ else results[c.key] = errorResult('runtime-error', `python3 reported no result for ${c.key}.`);
89
90
  }
91
+ return { status: 'ok', results };
90
92
  }
@@ -0,0 +1,48 @@
1
+ /** The stable diagnostic code for a rule condition a target could not translate. */
2
+ export const GEN_UNTRANSLATED: 'IL-GEN-001';
3
+
4
+ /** Why a generated or executed case did not produce an answer. */
5
+ export type TargetErrorKind =
6
+ | 'missing-toolchain'
7
+ | 'compile-failed'
8
+ | 'runtime-error'
9
+ | 'timeout'
10
+ | 'assertion-failed'
11
+ | 'not-translated'
12
+ | 'missing-input';
13
+ export const ERROR_KINDS: TargetErrorKind[];
14
+
15
+ /**
16
+ * One case's result. A real null answer is `{ status: 'ok', value: null }`; a failure is always
17
+ * `{ status: 'error', kind, message }`, never a null value.
18
+ */
19
+ export type CaseResult =
20
+ | { status: 'ok'; value: unknown }
21
+ | { status: 'error'; kind: TargetErrorKind; message: string };
22
+
23
+ /** A live target run: per-case results, or a whole-run failure (toolchain missing, compile failure, crash, timeout). */
24
+ export type TargetRun =
25
+ | { status: 'ok'; results: Record<string, CaseResult> }
26
+ | { status: 'error'; kind: TargetErrorKind; message: string };
27
+
28
+ /** An IL-GEN-001 generation diagnostic. */
29
+ export interface GenerationDiagnostic {
30
+ code: 'IL-GEN-001';
31
+ severity: 'error';
32
+ message: string;
33
+ target: string;
34
+ decision: string | null;
35
+ rule: string | null;
36
+ condition: string | null;
37
+ reason: string;
38
+ }
39
+
40
+ export function okResult(value: unknown): CaseResult;
41
+ export function errorResult(kind: TargetErrorKind, message: string): CaseResult;
42
+ export function isCaseResult(v: unknown): v is CaseResult;
43
+ export function untranslatedMessage(when: string, target: string, reason: string): string;
44
+ export function runFailure(kind: TargetErrorKind, message: string): TargetRun;
45
+ export function finishRun(args: { cases: Array<{ key: string }>; parsed: Record<string, unknown> | null; refused?: Record<string, CaseResult>; target: string }): TargetRun;
46
+ export function classifySpawn(r: unknown, opts?: { tool?: string; phase?: 'compile' | 'run' | 'build+run'; runtimePattern?: RegExp | null }): TargetRun;
47
+ /** Plain values of a run's ok cases (errors dropped); null for a whole-run failure. */
48
+ export function runValues(run: TargetRun | null): Record<string, unknown> | null;
@@ -0,0 +1,112 @@
1
+ // Honest results for generated and executed code. Browser-safe (no Node imports).
2
+ //
3
+ // Two rules live here:
4
+ // 1. A rule condition Thunder cannot translate is never replaced by `false`. Generation reports
5
+ // IL-GEN-001 for that rule; scaffolds emit code that throws with the same message; executable
6
+ // targets refuse to run that decision and report "not translated", never an answer.
7
+ // 2. Running a target never turns a failure into a value. Every case comes back as
8
+ // { status: 'ok', value } or { status: 'error', kind, message }, so a real null answer is
9
+ // distinguishable from a missing toolchain, a compile failure, a crash, or a timeout.
10
+
11
+ export const GEN_UNTRANSLATED = 'IL-GEN-001';
12
+
13
+ export const ERROR_KINDS = ['missing-toolchain', 'compile-failed', 'runtime-error', 'timeout', 'assertion-failed', 'not-translated', 'missing-input'];
14
+
15
+ export const okResult = (value) => ({ status: 'ok', value: value === undefined ? null : value });
16
+ export const errorResult = (kind, message) => ({ status: 'error', kind, message: String(message || kind) });
17
+
18
+ /** True for a per-case result object ({status:'ok', value} | {status:'error', kind, message}). */
19
+ export function isCaseResult(v) {
20
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return false;
21
+ if (v.status === 'ok') return 'value' in v;
22
+ return v.status === 'error' && ERROR_KINDS.includes(v.kind);
23
+ }
24
+
25
+ /** The one wording every surface uses for an untranslated condition. */
26
+ export function untranslatedMessage(when, target, reason) {
27
+ return `Thunder could not translate the condition '${when}' for ${target}: ${reason}`;
28
+ }
29
+
30
+ /**
31
+ * Translate one rule condition. Returns { ok: true, code } or { ok: false, diagnostic } where the
32
+ * diagnostic is an IL-GEN-001 error naming the decision, rule, target, and reason.
33
+ */
34
+ export function translateRule(translate, rule, opts, { target, decision }) {
35
+ try {
36
+ return { ok: true, code: translate(rule.when, opts) };
37
+ } catch (err) {
38
+ const reason = String((err && err.message) || err || 'unknown error');
39
+ const message = untranslatedMessage(rule.when, target, reason);
40
+ return {
41
+ ok: false,
42
+ message,
43
+ diagnostic: {
44
+ code: GEN_UNTRANSLATED, severity: 'error', message,
45
+ target, decision: decision ?? null, rule: rule.name ?? null, condition: rule.when ?? null, reason,
46
+ },
47
+ };
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Every rule a target cannot translate, as IL-GEN-001 diagnostics. `optsFor(decision)` supplies the
53
+ * translator options for a decision (inputs, money names).
54
+ */
55
+ export function untranslatedRules(ast, translate, target, optsFor) {
56
+ const out = [];
57
+ for (const d of ast.decisions || []) {
58
+ const opts = optsFor(d);
59
+ for (const r of d.rules || []) {
60
+ const t = translateRule(translate, r, opts, { target, decision: d.name });
61
+ if (!t.ok) out.push(t.diagnostic);
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+
67
+ /** Map decision name -> first untranslated message, for runners that must refuse those decisions. */
68
+ export function untranslatedByDecision(diagnostics) {
69
+ const m = new Map();
70
+ for (const d of diagnostics) if (!m.has(d.decision)) m.set(d.decision, d.message);
71
+ return m;
72
+ }
73
+
74
+ /**
75
+ * Assemble a target run. `cases` are the cases the program actually ran; `parsed` is the JSON object
76
+ * the program printed ({ key: value }), or null when it printed nothing usable; `refused` holds the
77
+ * not-translated case results. A key the program did not report is an error, never a null answer.
78
+ */
79
+ export function finishRun({ cases, parsed, refused = {}, target }) {
80
+ const results = { ...refused };
81
+ for (const c of cases) {
82
+ if (parsed && Object.prototype.hasOwnProperty.call(parsed, c.key)) results[c.key] = okResult(parsed[c.key]);
83
+ else results[c.key] = errorResult('runtime-error', `${target} ran but reported no result for ${c.key}.`);
84
+ }
85
+ return { status: 'ok', results };
86
+ }
87
+
88
+ /** A whole-run failure (the toolchain is missing, the program did not compile, it crashed or timed out). */
89
+ export const runFailure = (kind, message) => ({ status: 'error', kind, message: String(message || kind) });
90
+
91
+ /**
92
+ * Classify a failed child process. `phase` is 'compile', 'run', or 'build+run' (one command that both
93
+ * compiles and runs, such as `go run`); for that phase the output decides which half failed.
94
+ */
95
+ export function classifySpawn(r, { tool, phase = 'build+run', runtimePattern = null } = {}) {
96
+ const code = r && r.error && r.error.code;
97
+ if (code === 'ENOENT') return runFailure('missing-toolchain', `${tool} is not installed or not on PATH.`);
98
+ if (code === 'ETIMEDOUT' || (r && r.signal === 'SIGTERM' && r.status == null)) return runFailure('timeout', `${tool} did not finish in time${r.signal ? ` (stopped by ${r.signal})` : ''}.`);
99
+ const tail = String((r && (r.stderr || r.stdout)) || (r && r.error && r.error.message) || '').trim().split('\n').slice(-12).join('\n').slice(-1200);
100
+ let kind = phase === 'compile' ? 'compile-failed' : 'runtime-error';
101
+ if (phase === 'build+run') kind = runtimePattern && runtimePattern.test(tail) ? 'runtime-error' : 'compile-failed';
102
+ const what = kind === 'compile-failed' ? 'could not compile the generated code' : 'crashed while running the generated code';
103
+ return runFailure(kind, `${tool} ${what}${r && r.status != null ? ` (exit ${r.status})` : ''}${tail ? `: ${tail}` : '.'}`);
104
+ }
105
+
106
+ /** Plain values for a run's ok cases ({ key: value }), dropping errors. For display and legacy callers. */
107
+ export function runValues(run) {
108
+ if (!run || run.status !== 'ok') return null;
109
+ const out = {};
110
+ for (const [k, v] of Object.entries(run.results)) if (v.status === 'ok') out[k] = v.value;
111
+ return out;
112
+ }