@skillstech/thunderlang 0.4.2 → 0.5.4

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 (46) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/dist/core.cjs +8389 -4510
  3. package/dist/index.cjs +7218 -3842
  4. package/package.json +1 -1
  5. package/src/anchor.d.mts +12 -0
  6. package/src/anchor.mjs +127 -0
  7. package/src/cli.mjs +234 -42
  8. package/src/codegen.mjs +27 -9
  9. package/src/core.d.ts +19 -0
  10. package/src/core.mjs +16 -0
  11. package/src/emit.mjs +1 -1
  12. package/src/expr.mjs +42 -1
  13. package/src/human-contract.d.mts +20 -0
  14. package/src/human-contract.mjs +213 -0
  15. package/src/index.d.ts +23 -0
  16. package/src/index.mjs +11 -0
  17. package/src/lift.mjs +7 -0
  18. package/src/mcp.mjs +139 -54
  19. package/src/obligations.d.mts +9 -0
  20. package/src/obligations.mjs +35 -0
  21. package/src/plain-contract.d.mts +30 -0
  22. package/src/plain-contract.mjs +339 -0
  23. package/src/promote.d.mts +6 -0
  24. package/src/promote.mjs +179 -0
  25. package/src/read-repo-fs.mjs +29 -0
  26. package/src/read-repo.d.mts +21 -0
  27. package/src/read-repo.mjs +139 -0
  28. package/src/read.d.mts +29 -0
  29. package/src/read.mjs +1620 -0
  30. package/src/review-atlas.d.mts +19 -0
  31. package/src/review-atlas.mjs +136 -0
  32. package/src/steps.d.mts +2 -0
  33. package/src/steps.mjs +297 -0
  34. package/src/target-elixir.mjs +79 -0
  35. package/src/target-go.mjs +95 -0
  36. package/src/target-kotlin.mjs +91 -0
  37. package/src/target-rust.mjs +99 -0
  38. package/src/target-scala.mjs +93 -0
  39. package/src/target-types.mjs +97 -0
  40. package/src/target-util.mjs +1 -59
  41. package/src/testing.mjs +12 -9
  42. package/src/thunder-repo.mjs +96 -0
  43. package/src/translate.d.mts +5 -0
  44. package/src/translate.mjs +126 -0
  45. package/src/write.d.mts +24 -0
  46. package/src/write.mjs +263 -0
