@skillstech/thunderlang 1.0.3 → 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 (74) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/dist/core.cjs +13779 -10043
  3. package/dist/index.cjs +28500 -24392
  4. package/dist/learn.cjs +12853 -9579
  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/libraries.mjs +2 -2
  33. package/src/mcp.mjs +23 -0
  34. package/src/meaning.mjs +47 -7
  35. package/src/model.d.mts +7 -3
  36. package/src/model.mjs +30 -9
  37. package/src/money.d.mts +18 -0
  38. package/src/money.mjs +124 -0
  39. package/src/plain-contract.mjs +18 -2
  40. package/src/powershell.mjs +24 -5
  41. package/src/read-repo.mjs +1 -0
  42. package/src/read.d.mts +11 -0
  43. package/src/read.mjs +121 -13
  44. package/src/review-comment.d.mts +16 -0
  45. package/src/review-comment.mjs +145 -0
  46. package/src/rlang.mjs +10 -3
  47. package/src/say-less.mjs +1432 -0
  48. package/src/shell.mjs +45 -8
  49. package/src/sql-proc.mjs +1198 -0
  50. package/src/sql.mjs +87 -119
  51. package/src/steps.mjs +188 -37
  52. package/src/system.mjs +153 -44
  53. package/src/target-cs.mjs +39 -34
  54. package/src/target-elixir.mjs +40 -30
  55. package/src/target-go.mjs +41 -36
  56. package/src/target-java.mjs +34 -27
  57. package/src/target-kotlin.mjs +43 -35
  58. package/src/target-py.mjs +57 -55
  59. package/src/target-result.d.mts +48 -0
  60. package/src/target-result.mjs +112 -0
  61. package/src/target-rust.mjs +42 -38
  62. package/src/target-scala.mjs +45 -35
  63. package/src/target-ts.mjs +37 -45
  64. package/src/target-types.mjs +41 -5
  65. package/src/target-util.mjs +55 -2
  66. package/src/trace-cli.mjs +58 -0
  67. package/src/trace-fs.mjs +76 -0
  68. package/src/trace.mjs +261 -0
  69. package/src/translate.d.mts +3 -0
  70. package/src/translate.mjs +62 -32
  71. package/src/why-cli.mjs +31 -0
  72. package/src/why.d.mts +28 -0
  73. package/src/why.mjs +532 -0
  74. package/src/write-steps.mjs +22 -5
@@ -1,50 +1,50 @@
1
1
  // Rust target adapter. Emits a self-contained single-file program that defines each decision as a
2
2
  // typed fn (using the same exprToRust translator the codegen uses), calls every test case with
3
3
  // typed literal arguments, and prints the results as one JSON line. It compiles with `rustc` and
4
- // runs the produced binary, so a live Rust run grades real compiled + executed code. Returns null
5
- // (skip cleanly) when no usable Rust toolchain exists.
6
- import { spawnSync } from 'node:child_process';
4
+ // runs the produced binary, so a live Rust run grades real compiled + executed code.
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'). Money inputs are i64 minor units, never floats.
7
9
  import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
10
  import { join } from 'node:path';
9
11
  import { tmpdir } from 'node:os';
10
12
  import { exprToRust } from './expr.mjs';
11
- import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
13
+ import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
12
14
 
13
- const RUST_TYPE = { number: 'f64', bool: 'bool', string: '&str' };
15
+ const RUST_TYPE = { number: 'f64', bool: 'bool', string: '&str', money: 'i64' };
16
+ const RUST_RUN = { translate: exprToRust, target: 'Rust', dialect: 'rust' };
14
17
  // f64 params reject bare integer literals, so numeric args carry an explicit f64 suffix.