@@ -0,0 +1,91 @@
1
+ // Kotlin target adapter. Emits a self-contained Kotlin script (.kts) that defines each decision as
2
+ // a typed fun (using the same exprToKotlin translator the codegen uses), calls every test case with
3
+ // typed literal arguments, and prints the results as one JSON line. It runs through the Kotlin
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';
7
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { tmpdir } from 'node:os';
10
+ import { exprToKotlin } from './expr.mjs';
11
+ import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
12
+
13
+ const KOTLIN_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
14
+ // Double params reject bare integer literals, so numeric args carry an explicit decimal.
15
+ const kotlinLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}${Number.isInteger(Number(v)) ? '.0' : ''}` : litFor(type, v));
16
+
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.
19
+ function kotlinRun(dir, source) {
20
+ const f = join(dir, 'main.kts');
21
+ writeFileSync(f, source);
22
+ 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;
26
+ }
27
+
28
+ // The emitted Kotlin source (also usable for display / `gen`-parity).
29
+ export function emitKotlinModule(ast, cases = buildCases(ast)) {
30
+ 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)}`);
41
+ }
42
+ L.push(` return ${d.default == null ? '""' : strLit(d.default)}`, '}', '');
43
+ }
44
+ L.push('fun j(s: String?): String {');
45
+ L.push(' if (s == null) return "null"');
46
+ L.push(' val b = StringBuilder("\\"")');
47
+ L.push(' for (c in s) {');
48
+ L.push(' if (c == \'"\' || c == \'\\\\\') { b.append(\'\\\\\'); b.append(c) }');
49
+ L.push(' else if (c == \'\\n\') { b.append("\\\\n") }');
50
+ L.push(' else { b.append(c) }');
51
+ L.push(' }');
52
+ L.push(' b.append(\'"\')');
53
+ L.push(' return b.toString()');
54
+ L.push('}');
55
+ L.push('');
56
+ 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
+ });
65
+ L.push('sb.append("}")');
66
+ L.push('println(sb.toString())');
67
+ return L.join('\n');
68
+ }
69
+
70
+ export function kotlinAvailable() {
71
+ return cachedSmoke('kotlin', () => {
72
+ const dir = mkdtempSync(join(tmpdir(), 'tl-kt-smoke-'));
73
+ try {
74
+ const src = 'println("{\\"ok\\":\\"1\\"}")';
75
+ const out = kotlinRun(dir, src);
76
+ return !!out && /"ok"/.test(out);
77
+ } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
78
+ });
79
+ }
80
+
81
+ // Run every decision test case through generated, compiled Kotlin. Returns { "Test / case": actual }
82
+ // or null when no usable Kotlin toolchain is present.
83
+ export function runKotlinTarget(ast) {
84
+ if (!kotlinAvailable()) return null;
85
+ const cases = buildCases(ast);
86
+ const dir = mkdtempSync(join(tmpdir(), 'tl-kt-'));
87
+ try {
88
+ const out = kotlinRun(dir, emitKotlinModule(ast, cases));
89
+ return out == null ? null : parseLastJsonObject(out);
90
+ } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
91
+ }
@@ -0,0 +1,99 @@
1
+ // Rust target adapter. Emits a self-contained single-file program that defines each decision as a
2
+ // typed fn (using the same exprToRust translator the codegen uses), calls every test case with
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';
7
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { tmpdir } from 'node:os';
10
+ import { exprToRust } from './expr.mjs';
11
+ import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
12
+
13
+ const RUST_TYPE = { number: 'f64', bool: 'bool', string: '&str' };
14
+ // f64 params reject bare integer literals, so numeric args carry an explicit f64 suffix.
15
+ const rustLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}f64` : litFor(type, v));
16
+
17
+ // Compile `source` with rustc and run the binary. Returns stdout, or null on any failure.
18
+ function rustcRun(dir, source) {
19
+ const src = join(dir, 'main.rs');
20
+ const bin = join(dir, process.platform === 'win32' ? 'main.exe' : 'main_bin');
21
+ writeFileSync(src, source);
22
+ 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;
28
+ }
29
+
30
+ // The emitted Rust source (also usable for display / `gen`-parity).
31
+ export function emitRustModule(ast, cases = buildCases(ast)) {
32
+ const L = [
33
+ '#![allow(non_snake_case, unused_parens, dead_code, unused_variables)]',
34
+ '',
35
+ ];
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)}; }`);
46
+ }
47
+ L.push(` return ${d.default == null ? '""' : strLit(d.default)};`, '}', '');
48
+ }
49
+ L.push('fn j(s: &str) -> String {');
50
+ L.push(' let mut out = String::from("\\"");');
51
+ L.push(' for c in s.chars() {');
52
+ L.push(' match c {');
53
+ L.push(' \'"\' | \'\\\\\' => { out.push(\'\\\\\'); out.push(c); }');
54
+ L.push(' \'\\n\' => out.push_str("\\\\n"),');
55
+ L.push(' _ => out.push(c),');
56
+ L.push(' }');
57
+ L.push(' }');
58
+ L.push(' out.push(\'"\');');
59
+ L.push(' out');
60
+ L.push('}');
61
+ L.push('');
62
+ L.push('fn main() {');
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
+ });
72
+ L.push(' sb.push_str("}");');
73
+ L.push(' println!("{}", sb);');
74
+ L.push('}');
75
+ return L.join('\n');
76
+ }
77
+
78
+ export function rustAvailable() {
79
+ return cachedSmoke('rust', () => {
80
+ const dir = mkdtempSync(join(tmpdir(), 'tl-rust-smoke-'));
81
+ try {
82
+ const src = 'fn main() {\n println!("{}", "{\\"ok\\":\\"1\\"}");\n}';
83
+ const out = rustcRun(dir, src);
84
+ return !!out && /"ok"/.test(out);
85
+ } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
86
+ });
87
+ }
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.
91
+ export function runRustTarget(ast) {
92
+ if (!rustAvailable()) return null;
93
+ const cases = buildCases(ast);
94
+ const dir = mkdtempSync(join(tmpdir(), 'tl-rust-'));
95
+ try {
96
+ const out = rustcRun(dir, emitRustModule(ast, cases));
97
+ return out == null ? null : parseLastJsonObject(out);
98
+ } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
99
+ }
@@ -0,0 +1,93 @@
1
+ // Scala target adapter. Emits a self-contained Scala script that defines each decision as a typed
2
+ // def (using the same exprToScala translator the codegen uses), calls every test case with typed
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';
7
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { tmpdir } from 'node:os';
10
+ import { exprToScala } from './expr.mjs';
11
+ import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
12
+
13
+ const SCALA_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
14
+ // Which runner worked during the smoke, so run reuses it: [cmd, argsFor(file)].
15
+ let SCALA_RUNNER = null;
16
+
17
+ // 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.
19
+ function scalaRun(dir, source) {
20
+ const f = join(dir, 'Main.scala');
21
+ writeFileSync(f, source);
22
+ const env = { ...process.env };
23
+ const runners = SCALA_RUNNER ? [SCALA_RUNNER] : [['scala', (p) => [p]], ['scala-cli', (p) => ['run', p]]];
24
+ 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; }
27
+ }
28
+ return null;
29
+ }
30
+
31
+ // The emitted Scala source (also usable for display / `gen`-parity).
32
+ export function emitScalaModule(ast, cases = buildCases(ast)) {
33
+ 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)}`);
44
+ }
45
+ L.push(` return ${d.default == null ? 'null' : strLit(d.default)}`, '}', '');
46
+ }
47
+ L.push('def j(s: String): String = {');
48
+ L.push(' if (s == null) return "null"');
49
+ L.push(' val b = new StringBuilder("\\"")');
50
+ L.push(' for (c <- s) {');
51
+ L.push(' if (c == \'"\' || c == \'\\\\\') { b.append(\'\\\\\'); b.append(c) }');
52
+ L.push(' else if (c == \'\\n\') b.append("\\\\n")');
53
+ L.push(' else b.append(c)');
54
+ L.push(' }');
55
+ L.push(' b.append(\'"\').toString');
56
+ L.push('}');
57
+ L.push('');
58
+ 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
+ });
67
+ L.push('sb.append("}")');
68
+ L.push('println(sb.toString)');
69
+ return L.join('\n');
70
+ }
71
+
72
+ export function scalaAvailable() {
73
+ return cachedSmoke('scala', () => {
74
+ const dir = mkdtempSync(join(tmpdir(), 'tl-scala-smoke-'));
75
+ try {
76
+ const src = 'println("{\\"ok\\":\\"1\\"}")';
77
+ const out = scalaRun(dir, src);
78
+ return !!out && /"ok"/.test(out);
79
+ } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
80
+ });
81
+ }
82
+
83
+ // Run every decision test case through generated, compiled Scala. Returns { "Test / case": actual }
84
+ // or null when no usable Scala toolchain is present.
85
+ export function runScalaTarget(ast) {
86
+ if (!scalaAvailable()) return null;
87
+ const cases = buildCases(ast);
88
+ const dir = mkdtempSync(join(tmpdir(), 'tl-scala-'));
89
+ try {
90
+ const out = scalaRun(dir, emitScalaModule(ast, cases));
91
+ return out == null ? null : parseLastJsonObject(out);
92
+ } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
93
+ }
@@ -0,0 +1,97 @@
1
+ // Browser-safe helpers shared by the target adapters and the in-browser translator.
2
+ // No Node imports here, so the website can bundle this file.
3
+
4
+ export const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
5
+
6
+ export function coerceVal(v) {
7
+ if (v == null || typeof v !== 'string') return v;
8
+ const s = v.trim();
9
+ if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
10
+ if (s === 'true') return true;
11
+ if (s === 'false') return false;
12
+ return v;
13
+ }
14
+
15
+ // Every case-call we will emit, in a stable order: { key, fn, given: {name: coercedValue} }.
16
+ export function buildCases(ast) {
17
+ const cases = [];
18
+ for (const t of ast.tests || []) {
19
+ const dec = (ast.decisions || []).find((d) => d.name === t.name);
20
+ if (!dec) continue;
21
+ const names = inputNames(dec);
22
+ 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 });
26
+ }
27
+ }
28
+ return cases;
29
+ }
30
+
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
+ const BOOL_TYPES = /^(boolean|bool|Flag)$/i;
34
+ export function declaredInputType(raw) {
35
+ const m = String(raw).match(/:\s*([A-Za-z][\w<>]*)\s*$/);
36
+ if (!m) return null;
37
+ if (NUMBER_TYPES.test(m[1])) return 'number';
38
+ if (BOOL_TYPES.test(m[1])) return 'bool';
39
+ return 'string';
40
+ }
41
+
42
+ // How each input is used in the decision's rules: compared with a number, compared with text, or on its own (a yes/no).
43
+ function usageTypes(dec, names) {
44
+ const out = {};
45
+ const NUM = /^-?\d+(\.\d+)?$/, STR = /^"[^"]*"$|^'[^']*'$/, CMP = /^(<|<=|>|>=|==|!=)$/;
46
+ for (const r of dec.rules || []) {
47
+ const toks = String(r.when || '').match(/"[^"]*"|'[^']*'|[A-Za-z_][\w.]*|-?\d+(?:\.\d+)?|<=|>=|==|!=|[<>()]/g) || [];
48
+ toks.forEach((t, i) => {
49
+ if (!names.includes(t)) return;
50
+ const op = CMP.test(toks[i + 1] || '') ? toks[i + 1] : CMP.test(toks[i - 1] || '') ? toks[i - 1] : null;
51
+ const other = op === toks[i + 1] ? toks[i + 2] : op ? toks[i - 2] : null;
52
+ if (op && NUM.test(other || '')) out[t] = 'number';
53
+ else if (op && /^[<>]=?$/.test(op) && names.includes(other || '')) out[t] = out[t] ?? 'number';
54
+ else if (op && STR.test(other || '') && out[t] !== 'number') out[t] = 'string';
55
+ else if (!op && out[t] == null) out[t] = 'bool';
56
+ });
57
+ }
58
+ return out;
59
+ }
60
+
61
+ // Infer one type per input for a decision. A declared type wins; then the values the decision's examples give
62
+ // (numeric wins, so a relational comparison compiles, then boolean); then how the rules use the input.
63
+ // Falls back to 'string'.
64
+ export function inferInputTypes(ast, dec) {
65
+ const names = inputNames(dec);
66
+ const declared = Object.fromEntries((dec.inputs || []).map((raw) => [String(raw).split(':')[0].trim(), declaredInputType(raw)]));
67
+ const usage = usageTypes(dec, names);
68
+ const types = {};
69
+ for (const n of names) {
70
+ if (declared[n]) { types[n] = declared[n]; continue; }
71
+ let t = null;
72
+ for (const test of (ast.tests || []).filter((x) => x.name === dec.name)) {
73
+ for (const c of test.cases || []) {
74
+ const raw = (c.given || {})[n];
75
+ if (raw == null) continue;
76
+ const cv = coerceVal(raw);
77
+ if (typeof cv === 'number') { t = 'number'; break; }
78
+ if (typeof cv === 'boolean' && t !== 'number') t = 'bool';
79
+ if (typeof cv === 'string' && t == null) t = 'string';
80
+ }
81
+ if (t === 'number') break;
82
+ }
83
+ types[n] = t ?? usage[n] ?? 'string';
84
+ }
85
+ return types;
86
+ }
87
+
88
+ // A source literal for a value at an inferred type. JSON string escaping is valid in Java and C#
89
+ // string literals too, so we reuse JSON.stringify for the string case.
90
+ export const strLit = (s) => JSON.stringify(String(s));
91
+ export function litFor(type, v) {
92
+ if (v == null) return type === 'string' ? '""' : type === 'bool' ? 'false' : '0';
93
+ if (type === 'number') return String(v);
94
+ if (type === 'bool') return v === true || v === 'true' ? 'true' : 'false';
95
+ return strLit(v);
96
+ }
97
+
@@ -2,55 +2,7 @@
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
-
6
- export const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
7
-
8
- export function coerceVal(v) {
9
- if (v == null || typeof v !== 'string') return v;
10
- const s = v.trim();
11
- if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
12
- if (s === 'true') return true;
13
- if (s === 'false') return false;
14
- return v;
15
- }
16
-
17
- // Every case-call we will emit, in a stable order: { key, fn, given: {name: coercedValue} }.
18
- export function buildCases(ast) {
19
- const cases = [];
20
- for (const t of ast.tests || []) {
21
- const dec = (ast.decisions || []).find((d) => d.name === t.name);
22
- if (!dec) continue;
23
- const names = inputNames(dec);
24
- for (const c of t.cases || []) {
25
- const given = {};
26
- for (const n of names) given[n] = coerceVal((c.given || {})[n]);
27
- cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given });
28
- }
29
- }
30
- return cases;
31
- }
32
-
33
- // Infer one type per input for a decision, scanning every case that targets it. Numeric usage
34
- // wins (a relational comparison must compile), then boolean, else string. Falls back to 'string'.
35
- export function inferInputTypes(ast, dec) {
36
- const names = inputNames(dec);
37
- const types = {};
38
- for (const n of names) {
39
- let t = 'string';
40
- for (const test of (ast.tests || []).filter((x) => x.name === dec.name)) {
41
- for (const c of test.cases || []) {
42
- const raw = (c.given || {})[n];
43
- if (raw == null) continue;
44
- const cv = coerceVal(raw);
45
- if (typeof cv === 'number') { t = 'number'; break; }
46
- if (typeof cv === 'boolean' && t !== 'number') t = 'bool';
47
- }
48
- if (t === 'number') break;
49
- }
50
- types[n] = t;
51
- }
52
- return types;
53
- }
5
+ export { inputNames, coerceVal, buildCases, inferInputTypes, strLit, litFor } from './target-types.mjs';
54
6
 
55
7
  // Pick the last line of stdout that parses as a JSON object , build/tool chatter may precede it.
56
8
  export function parseLastJsonObject(stdout) {
@@ -75,16 +27,6 @@ export function cachedSmoke(key, fn) {
75
27
  return ok;
76
28
  }
77
29
 
78
- // A source literal for a value at an inferred type. JSON string escaping is valid in Java and C#
79
- // string literals too, so we reuse JSON.stringify for the string case.
80
- export const strLit = (s) => JSON.stringify(String(s));
81
- export function litFor(type, v) {
82
- if (v == null) return type === 'string' ? '""' : type === 'bool' ? 'false' : '0';
83
- if (type === 'number') return String(v);
84
- if (type === 'bool') return v === true || v === 'true' ? 'true' : 'false';
85
- return strLit(v);
86
- }
87
-
88
30
  export function toolOnPath(cmd, args = ['--version']) {
89
31
  try {
90
32
  const r = spawnSync(cmd, args, { encoding: 'utf8', timeout: 15000 });
package/src/testing.mjs CHANGED
@@ -1,7 +1,5 @@
1
- // First-class tests , make a .intent file SELF-VERIFYING. A `test <target>` block declares
2
- // cases (for a decision) or scenarios (for a lifecycle) right next to the intent they check.
3
- // `runTests` executes them through the deterministic Intent Runtime: no AI, no code, the
4
- // spec proves itself. This is what lets intent be trustworthy , the behavior is asserted.
1
+ // Execute declared cases against the intent runtime. Passing cases are evidence for
2
+ // those inputs, not a proof of every input or of the application's implementation.
5
3
 
6
4
  import { slug } from './parse.mjs';
7
5
  import { evaluateDecision, simulateLifecycle } from './runtime.mjs';
@@ -36,18 +34,23 @@ export function runTests(ast) {
36
34
  for (const t of ast.tests || []) {
37
35
  const dec = decisions.find((d) => slug(d.name) === slug(t.name || ''));
38
36
  const lc = lifecycles.find((l) => slug(l.name) === slug(t.name || ''));
39
- for (const c of t.cases) {
37
+ if (!t.cases?.length) {
38
+ results.push({ target: t.name, case: '(empty test)', kind: 'unknown', pass: false, error: 'test block has no cases' });
39
+ }
40
+ for (const c of t.cases || []) {
40
41
  const label = { target: t.name, case: c.name || `case ${results.length + 1}` };
41
42
  if (dec) {
42
43
  const inputs = coerce(c.given);
43
44
  const run = evaluateDecision(dec, inputs);
44
- const pass = c.expect == null || String(run.result) === String(c.expect);
45
- results.push({ ...label, kind: 'decision', expected: c.expect, actual: run.result, matched: run.matched, pass, ...(run.ok ? {} : { note: 'a condition failed to evaluate' }) });
45
+ const error = !run.ok ? 'a condition failed to evaluate' : c.expect == null ? 'decision case needs an expect assertion' : null;
46
+ const pass = !error && String(run.result) === String(c.expect);
47
+ results.push({ ...label, kind: 'decision', expected: c.expect, actual: run.result, matched: run.matched, pass, ...(error ? { error, note: error } : {}) });
46
48
  } else if (lc) {
47
49
  const sim = simulateLifecycle(lc, c.events || []);
48
50
  const passState = c.expect == null || sim.finalState === c.expect;
49
- const passValid = c.expectValid == null || sim.valid === c.expectValid;
50
- results.push({ ...label, kind: 'lifecycle', expected: c.expect, actual: sim.finalState, valid: sim.valid, expectValid: c.expectValid, pass: passState && passValid });
51
+ const hasAssertion = c.expect != null || c.expectValid != null;
52
+ const passValid = sim.valid === (c.expectValid ?? true);
53
+ results.push({ ...label, kind: 'lifecycle', expected: c.expect, actual: sim.finalState, valid: sim.valid, expectValid: c.expectValid, pass: hasAssertion && passState && passValid, ...(!hasAssertion ? { error: 'scenario needs an expect, valid, or invalid assertion' } : {}) });
51
54
  } else {
52
55
  results.push({ ...label, kind: 'unknown', pass: false, error: `no decision or lifecycle named "${t.name}"` });
53
56
  }
@@ -0,0 +1,96 @@
1
+ // Node-only: Thunder a whole repository (a local folder or a public GitHub repo).
2
+ // Read-only by design: files are parsed by the Thunder code reader, never executed, imported, or built.
3
+ // A GitHub URL is shallow-cloned with `git` (argument list, no shell) into a fresh temp folder.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { mkdtempSync, rmSync, statSync } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { collectReadableFiles } from './read-repo-fs.mjs';
9
+ import { readRepo } from './read-repo.mjs';
10
+ import { plainFromReading, conditionText } from './plain-contract.mjs';
11
+
12
+ export const THUNDER_REPO_SCHEMA = 'thunder-repo-v1';
13
+ const GITHUB = /^(?:https:\/\/github\.com\/)?([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))\/([A-Za-z0-9._-]{1,100}?)(?:\.git)?\/?$/;
14
+ const MONEY = /^(amount|price|total|charge|balance|refund|cost|fee|tax|discount)/i;
15
+ const spaced = (s) => s.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
16
+
17
+ /** Parse "owner/repo" or "https://github.com/owner/repo"; returns null for anything else. */
18
+ export function parseGitHub(target) {
19
+ const m = String(target).trim().match(GITHUB);
20
+ if (!m || m[2] === '.' || m[2] === '..') return null;
21
+ return { owner: m[1], repo: m[2], url: `https://github.com/${m[1]}/${m[2]}.git` };
22
+ }
23
+
24
+ function cloneGitHub(gh, { timeoutMs = 120000 } = {}) {
25
+ const dir = mkdtempSync(join(tmpdir(), 'thunder-repo-'));
26
+ const res = spawnSync('git', ['clone', '--depth', '1', '--quiet', '--no-tags', gh.url, join(dir, 'repo')], {
27
+ timeout: timeoutMs, encoding: 'utf8', env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
28
+ });
29
+ if (res.status !== 0) { rmSync(dir, { recursive: true, force: true }); throw new Error(`Could not clone ${gh.owner}/${gh.repo}: ${(res.stderr || res.error?.message || 'git failed').trim().split('\n')[0]}`); }
30
+ const head = spawnSync('git', ['-C', join(dir, 'repo'), 'rev-parse', 'HEAD'], { encoding: 'utf8' });
31
+ return { root: join(dir, 'repo'), cleanup: () => rmSync(dir, { recursive: true, force: true }), commit: head.stdout.trim() || null };
32
+ }
33
+
34
+ /** Thunder a repository: every readable file through the code reader, every drawable decision as a Thunder card. */
35
+ export function thunderRepo(target, { maxFiles = 3000, keep = false, exampleLimit = 8 } = {}) {
36
+ const gh = parseGitHub(target);
37
+ let isDir = false;
38
+ try { isDir = statSync(target).isDirectory(); } catch { /* not a local path */ }
39
+ if (!isDir && !gh) throw new Error('Give a local folder, owner/repo, or https://github.com/owner/repo.');
40
+ const started = Date.now();
41
+ const src = isDir ? { root: target, cleanup: () => {}, commit: null } : cloneGitHub(gh);
42
+ try {
43
+ const files = collectReadableFiles(src.root, { maxFiles });
44
+ const reading = readRepo(files, { maxFiles });
45
+ const decisions = reading.items.filter((i) => i.kind === 'decision');
46
+ const cards = [], errors = [];
47
+ for (const d of decisions) {
48
+ try { const m = plainFromReading(d); if (m) cards.push({ item: d, model: m }); }
49
+ catch (e) { errors.push({ file: d.file, name: d.name, error: e instanceof Error ? e.message : String(e) }); }
50
+ }
51
+ const functions = reading.items.filter((i) => i.kind === 'function');
52
+ const asSteps = functions.filter((f) => f.steps?.length && (f.stepsReadable ?? 0) >= 0.5);
53
+ const unread = [...decisions.filter((d) => !cards.some((c) => c.item === d)), ...functions.filter((f) => !asSteps.includes(f))];
54
+ const money = cards.filter((c) => c.model.inputs.some((i) => MONEY.test(i.id)));
55
+ const examples = [...money, ...cards.filter((c) => !money.includes(c))].slice(0, exampleLimit).map(({ item, model }) => ({
56
+ file: item.file, name: item.name, line: item.line,
57
+ reads: model.rules.map((r) => `${r.outcome} when ${r.conditions.map((c) => conditionText(model, c)).join(r.join === 'all' ? ' and ' : ' or ')}`).concat(`otherwise ${model.otherwise}`),
58
+ }));
59
+ return {
60
+ schema: THUNDER_REPO_SCHEMA,
61
+ source: gh && !isDir ? `github.com/${gh.owner}/${gh.repo}` : target,
62
+ commit: src.commit,
63
+ seconds: Math.round((Date.now() - started) / 100) / 10,
64
+ languages: reading.languages,
65
+ files: reading.files.length,
66
+ skipped: reading.skipped.length,
67
+ counts: { ...reading.counts, cards: cards.length, decisionsNotDrawn: decisions.length - cards.length, functionsAsSteps: asSteps.length, functionsAsStepsMostly: functions.filter((f) => (f.stepsReadable ?? 0) >= 0.8).length, unreadFunctions: unread.length, readerErrors: errors.length },
68
+ focus: [
69
+ ...money.slice(0, 5).map(({ item }) => ({ kind: 'money', file: item.file, name: item.name, line: item.line, reason: 'Decides about money; read from code only, so a person should confirm it.' })),
70
+ ...unread.slice(0, 5).map((i) => ({ kind: 'unreadable', file: i.file, name: i.name, line: i.line, reason: 'Thunder cannot fully read this yet: read the code.' })),
71
+ ],
72
+ examples, errors,
73
+ readOnly: true,
74
+ note: 'Read from code by the Thunder code reader: no code was executed. Cards show what the code does today; a person decides whether that is what the team wants.',
75
+ ...(keep ? { localPath: src.root } : {}),
76
+ };
77
+ } finally { if (!keep) src.cleanup(); }
78
+ }
79
+
80
+ /** A short Thunder Brief for the terminal. */
81
+ export function renderThunderRepo(r) {
82
+ const langs = Object.entries(r.languages).sort((a, b) => b[1] - a[1]).map(([l, n]) => `${l} ${n}`).join(', ');
83
+ const c = r.counts;
84
+ const out = [
85
+ `Thunder Brief: ${r.source}${r.commit ? ` @ ${r.commit.slice(0, 10)}` : ''}`,
86
+ `${r.files} files read (${langs || 'none'})${r.skipped ? `, ${r.skipped} skipped` : ''}, in ${r.seconds}s. Read-only: nothing was executed.`,
87
+ `${c.decision} decisions found, ${c.cards} drawn as Thunder rule cards. ${c.function} other functions, ${c.functionsAsSteps} read as Thunder steps (${c.functionsAsStepsMostly} at least 80% readable). ${c.unreadFunctions} need a person. ${c.route ?? 0} routes.`,
88
+ ];
89
+ if (r.examples.length) {
90
+ out.push('', 'Rules read in Thunder (read from code; confirm with a person):');
91
+ for (const e of r.examples) { out.push(` ${e.file}:${e.line} ${spaced(e.name)}`); for (const line of e.reads) out.push(` ${line}`); }
92
+ }
93
+ if (r.focus.length) { out.push('', 'Thunder Focus (look here first):'); for (const f of r.focus) out.push(` [${f.kind}] ${f.file}:${f.line} ${spaced(f.name)}: ${f.reason}`); }
94
+ if (r.errors.length) { out.push('', `Reader errors (${r.errors.length}):`); for (const e of r.errors.slice(0, 5)) out.push(` ${e.file} ${e.name}: ${e.error}`); }
95
+ return out.join('\n');
96
+ }
@@ -0,0 +1,5 @@
1
+ import type { IntentAst } from './index.js';
2
+ export type TranslateLanguage = 'typescript' | 'python' | 'go' | 'rust' | 'csharp' | 'java';
3
+ export const TRANSLATE_LANGUAGES: Array<{ key: TranslateLanguage; label: string }>;
4
+ /** Translate every decision in a parsed ThunderLang AST into readable, typed source. Deterministic. */
5
+ export function translateDecisions(ast: IntentAst, lang: TranslateLanguage): string;