15
18
  const rustLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}f64` : litFor(type, v));
16
19
 
17
- // Compile `source` with rustc and run the binary. Returns stdout, or null on any failure.
20
+ // Compile `source` with rustc and run the binary. Returns { ok, stdout } or { ok: false, failure }.
18
21
  function rustcRun(dir, source) {
19
22
  const src = join(dir, 'main.rs');
20
23
  const bin = join(dir, process.platform === 'win32' ? 'main.exe' : 'main_bin');
21
24
  writeFileSync(src, source);
22
25
  const env = { ...process.env };
23
- const c = spawnSync('rustc', ['-O', src, '-o', bin], { encoding: 'utf8', timeout: 180000, env });
24
- if (c.status !== 0) return null;
25
- const r = spawnSync(bin, [], { encoding: 'utf8', timeout: 60000, env });
26
- if (r.status !== 0) return null;
27
- return r.stdout;
26
+ const c = spawnStep('rustc', ['-O', src, '-o', bin], { timeout: 180000, env }, (r) => classifySpawn(r, { tool: 'rustc', phase: 'compile' }));
27
+ if (!c.ok) return c;
28
+ return spawnStep(bin, [], { timeout: 60000, env }, (r) => classifySpawn(r, { tool: 'the compiled Rust program', phase: 'run' }));
28
29
  }
29
30
 
30
31
  // The emitted Rust source (also usable for display / `gen`-parity).
31
- export function emitRustModule(ast, cases = buildCases(ast)) {
32
+ export function emitRustModule(ast, cases = prepareRun(ast, RUST_RUN).cases, plans = plansFor(ast, exprToRust, 'Rust')) {
32
33
  const L = [
33
34
  '#![allow(non_snake_case, unused_parens, dead_code, unused_variables)]',
34
35
  '',
35
36
  ];
36
- const typesByDec = {};
37
- for (const d of ast.decisions || []) {
38
- const names = inputNames(d);
39
- const types = inferInputTypes(ast, d);
40
- typesByDec[d.name] = types;
41
- const params = names.map((n) => `${n}: ${RUST_TYPE[types[n]] || '&str'}`).join(', ');
42
- L.push(`fn ${d.name}(${params}) -> &'static str {`);
43
- for (const r of d.rules || []) {
44
- let cond; try { cond = exprToRust(r.when, { inputs: names }); } catch { cond = 'false'; }
45
- L.push(` if ${cond} { return ${strLit(r.result)}; }`);
37
+ if ([...plans.values()].some((p) => p.refused)) {
38
+ L.push('// IL-GEN-001: a rule Thunder could not translate panics instead of guessing.');
39
+ L.push('fn thunder_untranslated(message: &str) -> bool {', ' panic!("{}", message)', '}', '');
40
+ }
41
+ for (const p of plans.values()) {
42
+ const params = p.names.map((n) => `${n}: ${RUST_TYPE[p.types[n]] || '&str'}`).join(', ');
43
+ L.push(`fn ${p.decision.name}(${params}) -> &'static str {`);
44
+ for (const { rule: r, code, message } of p.rules) {
45
+ L.push(` if ${code ?? `thunder_untranslated(${strLit(message)})`} { return ${strLit(r.result)}; }`);
46
46
  }
47
- L.push(` return ${d.default == null ? '""' : strLit(d.default)};`, '}', '');
47
+ L.push(` return ${p.decision.default == null ? '""' : strLit(p.decision.default)};`, '}', '');
48
48
  }
49
49
  L.push('fn j(s: &str) -> String {');
50
50
  L.push(' let mut out = String::from("\\"");');
@@ -61,14 +61,14 @@ export function emitRustModule(ast, cases = buildCases(ast)) {
61
61
  L.push('');
62
62
  L.push('fn main() {');
63
63
  L.push(' let mut sb = String::from("{");');
64
- cases.forEach((c, idx) => {
65
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
66
- if (!dec) return;
67
- const types = typesByDec[c.fn];
68
- const argList = inputNames(dec).map((n) => rustLit(types[n], c.given[n])).join(', ');
69
- const sep = idx === 0 ? '' : ',';
70
- L.push(` sb.push_str(&format!("{}{}:{}", ${JSON.stringify(sep)}, j(${strLit(c.key)}), j(${c.fn}(${argList}))));`);
71
- });
64
+ let first = true;
65
+ for (const c of cases) {
66
+ const p = plans.get(c.fn);
67
+ if (!p) continue;
68
+ const argList = p.names.map((n) => argLit(c, p, n, rustLit)).join(', ');
69
+ L.push(` sb.push_str(&format!("{}{}:{}", ${JSON.stringify(first ? '' : ',')}, j(${strLit(c.key)}), j(${c.fn}(${argList}))));`);
70
+ first = false;
71
+ }
72
72
  L.push(' sb.push_str("}");');
73
73
  L.push(' println!("{}", sb);');
74
74
  L.push('}');
@@ -81,19 +81,23 @@ export function rustAvailable() {
81
81
  try {
82
82
  const src = 'fn main() {\n println!("{}", "{\\"ok\\":\\"1\\"}");\n}';
83
83
  const out = rustcRun(dir, src);
84
- return !!out && /"ok"/.test(out);
84
+ return out.ok && /"ok"/.test(out.stdout);
85
85
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
86
86
  });
87
87
  }
88
88
 
89
- // Run every decision test case through generated, compiled Rust. Returns { "Test / case": actual }
90
- // or null when no usable Rust toolchain is present.
89
+ // Run every decision test case through generated, compiled Rust. Returns { status: 'ok', results }
90
+ // or a whole-run { status: 'error', kind, message }.
91
91
  export function runRustTarget(ast) {
92
- if (!rustAvailable()) return null;
93
- const cases = buildCases(ast);
92
+ if (!rustAvailable()) return runFailure('missing-toolchain', 'No usable Rust toolchain (rustc) on this machine.');
93
+ const { plans, cases, refused } = prepareRun(ast, RUST_RUN);
94
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
94
95
  const dir = mkdtempSync(join(tmpdir(), 'tl-rust-'));
95
96
  try {
96
- const out = rustcRun(dir, emitRustModule(ast, cases));
97
- return out == null ? null : parseLastJsonObject(out);
97
+ const out = rustcRun(dir, emitRustModule(ast, cases, plans));
98
+ if (!out.ok) return out.failure;
99
+ const parsed = parseLastJsonObject(out.stdout);
100
+ if (!parsed) return runFailure('runtime-error', 'The compiled Rust program printed no results.');
101
+ return finishRun({ cases, parsed, refused, target: 'Rust' });
98
102
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
99
103
  }
@@ -1,48 +1,54 @@
1
1
  // Scala target adapter. Emits a self-contained Scala script that defines each decision as a typed
2
2
  // def (using the same exprToScala translator the codegen uses), calls every test case with typed
3
3
  // literal arguments, and prints the results as one JSON line. It runs through `scala` (falling back
4
- // to `scala-cli run`), so a live Scala run grades real compiled + executed code. Returns null (skip
5
- // cleanly) when no usable Scala toolchain exists.
6
- import { spawnSync } from 'node:child_process';
4
+ // to `scala-cli run`), so a live Scala run grades real compiled + executed code.
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'). Scala 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 { exprToScala } 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 SCALA_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
17
+ const SCALA_RUN = { translate: exprToScala, target: 'Scala', dialect: 'scala' };
18
+ const SCALA_RUNTIME = /Exception in thread|\n\s+at [\w.$]+\(/;
14
19
  // Which runner worked during the smoke, so run reuses it: [cmd, argsFor(file)].
15
20
  let SCALA_RUNNER = null;
16
21
 
17
22
  // Write `source` to a .scala file in `dir` and run it. Prefers `scala` (script mode); falls back to
18
- // `scala-cli run`. Returns stdout, or null on any failure.
23
+ // `scala-cli run`. Returns { ok, stdout } or { ok: false, failure } (the last runner's failure).
19
24
  function scalaRun(dir, source) {
20
25
  const f = join(dir, 'Main.scala');
21
26
  writeFileSync(f, source);
22
27
  const env = { ...process.env };
23
28
  const runners = SCALA_RUNNER ? [SCALA_RUNNER] : [['scala', (p) => [p]], ['scala-cli', (p) => ['run', p]]];
29
+ let last = { ok: false, failure: runFailure('missing-toolchain', 'Neither scala nor scala-cli is installed or on PATH.') };
24
30
  for (const [cmd, argsFor] of runners) {
25
- const r = spawnSync(cmd, argsFor(f), { encoding: 'utf8', timeout: 300000, env });
26
- if (r.status === 0 && r.stdout) { SCALA_RUNNER = [cmd, argsFor]; return r.stdout; }
31
+ const r = spawnStep(cmd, argsFor(f), { timeout: 300000, env }, (x) => classifySpawn(x, { tool: cmd, phase: 'build+run', runtimePattern: SCALA_RUNTIME }));
32
+ if (r.ok && r.stdout) { SCALA_RUNNER = [cmd, argsFor]; return r; }
33
+ if (!r.ok && (r.failure.kind !== 'missing-toolchain' || last.failure.kind === 'missing-toolchain')) last = r;
27
34
  }
28
- return null;
35
+ return last;
29
36
  }
30
37
 
31
38
  // The emitted Scala source (also usable for display / `gen`-parity).
32
- export function emitScalaModule(ast, cases = buildCases(ast)) {
39
+ export function emitScalaModule(ast, cases = prepareRun(ast, SCALA_RUN).cases, plans = plansFor(ast, exprToScala, 'Scala')) {
33
40
  const L = [];
34
- const typesByDec = {};
35
- for (const d of ast.decisions || []) {
36
- const names = inputNames(d);
37
- const types = inferInputTypes(ast, d);
38
- typesByDec[d.name] = types;
39
- const params = names.map((n) => `${n}: ${SCALA_TYPE[types[n]] || 'String'}`).join(', ');
40
- L.push(`def ${d.name}(${params}): String = {`);
41
- for (const r of d.rules || []) {
42
- let cond; try { cond = exprToScala(r.when, { inputs: names }); } catch { cond = 'false'; }
43
- L.push(` if (${cond}) return ${strLit(r.result)}`);
41
+ if ([...plans.values()].some((p) => p.refused)) {
42
+ L.push('// IL-GEN-001: a rule Thunder could not translate throws instead of guessing.');
43
+ L.push('def thunderUntranslated(message: String): Boolean = throw new UnsupportedOperationException(message)', '');
44
+ }
45
+ for (const p of plans.values()) {
46
+ const params = p.names.map((n) => `${n}: ${SCALA_TYPE[p.types[n]] || 'String'}`).join(', ');
47
+ L.push(`def ${p.decision.name}(${params}): String = {`);
48
+ for (const { rule: r, code, message } of p.rules) {
49
+ L.push(` if (${code ?? `thunderUntranslated(${strLit(message)})`}) return ${strLit(r.result)}`);
44
50
  }
45
- L.push(` return ${d.default == null ? 'null' : strLit(d.default)}`, '}', '');
51
+ L.push(` return ${p.decision.default == null ? 'null' : strLit(p.decision.default)}`, '}', '');
46
52
  }
47
53
  L.push('def j(s: String): String = {');
48
54
  L.push(' if (s == null) return "null"');
@@ -56,14 +62,14 @@ export function emitScalaModule(ast, cases = buildCases(ast)) {
56
62
  L.push('}');
57
63
  L.push('');
58
64
  L.push('val sb = new StringBuilder("{")');
59
- cases.forEach((c, idx) => {
60
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
61
- if (!dec) return;
62
- const types = typesByDec[c.fn];
63
- const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
64
- const sep = idx === 0 ? '' : ',';
65
- L.push(`sb.append(${JSON.stringify(sep)}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
66
- });
65
+ let first = true;
66
+ for (const c of cases) {
67
+ const p = plans.get(c.fn);
68
+ if (!p) continue;
69
+ const argList = p.names.map((n) => argLit(c, p, n, litFor)).join(', ');
70
+ L.push(`sb.append(${JSON.stringify(first ? '' : ',')}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
71
+ first = false;
72
+ }
67
73
  L.push('sb.append("}")');
68
74
  L.push('println(sb.toString)');
69
75
  return L.join('\n');
@@ -75,19 +81,23 @@ export function scalaAvailable() {
75
81
  try {
76
82
  const src = 'println("{\\"ok\\":\\"1\\"}")';
77
83
  const out = scalaRun(dir, src);
78
- return !!out && /"ok"/.test(out);
84
+ return out.ok && /"ok"/.test(out.stdout);
79
85
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
80
86
  });
81
87
  }
82
88
 
83
- // Run every decision test case through generated, compiled Scala. Returns { "Test / case": actual }
84
- // or null when no usable Scala toolchain is present.
89
+ // Run every decision test case through generated, compiled Scala. Returns { status: 'ok', results }
90
+ // or a whole-run { status: 'error', kind, message }.
85
91
  export function runScalaTarget(ast) {
86
- if (!scalaAvailable()) return null;
87
- const cases = buildCases(ast);
92
+ if (!scalaAvailable()) return runFailure('missing-toolchain', 'No usable Scala toolchain (scala or scala-cli) on this machine.');
93
+ const { plans, cases, refused } = prepareRun(ast, SCALA_RUN);
94
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
88
95
  const dir = mkdtempSync(join(tmpdir(), 'tl-scala-'));
89
96
  try {
90
- const out = scalaRun(dir, emitScalaModule(ast, cases));
91
- return out == null ? null : parseLastJsonObject(out);
97
+ const out = scalaRun(dir, emitScalaModule(ast, cases, plans));
98
+ if (!out.ok) return out.failure;
99
+ const parsed = parseLastJsonObject(out.stdout);
100
+ if (!parsed) return runFailure('runtime-error', 'scala ran but printed no results.');
101
+ return finishRun({ cases, parsed, refused, target: 'Scala' });
92
102
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
93
103
  }
package/src/target-ts.mjs CHANGED
@@ -3,64 +3,56 @@
3
3
  // through the generated code and returns actual outputs. This turns conformance from "grade fed
4
4
  // results" into "grade a live target": the generated implementation is executed for real.
5
5
  // Type annotations are erased at runtime, so running the type-stripped JS is faithful to the TS.
6
+ //
7
+ // Results are honest: every case is { status: 'ok', value } or { status: 'error', kind, message }.
8
+ // A decision with a rule Thunder cannot translate is refused ('not-translated'), never run with a
9
+ // stand-in `false`. Money inputs are exact bigint minor units, never floats.
6
10
  import { exprToJs } from './expr.mjs';
7
-
8
- const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
9
-
10
- function coerceVal(v) {
11
- if (v == null || typeof v !== 'string') return v;
12
- const s = v.trim();
13
- if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
14
- if (s === 'true') return true;
15
- if (s === 'false') return false;
16
- return v;
17
- }
11
+ import { planDecision } from './target-types.mjs';
12
+ import { okResult, errorResult } from './target-result.mjs';
13
+ import { prepareRun } from './target-util.mjs';
18
14
 
19
15
  // The emitted source (for display / `gen`-parity); the runtime uses new Function on the body.
20
16
  export function emitDecisionModule(ast) {
21
17
  const L = ['// Executable target compiled from the decision(s). Deterministic, no AI.'];
22
- for (const d of ast.decisions || []) {
23
- L.push(`export function ${d.name}(${inputNames(d).join(', ')}) {`);
24
- for (const r of d.rules || []) {
25
- let cond; try { cond = exprToJs(r.when, { inputs: inputNames(d) }); } catch { cond = 'false'; }
26
- L.push(` if (${cond}) return ${JSON.stringify(r.result)};`);
18
+ const plans = (ast.decisions || []).map((d) => planDecision(ast, d, { translate: exprToJs, target: 'TypeScript' }));
19
+ if (plans.some((p) => p.refused)) L.push('function thunderUntranslated(message) { throw new Error(message); }');
20
+ for (const p of plans) {
21
+ L.push(`export function ${p.decision.name}(${p.names.join(', ')}) {`);
22
+ for (const { rule: r, code, message } of p.rules) {
23
+ L.push(` if (${code ?? `thunderUntranslated(${JSON.stringify(message)})`}) return ${JSON.stringify(r.result)};`);
27
24
  }
28
- L.push(` return ${JSON.stringify(d.default ?? null)};`, '}');
25
+ L.push(` return ${JSON.stringify(p.decision.default ?? null)};`, '}');
29
26
  }
30
27
  return L.join('\n');
31
28
  }
32
29
 
33
- // Compile each decision to a runnable function.
34
- function compileDecisionFns(ast) {
35
- const fns = {};
36
- for (const d of ast.decisions || []) {
37
- const names = inputNames(d);
38
- const body = [];
39
- for (const r of d.rules || []) {
40
- let cond; try { cond = exprToJs(r.when, { inputs: names }); } catch { cond = 'false'; }
41
- body.push(`if (${cond}) return ${JSON.stringify(r.result)};`);
42
- }
43
- body.push(`return ${JSON.stringify(d.default ?? null)};`);
44
- try { fns[d.name] = new Function(...names, body.join('\n')); } catch { fns[d.name] = null; }
45
- }
46
- return fns;
30
+ // Compile one planned (fully translated) decision to a runnable function.
31
+ function compileDecisionFn(p) {
32
+ const body = p.rules.map(({ rule: r, code }) => `if (${code}) return ${JSON.stringify(r.result)};`);
33
+ body.push(`return ${JSON.stringify(p.decision.default ?? null)};`);
34
+ return new Function(...p.names, body.join('\n'));
47
35
  }
48
36
 
49
- // Run every decision test case through the generated code. Returns { "Test / case": actual }.
37
+ /**
38
+ * Run every decision test case through the generated code.
39
+ * Returns { status: 'ok', results: { "Test / case": {status:'ok', value} | {status:'error', kind, message} } }.
40
+ */
50
41
  export function runTypescriptTarget(ast) {
51
- const fns = compileDecisionFns(ast);
52
- const out = {};
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
- const fn = fns[t.name];
58
- for (const c of t.cases || []) {
59
- const key = `${t.name} / ${c.name || 'case'}`;
60
- if (typeof fn !== 'function') { out[key] = null; continue; }
61
- const args = names.map((n) => coerceVal((c.given || {})[n]));
62
- try { out[key] = fn(...args); } catch { out[key] = null; }
42
+ const { plans, cases, refused } = prepareRun(ast, { translate: exprToJs, target: 'TypeScript', dialect: 'js-runtime' });
43
+ const results = { ...refused };
44
+ const fns = new Map();
45
+ for (const c of cases) {
46
+ const p = plans.get(c.fn);
47
+ if (!fns.has(c.fn)) {
48
+ try { fns.set(c.fn, { fn: compileDecisionFn(p) }); }
49
+ catch (e) { fns.set(c.fn, { error: `TypeScript could not compile the generated decision ${c.fn}: ${e.message}` }); }
63
50
  }
51
+ const compiled = fns.get(c.fn);
52
+ if (compiled.error) { results[c.key] = errorResult('compile-failed', compiled.error); continue; }
53
+ const args = p.names.map((n) => (c.moneyArgs[n] != null ? c.moneyArgs[n] : c.given[n]));
54
+ try { results[c.key] = okResult(compiled.fn(...args)); }
55
+ catch (e) { results[c.key] = errorResult('runtime-error', `The generated TypeScript threw while running ${c.key}: ${e && e.message ? e.message : e}`); }
64
56
  }
65
- return out;
57
+ return { status: 'ok', results };
66
58
  }
@@ -1,5 +1,7 @@
1
1
  // Browser-safe helpers shared by the target adapters and the in-browser translator.
2
2
  // No Node imports here, so the website can bundle this file.
3
+ import { moneyTypeMinorUnits } from './money.mjs';
4
+ import { translateRule } from './target-result.mjs';
3
5
 
4
6
  export const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
5
7
 
@@ -20,18 +22,21 @@ export function buildCases(ast) {
20
22
  if (!dec) continue;
21
23
  const names = inputNames(dec);
22
24
  for (const c of t.cases || []) {
23
- const given = {};
24
- for (const n of names) given[n] = coerceVal((c.given || {})[n]);
25
- cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given });
25
+ const given = {}; const raw = {};
26
+ for (const n of names) { raw[n] = (c.given || {})[n]; given[n] = coerceVal(raw[n]); }
27
+ cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given, raw });
26
28
  }
27
29
  }
28
30
  return cases;
29
31
  }
30
32
 
31
- // A declared input type (`amount: number`, `Money`, `Flag`) as number, bool, or string; null when none.
32
- const NUMBER_TYPES = /^(number|int|integer|long|short|float|double|decimal|Money|Percentage|Count|Duration)$/i;
33
+ // A declared input type (`amount: number`, `Money`, `Flag`) as number, bool, string, or money; null
34
+ // when none. Money stays its own type so no target turns it into binary floating point.
35
+ const NUMBER_TYPES = /^(number|int|integer|long|short|float|double|decimal|Percentage|Count|Duration)$/i;
33
36
  const BOOL_TYPES = /^(boolean|bool|Flag)$/i;
34
37
  export function declaredInputType(raw) {
38
+ const t = String(raw).includes(':') ? String(raw).slice(String(raw).indexOf(':') + 1).trim() : '';
39
+ if (moneyTypeMinorUnits(t) != null) return 'money';
35
40
  const m = String(raw).match(/:\s*([A-Za-z][\w<>]*)\s*$/);
36
41
  if (!m) return null;
37
42
  if (NUMBER_TYPES.test(m[1])) return 'number';
@@ -95,3 +100,34 @@ export function litFor(type, v) {
95
100
  return strLit(v);
96
101
  }
97
102
 
103
+
104
+ /** Money inputs of a decision: { name: minorUnits } (Money = 2, Money(JPY) = 0, Money(KWD) = 3). */
105
+ export function moneyInputs(dec) {
106
+ const out = {};
107
+ for (const raw of dec.inputs || []) {
108
+ const s = String(raw);
109
+ if (!s.includes(':')) continue;
110
+ const units = moneyTypeMinorUnits(s.slice(s.indexOf(':') + 1).trim());
111
+ if (units != null) out[s.split(':')[0].trim()] = units;
112
+ }
113
+ return out;
114
+ }
115
+
116
+ /**
117
+ * Everything a generator needs for one decision: input names and types, Money minor units, each
118
+ * rule's translated condition (or the IL-GEN-001 message when it cannot be translated), and
119
+ * `refused`: the first untranslated message, set when this decision must not be run.
120
+ */
121
+ export function planDecision(ast, d, { translate, target }) {
122
+ const names = inputNames(d);
123
+ const types = inferInputTypes(ast, d);
124
+ const money = moneyInputs(d);
125
+ const opts = { inputs: names, money };
126
+ const rules = []; const diagnostics = []; let refused = null;
127
+ for (const r of d.rules || []) {
128
+ const t = translateRule(translate, r, opts, { target, decision: d.name });
129
+ if (t.ok) rules.push({ rule: r, code: t.code });
130
+ else { rules.push({ rule: r, code: null, message: t.message }); diagnostics.push(t.diagnostic); refused = refused ?? t.message; }
131
+ }
132
+ return { decision: d, names, types, money, rules, diagnostics, refused };
133
+ }
@@ -1,8 +1,12 @@
1
- // Shared helpers for the compiled target adapters (Python/C#/Java). The statically typed targets
1
+ // Shared helpers for the compiled target adapters (Python/C#/Java/...). The statically typed targets
2
2
  // (C#, Java) need a declared type for every decision parameter, which ThunderLang source leaves
3
3
  // implicit, so we infer each input's type from the test-case values that will actually be passed.
4
4
  import { spawnSync } from 'node:child_process';
5
- export { inputNames, coerceVal, buildCases, inferInputTypes, strLit, litFor } from './target-types.mjs';
5
+ import { buildCases, planDecision } from './target-types.mjs';
6
+ import { errorResult } from './target-result.mjs';
7
+ import { parseMoney, moneyLiteral } from './money.mjs';
8
+ export { inputNames, coerceVal, buildCases, inferInputTypes, strLit, litFor, planDecision, moneyInputs } from './target-types.mjs';
9
+ export { okResult, errorResult, finishRun, runFailure, classifySpawn, runValues, isCaseResult, ERROR_KINDS, GEN_UNTRANSLATED } from './target-result.mjs';
6
10
 
7
11
  // Pick the last line of stdout that parses as a JSON object , build/tool chatter may precede it.
8
12
  export function parseLastJsonObject(stdout) {
@@ -35,3 +39,52 @@ export function toolOnPath(cmd, args = ['--version']) {
35
39
  return false;
36
40
  }
37
41
  }
42
+
43
+ // ── Honest runs ──────────────────────────────────────────────────────────────
44
+ // Plan a live run: translate every decision for the target, refuse the cases of any decision with an
45
+ // untranslated rule (IL-GEN-001, kind 'not-translated'), and render each Money argument with the
46
+ // target's exact literal ('js-runtime' gives a real bigint for the in-process runner).
47
+ // Returns { plans: Map(name -> plan), cases, refused }.
48
+ export function prepareRun(ast, { translate, target, dialect }) {
49
+ const plans = new Map((ast.decisions || []).map((d) => [d.name, planDecision(ast, d, { translate, target })]));
50
+ const refused = {};
51
+ const cases = [];
52
+ for (const c of buildCases(ast)) {
53
+ const p = plans.get(c.fn);
54
+ if (!p) continue;
55
+ if (p.refused) { refused[c.key] = errorResult('not-translated', p.refused); continue; }
56
+ // A case that gives no value for an input is never run with a made-up one ("", false, 0, $0): a typed
57
+ // target would answer for a value nobody wrote, and the reference engine reads "missing" differently.
58
+ const missing = p.names.filter((n) => c.raw[n] === undefined || c.raw[n] === null);
59
+ if (missing.length) {
60
+ refused[c.key] = errorResult('missing-input', `${c.key} gives no value for ${missing.join(', ')}, so it cannot run in ${target} without making one up. Add ${missing.length === 1 ? 'it' : 'them'} to the case's "given".`);
61
+ continue;
62
+ }
63
+ try {
64
+ const moneyArgs = {};
65
+ for (const [n, units] of Object.entries(p.money)) {
66
+ const raw = c.raw[n];
67
+ moneyArgs[n] = dialect === 'js-runtime' ? parseMoney(raw, { minorUnits: units }) : moneyLiteral(dialect, raw, units);
68
+ }
69
+ cases.push({ ...c, moneyArgs });
70
+ } catch (e) {
71
+ refused[c.key] = errorResult('not-translated', `Thunder could not pass the example value for ${c.key} to ${target} exactly: ${e.message}`);
72
+ }
73
+ }
74
+ return { plans, cases, refused };
75
+ }
76
+
77
+ // The source text of an argument: the exact Money literal for Money inputs, else the typed literal.
78
+ export const argLit = (c, plan, n, lit) => (c.moneyArgs && c.moneyArgs[n] != null ? c.moneyArgs[n] : lit(plan.types[n], c.given[n]));
79
+
80
+ // Plans for display emitters that are called without a prepared run.
81
+ export function plansFor(ast, translate, target) {
82
+ return new Map((ast.decisions || []).map((d) => [d.name, planDecision(ast, d, { translate, target })]));
83
+ }
84
+
85
+ // Run a child process and return { ok: true, stdout } or { ok: false, failure } (a classified run failure).
86
+ export function spawnStep(cmd, args, opts, classify) {
87
+ const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
88
+ if (r.status === 0 && !r.error) return { ok: true, stdout: r.stdout || '' };
89
+ return { ok: false, failure: classify(r) };
90
+ }
@@ -0,0 +1,58 @@
1
+ // thunder trace: the command line for Thunder Trace (src/trace.mjs, docs/trace.md).
2
+ // thunder trace <folder…> [--json] [--out graph.json] the links between repositories
3
+ // thunder trace impact <thing> <folder…> [--json] what changing a route, event, or file can affect
4
+ // thunder trace impact --diff [--base <ref>] <folder…> what the current changes (branch + uncommitted) can affect
5
+ import { writeFileSync } from 'node:fs';
6
+ import { buildTrace, renderTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
7
+ import { readRepoDir, gitChanges } from './trace-fs.mjs';
8
+
9
+ const USAGE = `usage: thunder trace <folder> <folder> … [--json] [--out graph.json]
10
+ thunder trace impact "<POST /api/orders | event name | repo:file[:line]>" <folder> … [--json]
11
+ thunder trace impact --diff [--base <ref>] <folder> … [--json]
12
+ Each folder is one repository. Nothing is run; links are read from code.`;
13
+
14
+ export function traceMain(argv) {
15
+ const a = { _: [], json: false, diff: false, base: null, out: null, maxFiles: 5000 };
16
+ for (let i = 0; i < argv.length; i++) {
17
+ const x = argv[i];
18
+ if (x === '--json') a.json = true;
19
+ else if (x === '--diff') a.diff = true;
20
+ else if (x === '--base') a.base = argv[++i];
21
+ else if (x === '--out') a.out = argv[++i];
22
+ else if (x === '--max-files') a.maxFiles = Number(argv[++i]);
23
+ else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
24
+ else if (x.startsWith('--')) { console.error(`thunder trace: unknown option ${x}\n${USAGE}`); return 2; }
25
+ else a._.push(x);
26
+ }
27
+ const impact = a._[0] === 'impact';
28
+ if (impact) a._.shift();
29
+ const term = impact && !a.diff ? a._.shift() : null;
30
+ if (impact && !a.diff && !term) { console.error(`thunder trace impact: name what changes (a route, an event, or repo:file), or use --diff.\n${USAGE}`); return 2; }
31
+ if (!a._.length) { console.error(`thunder trace: give at least one repository folder.\n${USAGE}`); return 2; }
32
+ let repos;
33
+ try { repos = a._.map((d) => readRepoDir(d, { maxFiles: a.maxFiles })); } catch (e) { console.error(`thunder trace: ${e.message}`); return 2; }
34
+ const trace = buildTrace(repos);
35
+ if (!impact) {
36
+ if (a.out) writeFileSync(a.out, `${JSON.stringify(trace, null, 2)}\n`);
37
+ console.log(a.json ? JSON.stringify(trace, null, 2) : renderTrace(trace) + (a.out ? `\nWrote ${a.out}.` : ''));
38
+ return 0;
39
+ }
40
+ if (term) {
41
+ const r = traceImpactOf(trace, term);
42
+ console.log(a.json ? JSON.stringify(r, null, 2) : renderImpact(r));
43
+ return r.matched.length ? 0 : 1;
44
+ }
45
+ const changes = [], notes = [];
46
+ for (const repo of repos) {
47
+ const g = gitChanges(repo, a.base);
48
+ if (!g.base) notes.push(g.why); else changes.push(...g.changes);
49
+ }
50
+ const r = traceImpact(trace, changes);
51
+ if (a.json) console.log(JSON.stringify({ ...r, notes }, null, 2));
52
+ else {
53
+ console.log(`${changes.length ? `${changes.length} changed file${changes.length === 1 ? '' : 's'} across ${new Set(changes.map((c) => c.repo)).size} of ${repos.length} repositories.` : 'No changes found.'}`);
54
+ for (const n of notes) console.log(`Note: ${n}`);
55
+ console.log(renderImpact(r));
56
+ }
57
+ return 0;
58
+ }