@skillstech/thunderlang 1.0.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2568 -462
  4. package/dist/index.cjs +7562 -5084
  5. package/dist/learn.cjs +16994 -8339
  6. package/intent-graph.schema.json +11 -0
  7. package/package.json +6 -2
  8. package/src/cli-home.mjs +242 -0
  9. package/src/cli.mjs +241 -89
  10. package/src/codegen.mjs +145 -55
  11. package/src/conformance.mjs +15 -6
  12. package/src/core/check.mjs +725 -0
  13. package/src/core/cli.mjs +184 -0
  14. package/src/core/diagnostics.mjs +82 -0
  15. package/src/core/engine-core.mjs +572 -0
  16. package/src/core/engine-values.mjs +1054 -0
  17. package/src/core/engine-worker.mjs +15 -0
  18. package/src/core/engine.mjs +63 -0
  19. package/src/core/format.mjs +20 -0
  20. package/src/core/from-python.mjs +645 -0
  21. package/src/core/index.mjs +39 -0
  22. package/src/core/lexer.mjs +115 -0
  23. package/src/core/parser.mjs +742 -0
  24. package/src/core/project.mjs +177 -0
  25. package/src/core/round-trip.mjs +150 -0
  26. package/src/core/runtime-python.mjs +801 -0
  27. package/src/core/runtime-typescript.mjs +119 -0
  28. package/src/core/target-python.mjs +487 -0
  29. package/src/core/target-typescript.mjs +466 -0
  30. package/src/core/typescript-run.mjs +114 -0
  31. package/src/core.d.ts +5 -2
  32. package/src/core.mjs +5 -2
  33. package/src/data-schema.mjs +8 -1
  34. package/src/emit.mjs +1 -1
  35. package/src/evidence.mjs +1 -1
  36. package/src/expr.mjs +81 -4
  37. package/src/form-words.mjs +2 -0
  38. package/src/index.d.ts +8 -1
  39. package/src/index.mjs +5 -1
  40. package/src/intent-schema.mjs +1 -0
  41. package/src/learn-lessons.mjs +245 -1
  42. package/src/learn.d.mts +8 -0
  43. package/src/learn.mjs +40 -4
  44. package/src/mcp.mjs +23 -0
  45. package/src/meaning.mjs +45 -6
  46. package/src/model.d.mts +7 -3
  47. package/src/model.mjs +19 -6
  48. package/src/money.d.mts +18 -0
  49. package/src/money.mjs +124 -0
  50. package/src/plain-contract.mjs +18 -2
  51. package/src/read-level.mjs +146 -0
  52. package/src/read.d.mts +11 -0
  53. package/src/read.mjs +40 -6
  54. package/src/review-comment.d.mts +16 -0
  55. package/src/review-comment.mjs +145 -0
  56. package/src/say-less.mjs +1432 -0
  57. package/src/system.mjs +153 -44
  58. package/src/target-cs.mjs +39 -34
  59. package/src/target-elixir.mjs +40 -30
  60. package/src/target-go.mjs +41 -36
  61. package/src/target-java.mjs +34 -27
  62. package/src/target-kotlin.mjs +43 -35
  63. package/src/target-py.mjs +57 -55
  64. package/src/target-result.d.mts +48 -0
  65. package/src/target-result.mjs +112 -0
  66. package/src/target-rust.mjs +42 -38
  67. package/src/target-scala.mjs +45 -35
  68. package/src/target-ts.mjs +37 -45
  69. package/src/target-types.mjs +41 -5
  70. package/src/target-util.mjs +55 -2
  71. package/src/term.mjs +89 -0
  72. package/src/trace-cli.mjs +58 -0
  73. package/src/trace-fs.mjs +76 -0
  74. package/src/trace.mjs +261 -0
  75. package/src/translate.d.mts +3 -0
  76. package/src/translate.mjs +62 -32
  77. package/src/try-cli.mjs +225 -0
  78. package/src/why-cli.mjs +41 -0
  79. package/src/why.d.mts +38 -0
  80. package/src/why.mjs +613 -0
  81. package/src/write-steps.mjs +22 -5
package/src/cli.mjs CHANGED
@@ -49,6 +49,14 @@ import { verifyDiff } from './verify-diff.mjs';
49
49
  import { verifyRun, executedText, mergeTraces } from './executed.mjs';
50
50
  import { runtimeOverlay, runtimeText, fromTrace, fromStack, fromLogs, fromOtlp, parseStacks, explainError, countWords } from './running.mjs';
51
51
  import { thunderModel } from './model.mjs';
52
+ import { LEVELS, readLevel, renderLevel, findFocus, nearestLevel } from './read-level.mjs';
53
+ import { traceMain } from './trace-cli.mjs';
54
+ import { whyMain } from './why-cli.mjs';
55
+ import { tryMain } from './try-cli.mjs';
56
+ import { homeText, helpFor, knownCommands, unknownCommandText, noProjectText, doctorMain, completionMain } from './cli-home.mjs';
57
+ import { paint, paintHelp, useColor } from './term.mjs';
58
+ import { coreMain } from './core/cli.mjs';
59
+ import { pythonToCore } from './core/from-python.mjs';
52
60
  import { guardSummary } from './guard.mjs';
53
61
  import { draftIntent } from './draft.mjs';
54
62
  import { liftSource, liftAll, liftRepo, languageForFile } from './lift.mjs';
@@ -61,7 +69,7 @@ import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './revi
61
69
  import { buildFocusGraph, intentBrief, makeScope } from './focus.mjs';
62
70
  import { comprehensionLevel, comprehensionReport, LEVELS as COMPREHENSION_LEVELS } from './comprehension.mjs';
63
71
  import { twelveFactorReport } from './twelve-factor.mjs';
64
- import { GENERATORS } from './codegen.mjs';
72
+ import { GENERATORS, generateWithDiagnostics } from './codegen.mjs';
65
73
  import { changeReport } from './changes.mjs';
66
74
  import { execSync, execFileSync, spawnSync } from 'node:child_process';
67
75
  import { diffGraphs, mergeGraphs } from './semantic-diff.mjs';
@@ -82,6 +90,7 @@ import { runRustTarget, rustAvailable } from './target-rust.mjs';
82
90
  import { runKotlinTarget, kotlinAvailable } from './target-kotlin.mjs';
83
91
  import { runScalaTarget, scalaAvailable } from './target-scala.mjs';
84
92
  import { runElixirTarget, elixirAvailable } from './target-elixir.mjs';
93
+ import { errorResult, runFailure } from './target-result.mjs';
85
94
 
86
95
  // The live-target registry: one entry per canonical target that can be compiled + executed.
87
96
  // `available()` is a (cached) toolchain probe; TypeScript/JS runs in-process so it is always live.
@@ -110,12 +119,42 @@ const TARGET_ALIASES = {
110
119
  golang: 'go', rs: 'rust', kt: 'kotlin', sc: 'scala', ex: 'elixir',
111
120
  };
112
121
  const canonicalTarget = (t) => TARGET_ALIASES[String(t).toLowerCase()] || String(t).toLowerCase();
113
- // Execute a live target. Returns { "Test / case": actual } or null if the target can't run
114
- // (e.g. the runtime/SDK is not installed). Unknown targets return null.
122
+ // Execute a live target. Returns { status: 'ok', results: { "Test / case": caseResult } } or a
123
+ // whole-run { status: 'error', kind, message } (e.g. kind 'missing-toolchain' when the SDK is not
124
+ // installed). A failure is never turned into a null answer.
115
125
  function runLiveTarget(ast, target) {
116
126
  const entry = LIVE_BY_KEY.get(canonicalTarget(target));
117
- return entry ? entry.run(ast) : null;
127
+ if (!entry) return runFailure('missing-toolchain', `Thunder has no live runner for "${target}".`);
128
+ return entry.run(ast);
118
129
  }
130
+ // Grade a live run against the intent's test cases. A case the target could not produce (not
131
+ // translated, compile failure, crash, timeout) is an error, never a pass and never a null answer.
132
+ function gradeRun(ast, run) {
133
+ const cs = [];
134
+ for (const t of ast.tests || []) {
135
+ if (!(ast.decisions || []).some((d) => d.name === t.name)) continue;
136
+ for (const c of t.cases || []) {
137
+ const key = `${t.name} / ${c.name || 'case'}`;
138
+ const r = run.status === 'ok'
139
+ ? (run.results[key] || errorResult('runtime-error', `The target reported no result for ${key}.`))
140
+ : errorResult(run.kind, run.message);
141
+ if (r.status === 'error') { cs.push({ key, expected: c.expect, status: 'error', kind: r.kind, message: r.message, pass: false }); continue; }
142
+ const pass = c.expect == null || String(r.value) === String(c.expect);
143
+ cs.push({ key, expected: c.expect, actual: r.value, status: pass ? 'pass' : 'fail', ...(pass ? {} : { kind: 'assertion-failed' }), pass });
144
+ }
145
+ }
146
+ return cs;
147
+ }
148
+ // Per-case results for conformance: the run's own results, or the whole-run failure on every case.
149
+ function caseResultsOf(ast, run) {
150
+ if (run.status === 'ok') return run.results;
151
+ const out = {};
152
+ for (const t of ast.tests || []) for (const c of t.cases || []) out[`${t.name} / ${c.name || 'case'}`] = errorResult(run.kind, run.message);
153
+ return out;
154
+ }
155
+ const caseLine = (c) => (c.status === 'error'
156
+ ? `ERROR ${c.key} , ${c.kind === 'not-translated' ? 'not translated' : c.kind === 'missing-input' ? 'missing input' : c.kind}: ${c.message}`
157
+ : `FAIL ${c.key} , expected ${c.expected}, got ${c.actual === null ? 'null' : c.actual}`);
119
158
  import { importIntent, importReport, detectFormat, IMPORT_FORMATS } from './importers.mjs';
120
159
  import { runTests } from './testing.mjs';
121
160
  import { resolveObligations } from './obligations.mjs';
@@ -211,14 +250,16 @@ function collectIntents(root, acc = []) {
211
250
  * Read the files that changed between two commits (or a commit and the working tree, when head is null) and review
212
251
  * them in Thunder. Only git is run (show, diff, ls-files): nothing is fetched and nothing is executed.
213
252
  */
214
- function reviewGit(base, head) {
253
+ function reviewGit(base, head, paths = []) {
215
254
  const git = (...a) => execFileSync('git', a, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
216
255
  try { git('rev-parse', '--is-inside-work-tree'); } catch { throw new Error('not inside a git repository.'); }
217
256
  for (const ref of [base, head].filter(Boolean)) {
218
257
  try { git('rev-parse', '--verify', '--quiet', `${ref}^{commit}`); } catch { throw new Error(`${ref} is not a commit in this repository (fetch it first, for example with fetch-depth: 0).`); }
219
258
  }
220
259
  const root = git('rev-parse', '--show-toplevel').trim();
221
- const parts = git('diff', '--name-status', '-z', '-M', base, ...(head ? [head] : []), '--').split('\0');
260
+ // --paths: git pathspecs with glob magic, so `src/**` and `*.py` mean what they look like.
261
+ const spec = paths.map((p) => `:(glob)${p}`);
262
+ const parts = git('diff', '--name-status', '-z', '-M', base, ...(head ? [head] : []), '--', ...spec).split('\0');
222
263
  const changes = [];
223
264
  for (let i = 0; i < parts.length && parts[i];) {
224
265
  const status = parts[i++];
@@ -227,7 +268,7 @@ function reviewGit(base, head) {
227
268
  else if (status === 'D') changes.push({ old: parts[i++], new: null });
228
269
  else { const p = parts[i++]; changes.push({ old: p, new: p }); }
229
270
  }
230
- if (!head) for (const p of git('ls-files', '--others', '--exclude-standard', '-z').split('\0').filter(Boolean)) changes.push({ old: null, new: p });
271
+ if (!head) for (const p of git('ls-files', '--others', '--exclude-standard', '-z', '--', ...spec).split('\0').filter(Boolean)) changes.push({ old: null, new: p });
231
272
  const text = (s) => (s == null || s.includes('\0') ? null : s); // binary files are not read
232
273
  const at = (ref, p) => { try { return text(git('show', `${ref}:${p}`)); } catch { return null; } };
233
274
  const disk = (p) => { try { return text(readFileSync(join(root, p), 'utf8')); } catch { return null; } };
@@ -296,6 +337,8 @@ function parseArgs(argv) {
296
337
  else if (a === '--role') args.role = argv[++i];
297
338
  else if (a === '--note') args.note = argv[++i];
298
339
  else if (a === '--search') args.search = argv[++i];
340
+ else if (a === '--level') args.level = argv[++i] ?? '';
341
+ else if (a === '--focus') args.focus = argv[++i];
299
342
  else if (a === '--kind') args.kind = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
300
343
  else if (a === '--in') args.inLang = argv[++i];
301
344
  else if (a === '--answer') args.answer = argv[++i];
@@ -307,6 +350,9 @@ function parseArgs(argv) {
307
350
  else if (a === '--expand') args.expand = argv[++i];
308
351
  else if (a === '--now') args.now = argv[++i];
309
352
  else if (a === '--format') args.format = argv[++i];
353
+ else if (a === '--base') args.base = argv[++i];
354
+ else if (a === '--head') args.head = argv[++i];
355
+ else if (a === '--paths') args.paths = (argv[++i] || '').split(/[,\n]/).map((p) => p.trim()).filter(Boolean);
310
356
  else if (a === '--inputs') args.inputs = argv[++i];
311
357
  else if (a === '--events') args.events = (argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
312
358
  else if (a === '--decision') args.decision = argv[++i];
@@ -319,6 +365,9 @@ function parseArgs(argv) {
319
365
  else if (a === '--when') args.when = argv[++i];
320
366
  else if (a === '--to') args.to = argv[++i];
321
367
  else if (a === '--force') args.force = true;
368
+ else if (a === '--mission') args.mission = true;
369
+ else if (a === '--core') args.core = true;
370
+ else if (a === '--as-core') args.asCore = true;
322
371
  else if (a === '--write' || a === '-w') args.write = true;
323
372
  else if (a === '--check') args.check = true;
324
373
  else if (a === '--schema') args.schema = true;
@@ -412,15 +461,61 @@ function printDiagnostics(diags) {
412
461
  return errors;
413
462
  }
414
463
 
415
- const HELP = `thunder , the ThunderLang compiler + engine (deterministic, no AI required)
464
+ const HELP = `⚡ Thunder™: every command. Most people only need the first four groups.
416
465
 
417
- The flow: author intent, inspect it, run and prove it, then keep real code aligned with it.
466
+ usage: thunder <command> [file] [options] Help for one command: thunder help <command>
467
+
468
+ Start
469
+ doctor [--json] is this computer ready? Thunder, Node.js, Python, PATH, and optional toolchains (offline)
470
+ completion <zsh|bash|fish> a script that completes thunder commands when you press Tab
471
+
472
+ Write and run programs (Thunder Core, docs/core.md)
473
+ new <dir> create a Thunder Core project: thunder.toml, src/main.thunder, tests/
474
+ run | build | test | check | format in a project (a folder with thunder.toml), or on a .thunder file in one;
475
+ add --core for a single file with no project. run/test need Python 3.10+, or add
476
+ --engine thunder to run them on the Thunder engine (no Python; programs that Use a
477
+ Python module are refused there). --target typescript compiles to TypeScript instead
478
+ (generated/typescript/; runs on Node 22.6+, or with the typescript package)
479
+
480
+ Read and understand code
481
+ read <file|dir> [--search q] [--kind decision,function,error,test] [--in <lang>] [--from <lang>] [--json]
482
+ read <file|dir> --level big-picture|flow|details|text|original [--focus "<action or rule>"] [--json]
483
+ read at one depth, from the same model OpenThunder shows: the big picture, one action's flow,
484
+ its exact details, its Thunder Text, or the original lines
485
+ read <file.py> --as-core the same code as Thunder Core you can edit and run (Python for now); lines it cannot say exactly are marked
486
+ for a folder also: [--answer <Outcome>] [--input <name>] [--lang go,rust] [--path <prefix>] [--limit n]
487
+ --promote <decision> [--out <file>] turn a recovered decision into a contract with starter examples
488
+ read code you don't know: its decision rules as ThunderLang + plain English,
489
+ optionally rewritten in a language you know (--in typescript|python|go|rust|csharp|java)
490
+ try <file> [--focus "<rule>"] [--with "name=value, …"] [--json] try a rule from your code with your own values: the answer and why (rules only; nothing changes)
491
+ why <run.json> [--step n] [--json] what an AI agent did and why it stopped, in plain words, from its OpenTelemetry record
492
+ same <old> <new> [--json] does the new code mean the same as the old? (files or folders, any languages; rules are run on every edge case)
493
+ review <base-ref> [head-ref] [--format markdown|json] [--paths <glob,...>] [--out <file>]
494
+ review in Thunder: what changed in meaning between two git commits (head: the working tree
495
+ when omitted), as Markdown for a pull request comment; read from git, no network
496
+ trace <folder…> [--json] [--out f] Thunder Trace: routes, requests, and events linked across repositories, cited repo@sha:file:line
497
+ trace impact <thing | --diff [--base ref]> <folder…> what a change can affect in other repositories (one hop, ranked by risk)
498
+ repo <owner/repo | github url | folder> [--json] [--max-files n] Thunder a whole repository (read-only; nothing is executed)
499
+ thunderize <folder | owner/repo> [--out <dir>] [--json] the whole app in Thunder Text: one .thunder-text per file + APP.thunder-text
418
500
 
419
- usage: thunder <command> <file> [options]
501
+ Change code
502
+ write <file> --edit '<json>' [--edit …] [--also <file>] [--apply] [--test "<cmd>"] [--candidate <file>] [--json]
503
+ Writing in Thunder: change a step, question, Stop, input, or function in Thunder; the code is
504
+ written as a minimal patch (TS/JS, Python, Go) and proven (the edited steps mean exactly
505
+ the edit; everything else means the same). Dry run by default; --apply saves; --test runs a
506
+ command on the changed code. Other cases print an instruction for an AI coding agent;
507
+ --candidate checks code it wrote (labeled AI-written).
508
+ write <file> --decision <name> --rule <n|otherwise> [--when "<condition>"] [--answer <Outcome>] [--write] [--json]
509
+ Thunder write: change a number, comparison, text value, or answer in a recovered rule;
510
+ previews the exact code change and the cases whose answer changes; --write saves it
511
+
512
+ ────────────────────────────────────────────────────────────────────────
513
+ Advanced: rules and missions (ThunderLang™ intent files), proofs, and tools for editors and CI.
514
+ The flow: author intent, inspect it, run and prove it, then keep real code aligned with it.
420
515
  thunder mission <Name> <command> run any command on a mission by name
421
516
 
422
517
  Author
423
- new [Name] scaffold a runnable starter mission (Name.thunder) [alias: init]
518
+ init [Name] scaffold a runnable starter mission (Name.thunder) [alias: new --mission Name]
424
519
  mission <Name> [cmd] resolve a mission by name and run a command on it (list | <Name> | <Name> <cmd>)
425
520
  draft --brief <json|-> scaffold a rigorous intent draft + gap checklist from a brief
426
521
  edit <file> [--edits <json|->] [--set-goal ..] [--add-guarantee ..] [--write] structural edits, comments kept
@@ -487,27 +582,7 @@ Graph & IR
487
582
  human <file> [--json | --format source] experimental compact authoring and a decision reading view
488
583
  --version print the Thunder compiler version
489
584
  anchor <file> [--json] show every Thunder step with its exact place in the file, and line coverage
490
- write <file> --edit '<json>' [--edit …] [--also <file>] [--apply] [--test "<cmd>"] [--candidate <file>] [--json]
491
- Writing in Thunder: change a step, question, Stop, input, or function in Thunder; the code is
492
- written as a minimal patch (TS/JS, Python, Go) and proven (the edited steps mean exactly
493
- the edit; everything else means the same). Dry run by default; --apply saves; --test runs a
494
- command on the changed code. Other cases print an instruction for an AI coding agent;
495
- --candidate checks code it wrote (labeled AI-written).
496
- write <file> --decision <name> --rule <n|otherwise> [--when "<condition>"] [--answer <Outcome>] [--write] [--json]
497
- Thunder write: change a number, comparison, text value, or answer in a recovered rule;
498
- previews the exact code change and the cases whose answer changes; --write saves it
499
- repo <owner/repo | github url | folder> [--json] [--max-files n] Thunder a whole repository (read-only; nothing is executed)
500
- thunderize <folder | owner/repo> [--out <dir>] [--json] the whole app in Thunder Text: one .thunder-text per file + APP.thunder-text
501
- review <base-ref> [head-ref] [--json] [--out <file>]
502
- review in Thunder: what changed in meaning between two git commits (head: the working tree
503
- when omitted), as Markdown for a pull request comment; read from git, no network
504
- same <old> <new> [--json] does the new code mean the same as the old? (files or folders, any languages; rules are run on every edge case)
505
585
  text <file> [--json | --format source] experimental Thunder Text rule (.thunder-plain): run its examples [alias: plain]
506
- read <file|dir> [--search q] [--kind decision,function,error,test] [--in <lang>] [--from <lang>] [--json]
507
- for a folder also: [--answer <Outcome>] [--input <name>] [--lang go,rust] [--path <prefix>] [--limit n]
508
- --promote <decision> [--out <file>] turn a recovered decision into a contract with starter examples
509
- read code you don't know: its decision rules as ThunderLang + plain English,
510
- optionally rewritten in a language you know (--in typescript|python|go|rust|csharp|java)
511
586
  graph <file> [--safe] the canonical Intent Graph (intent-graph-v1); --safe = display-safe on stdout
512
587
  migrate <graph.json> [--to <version>] upgrade a persisted graph
513
588
  validate <graph.json> [--json] check a graph is canonical (anti-fork)
@@ -533,19 +608,75 @@ function main() {
533
608
  const args = parseArgs(restArgv);
534
609
  const file = args._[0];
535
610
  if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
536
- console.log(`thunder ${COMPILER_VERSION} (the Thunder compiler, also called ThunderLang)`);
611
+ console.log(`thunder ${COMPILER_VERSION} (the Thunder™ compiler, also called ThunderLang™)`);
537
612
  return;
538
613
  }
614
+ const known = [...new Set([...knownCommands(HELP), ...Object.keys(VIEWS)])].sort();
539
615
  if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
540
- console.log(HELP);
541
- // exitCode, not exit(): the help is longer than a pipe's buffer, and exit() would cut it off when piped.
616
+ // `thunder help <command>`: just that command's lines from the full list.
617
+ const topic = cmd === 'help' ? restArgv.find((x) => !x.startsWith('-')) : null;
618
+ if (topic) {
619
+ const h = helpFor(topic, HELP);
620
+ if (h) { console.log(`${paintHelp(h)}\n\n${paint('All commands: thunder help --all')}`); process.exitCode = 0; }
621
+ else { console.error(paint(unknownCommandText(topic, known), useColor(process.stderr))); process.exitCode = 2; }
622
+ return;
623
+ }
624
+ // The short home screen first; every command with --all. Exit codes are unchanged (2 with no command at all).
625
+ // exitCode, not exit(): the full help is longer than a pipe's buffer, and exit() would cut it off when piped.
626
+ console.log(restArgv.includes('--all') ? paintHelp(HELP) : paint(homeText(COMPILER_VERSION, known.length)));
542
627
  process.exitCode = cmd ? 0 : 2;
543
628
  return;
544
629
  }
630
+ // thunder doctor: is this computer ready? Offline; changes nothing (src/cli-home.mjs).
631
+ if (cmd === 'completion') { process.exitCode = completionMain(restArgv, known); return; }
632
+ if (cmd === 'doctor') { process.exitCode = doctorMain(restArgv, { version: COMPILER_VERSION, cliPath: process.argv[1] }); return; }
633
+ // A command Thunder doesn't have (and not a file): say so, and suggest the closest ones, instead of failing later.
634
+ if (!known.includes(cmd) && !cmd.startsWith('-') && !existsSync(cmd)) { console.error(paint(unknownCommandText(cmd, known), useColor(process.stderr))); process.exitCode = 2; return; }
635
+ // Thunder Trace: links between repositories and what a change can affect (src/trace-cli.mjs).
636
+ if (cmd === 'trace') { process.exitCode = traceMain(restArgv); return; }
637
+ // Thunder Why: an AI agent's run explained in plain words, from its OpenTelemetry record (src/why-cli.mjs).
638
+ if (cmd === 'why') { process.exitCode = whyMain(restArgv); return; }
639
+ // Thunder Try: try a rule from your code with your own values, and see the answer and why (src/try-cli.mjs).
640
+ if (cmd === 'try') { tryMain(restArgv).then((code) => { process.exitCode = code; }); return; }
641
+ // Thunder Core (programs you write and run): thunder new <dir>, and run/build/test/check/format inside a
642
+ // project with thunder.toml (or with --core). Mission files fall through unchanged. See src/core/cli.mjs.
643
+ const coreCode = coreMain(cmd, restArgv);
644
+ if (coreCode !== null) { process.exitCode = coreCode; return; }
545
645
  if (cmd === 'read') {
546
646
  try {
547
647
  if (!file) throw new Error('Use thunder read <file> [--search q] [--kind decision,function,error,test] [--in <lang>] [--json].');
648
+ if (args.level != null) {
649
+ // The five reading levels, from the same model OpenThunder shows (src/read-level.mjs).
650
+ const ids = LEVELS.map((l) => l.id);
651
+ if (!ids.includes(args.level)) {
652
+ const near = nearestLevel(args.level);
653
+ throw new Error(`there is no level "${args.level}". The levels are: ${ids.join(', ')}.${near ? ` Did you mean --level ${near}?` : ''}`);
654
+ }
655
+ const isDir = statSync(file).isDirectory();
656
+ const files = isDir ? collectReadableFiles(file, { maxFiles: 5000 }).filter((f) => f.source) : [{ path: basename(file), source: readFileSync(file, 'utf8') }];
657
+ const model = thunderModel(files, { name: basename(resolve(file)) });
658
+ const focus = findFocus(model, args.focus);
659
+ if (focus.error) throw new Error(focus.error);
660
+ const r = readLevel(model, args.level, focus.id);
661
+ if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
662
+ console.log(paint(renderLevel(r, { sources: Object.fromEntries(files.map((f) => [f.path, f.source])), file })));
663
+ return;
664
+ }
548
665
  if (statSync(file).isDirectory()) { readFolder(file, args); return; }
666
+ if (args.asCore) {
667
+ // Reading and writing are one language: the reader's meaning tree printed as Thunder Core (docs/core.md).
668
+ if (!/\.py$/i.test(file) && (args.from || 'python') !== 'python') throw new Error('--as-core reads Python for now (other languages next).');
669
+ const r = pythonToCore(readFileSync(file, 'utf8'));
670
+ if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
671
+ console.log(r.core.trimEnd());
672
+ const all = [...r.module.notTranslated, ...r.functions.flatMap((f) => f.notTranslated)];
673
+ const exact = r.functions.filter((f) => f.exact);
674
+ console.error(`\nthunder read --as-core: ${exact.length} of ${r.functions.length} function${r.functions.length === 1 ? '' : 's'} printed exactly as Thunder Core${all.length ? `; ${all.length} line${all.length === 1 ? '' : 's'} not translated (each stops with a clear error if it runs)` : ''}.`);
675
+ for (const f of r.functions.filter((x) => !x.exact)) console.error(` ${f.name}: not safely editable: ${f.notTranslated.map((n) => `line ${n.line}: ${n.why}`).join('; ')}`);
676
+ const assumes = r.functions.flatMap((f) => f.assumptions.map((a) => `${f.name}, line ${a.line}: ${a.says}`));
677
+ for (const a of assumes) console.error(` assumes: ${a}`);
678
+ return;
679
+ }
549
680
  if (args.promote) {
550
681
  const items = statSync(file).isDirectory()
551
682
  ? searchRepo(readRepo(collectReadableFiles(file)), { path: args.pathPrefix || '' })
@@ -708,10 +839,12 @@ function main() {
708
839
  }
709
840
  if (cmd === 'review') {
710
841
  try {
711
- const [base, head] = args._;
712
- if (!base) throw new Error('Use thunder review <base-ref> [head-ref] [--json] [--out <file>]. Without head-ref, the working tree is the new side.');
713
- const r = reviewGit(base, head ?? null);
714
- const text = args.json ? JSON.stringify(r, null, 2) : renderReview(r, { footer: `<sub>\`thunder review ${base}${head ? ` ${head}` : ''}\` · Thunder compiler ${COMPILER_VERSION}</sub>` }).trimEnd();
842
+ const base = args.base ?? args._[0], head = args.head ?? (args.base ? null : args._[1]);
843
+ if (!base) throw new Error('Use thunder review <base-ref> [head-ref] (or --base <ref> --head <ref>) [--format markdown|json] [--paths <glob,...>] [--out <file>]. Without a head, the working tree is the new side.');
844
+ if (args.format && !['markdown', 'json'].includes(args.format)) throw new Error(`--format ${args.format} is not one of markdown, json.`);
845
+ const json = args.json || args.format === 'json';
846
+ const r = reviewGit(base, head ?? null, args.paths ?? []);
847
+ const text = json ? JSON.stringify(r, null, 2) : renderReview(r, { footer: `<sub>\`thunder review ${base}${head ? ` ${head}` : ''}\` · Thunder compiler ${COMPILER_VERSION}</sub>` }).trimEnd();
715
848
  if (args.outExplicit) { mkdirSync(dirname(resolve(args.out)), { recursive: true }); writeFileSync(args.out, `${text}\n`); console.log(`thunder review: ${r.says} Wrote ${args.out}.`); }
716
849
  else console.log(text);
717
850
  } catch (e) { console.error(`thunder review: ${e.message}`); process.exitCode = 2; }
@@ -1052,7 +1185,14 @@ function main() {
1052
1185
  const generate = GENERATORS[target];
1053
1186
  if (!generate) { console.error(`thunder gen: unknown target "${target}" (have: ${Object.keys(GENERATORS).join(', ')})`); process.exit(2); return; }
1054
1187
  const ast = parseIntent(readFileSync(file, 'utf8'));
1055
- const code = generate(ast);
1188
+ // IL-GEN-001: a rule condition the target cannot express fails generation for that rule. The code
1189
+ // is still emitted (that rule throws at runtime with the same message), and the command exits 1.
1190
+ const { code, diagnostics } = generateWithDiagnostics(ast, target);
1191
+ const reportGen = () => {
1192
+ for (const d of diagnostics) console.error(`thunder gen: error ${d.code} (decision ${d.decision}, rule ${d.rule}): ${d.message}`);
1193
+ if (diagnostics.length) console.error(`thunder gen: ${diagnostics.length} rule condition(s) not translated; those rules throw instead of deciding. Run "thunder explain ${diagnostics[0].code}".`);
1194
+ };
1195
+ if (args.json) { console.log(JSON.stringify({ schema: 'intent-codegen-v1', target, code, diagnostics }, null, 2)); process.exit(diagnostics.length ? 1 : 0); return; }
1056
1196
  if (args.outExplicit) {
1057
1197
  const ext = target.startsWith('ts') || target === 'typescript' ? 'ts' : target === 'python' ? 'py' : target === 'csharp' ? 'cs' : target;
1058
1198
  // Java requires a public class to live in a file of exactly its name (RefundDecision.java).
@@ -1060,9 +1200,13 @@ function main() {
1060
1200
  const fileName = ext === 'java' ? `${(subject[0].toUpperCase() + subject.slice(1)).replace(/[^A-Za-z0-9]/g, '')}.java` : `${slug(subject)}.${ext}`;
1061
1201
  const p = writeText(args.out, fileName, code.endsWith('\n') ? code : code + '\n');
1062
1202
  console.log(`wrote ${p.replace(process.cwd() + '/', '')}`);
1203
+ reportGen();
1204
+ if (diagnostics.length) process.exit(1);
1063
1205
  return;
1064
1206
  }
1065
1207
  console.log(code);
1208
+ reportGen();
1209
+ if (diagnostics.length) { process.exit(1); return; }
1066
1210
  return;
1067
1211
  }
1068
1212
 
@@ -1119,7 +1263,10 @@ function main() {
1119
1263
  console.error(`thunder init: ${target} already exists (use --force to overwrite).`);
1120
1264
  process.exit(1); return;
1121
1265
  }
1122
- const starter = `mission ${name}
1266
+ const starter = `# A mission: what one part of your product must do, the rules it follows, and examples that prove them.
1267
+ # Run the examples: thunder test ${basename(target)}
1268
+ # Try the rule: thunder try ${basename(target)}
1269
+ mission ${name}
1123
1270
  use product
1124
1271
 
1125
1272
  goal
@@ -1132,7 +1279,7 @@ guarantee an example property that must always hold
1132
1279
  never
1133
1280
  do something this mission must never do
1134
1281
 
1135
- # A runnable decision. Try: thunder run ${name}.intent --inputs '{"age":20}'
1282
+ # A rule that decides: people 18 or older are allowed. Try it: thunder try ${basename(target)}
1136
1283
  decision Example
1137
1284
  inputs
1138
1285
  age
@@ -1142,7 +1289,7 @@ decision Example
1142
1289
  default
1143
1290
  return Blocked
1144
1291
 
1145
- # Tests live in the file. Try: thunder test ${name}.intent
1292
+ # Examples that prove the rule. Run them: thunder test ${basename(target)}
1146
1293
  test Example
1147
1294
  case adult
1148
1295
  given age 20
@@ -1153,13 +1300,22 @@ test Example
1153
1300
  `;
1154
1301
  if (target.includes('/')) mkdirSync(dirname(target), { recursive: true });
1155
1302
  writeFileSync(target, starter);
1156
- console.log(`thunder ${cmd}: wrote ${target}`);
1157
- console.log(` next: thunder check ${target} | thunder run ${target} --inputs '{"age":20}' | thunder test ${target}`);
1303
+ console.log(paint([
1304
+ `Created ${target}: a starter mission, the ThunderLang™ format for a product's rules and the examples that prove them.`,
1305
+ '',
1306
+ 'Try it:',
1307
+ ` thunder test ${target} run the examples written in the file`,
1308
+ ` thunder try ${target} try the rule with your own values`,
1309
+ ` thunder check ${target} look for mistakes, explained in plain words`,
1310
+ '',
1311
+ 'Just starting out? A program in plain words is easier: thunder new hello',
1312
+ ].join('\n')));
1158
1313
  return;
1159
1314
  }
1160
1315
 
1161
1316
  if (!file && cmd !== 'draft' && cmd !== 'mission' && !(cmd === 'test' && args.changed)) {
1162
- console.error(`thunder ${cmd}: missing a file argument. Run "intent help" for usage.`);
1317
+ if (['run', 'test', 'build', 'check'].includes(cmd)) console.error(paint(noProjectText(cmd, process.cwd()), useColor(process.stderr)));
1318
+ else console.error(`thunder ${cmd}: missing a file argument. See: thunder help ${cmd}`);
1163
1319
  process.exit(2);
1164
1320
  }
1165
1321
 
@@ -1665,34 +1821,26 @@ test Example
1665
1821
  // All-targets mode: run the tests against EVERY target whose toolchain is available, in one
1666
1822
  // pass, and report each target's pass count side by side. `thunder test <file> --all-targets`.
1667
1823
  if (args.allTargets) {
1668
- const gradeCases = (actual) => {
1669
- const cs = [];
1670
- for (const t of ast.tests || []) {
1671
- if (!(ast.decisions || []).some((d) => d.name === t.name)) continue;
1672
- for (const c of t.cases || []) {
1673
- const key = `${t.name} / ${c.name || 'case'}`;
1674
- const act = actual[key];
1675
- cs.push({ key, expected: c.expect, actual: act, pass: c.expect == null || String(act) === String(c.expect) });
1676
- }
1677
- }
1678
- return cs;
1679
- };
1680
1824
  const report = LIVE_TARGETS.map((t) => {
1681
- const actual = t.available() ? t.run(ast) : null;
1682
- if (actual === null) return { target: t.key, status: 'skipped', reason: `${t.key} toolchain not available` };
1683
- const cases = gradeCases(actual);
1825
+ const run = t.available() ? t.run(ast) : runFailure('missing-toolchain', `${t.key} toolchain not available`);
1826
+ if (run.status === 'error' && run.kind === 'missing-toolchain') return { target: t.key, status: 'skipped', reason: run.message, kind: run.kind };
1827
+ // A compile failure, crash, or timeout is an error for the whole target, not a skip and not a pass.
1828
+ if (run.status === 'error') return { target: t.key, status: 'error', kind: run.kind, message: run.message, total: 0, passed: 0, cases: gradeRun(ast, run) };
1829
+ const cases = gradeRun(ast, run);
1684
1830
  const passed = cases.filter((c) => c.pass).length;
1685
- return { target: t.key, status: passed === cases.length ? 'pass' : 'fail', total: cases.length, passed, cases };
1831
+ const errors = cases.filter((c) => c.status === 'error').length;
1832
+ return { target: t.key, status: passed === cases.length ? 'pass' : 'fail', total: cases.length, passed, errors, cases };
1686
1833
  });
1687
- const bad = report.some((r) => r.status === 'fail');
1834
+ const bad = report.some((r) => r.status === 'fail' || r.status === 'error');
1688
1835
  if (args.json) { console.log(JSON.stringify({ schema: 'thunder-all-targets-v1', mission: ast.mission, file: basename(file), targets: report }, null, 2)); process.exit(bad ? 1 : 0); return; }
1689
- const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1836
+ const cap = (s) => ({ typescript: 'TypeScript', csharp: 'C#', javascript: 'JavaScript' })[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
1690
1837
  const ran = report.filter((r) => r.status !== 'skipped');
1691
1838
  console.log(`thunder test ${basename(file)} --all-targets: ${ran.length}/${report.length} target(s) executed`);
1692
1839
  for (const r of report) {
1693
1840
  if (r.status === 'skipped') { console.log(` SKIP ${cap(r.target).padEnd(12)} (toolchain not available)`); continue; }
1694
- console.log(` ${r.status === 'pass' ? 'PASS' : 'FAIL'} ${cap(r.target).padEnd(12)} ${r.passed}/${r.total} passed (executed generated code)`);
1695
- for (const c of r.cases) if (!c.pass) console.log(` FAIL ${c.key} , expected ${c.expected}, got ${c.actual}`);
1841
+ if (r.status === 'error') { console.log(` ERROR ${cap(r.target).padEnd(12)} ${r.kind}: ${r.message}`); continue; }
1842
+ console.log(` ${r.status === 'pass' ? 'PASS' : 'FAIL'} ${cap(r.target).padEnd(12)} ${r.passed}/${r.total} passed (executed generated code)${r.errors ? `, ${r.errors} could not run` : ''}`);
1843
+ for (const c of r.cases) if (!c.pass) console.log(` ${caseLine(c)}`);
1696
1844
  }
1697
1845
  process.exit(bad ? 1 : 0);
1698
1846
  return;
@@ -1703,29 +1851,28 @@ test Example
1703
1851
  // `thunder test <file> --target typescript`.
1704
1852
  if (args.target && RUNNABLE_TARGETS.has(String(args.target).toLowerCase())) {
1705
1853
  const targetKey = canonicalTarget(args.target);
1706
- const actual = runLiveTarget(ast, targetKey);
1707
- // Live target could not run (e.g. python3 not installed) , skip cleanly, don't fail.
1708
- if (actual === null) {
1709
- if (args.json) { console.log(JSON.stringify({ schema: 'thunder-target-v1', target: targetKey, skipped: true, reason: `${targetKey} runtime unavailable` }, null, 2)); return; }
1854
+ const run = runLiveTarget(ast, targetKey);
1855
+ // Live target could not run because its toolchain is missing (e.g. python3 not installed) , skip cleanly, don't fail.
1856
+ if (run.status === 'error' && run.kind === 'missing-toolchain') {
1857
+ if (args.json) { console.log(JSON.stringify({ schema: 'thunder-target-v1', target: targetKey, skipped: true, reason: `${targetKey} runtime unavailable`, error: { kind: run.kind, message: run.message } }, null, 2)); return; }
1710
1858
  console.log(`thunder test ${basename(file)} --target ${targetKey}: skipped (the ${targetKey} runtime is not available on this machine).`);
1711
1859
  return;
1712
1860
  }
1713
- const cases = [];
1714
- for (const t of ast.tests || []) {
1715
- const dec = (ast.decisions || []).find((d) => d.name === t.name);
1716
- if (!dec) continue;
1717
- for (const c of t.cases || []) {
1718
- const key = `${t.name} / ${c.name || 'case'}`;
1719
- const act = actual[key];
1720
- cases.push({ key, expected: c.expect, actual: act, pass: c.expect == null || String(act) === String(c.expect) });
1721
- }
1861
+ // Any other whole-run failure (compile failure, crash, timeout) is an error with its reason, never a null answer.
1862
+ if (run.status === 'error') {
1863
+ if (args.json) { console.log(JSON.stringify({ schema: 'thunder-target-v1', target: targetKey, status: 'error', error: { kind: run.kind, message: run.message }, cases: gradeRun(ast, run) }, null, 2)); process.exit(1); return; }
1864
+ console.log(`thunder test ${basename(file)} --target ${targetKey}: ERROR (${run.kind}) , ${run.message}`);
1865
+ process.exit(1);
1866
+ return;
1722
1867
  }
1868
+ const cases = gradeRun(ast, run);
1723
1869
  const passed = cases.filter((c) => c.pass).length;
1870
+ const errors = cases.filter((c) => c.status === 'error').length;
1724
1871
  const bad = passed !== cases.length;
1725
- if (args.json) { console.log(JSON.stringify({ schema: 'thunder-target-v1', target: targetKey, total: cases.length, passed, cases }, null, 2)); process.exit(bad ? 1 : 0); return; }
1872
+ if (args.json) { console.log(JSON.stringify({ schema: 'thunder-target-v1', target: targetKey, total: cases.length, passed, errors, cases }, null, 2)); process.exit(bad ? 1 : 0); return; }
1726
1873
  if (!cases.length) { console.log(`thunder test ${basename(file)} --target ${targetKey}: no decision test cases to run.`); return; }
1727
- console.log(`thunder test ${basename(file)} --target ${targetKey}: ${passed}/${cases.length} passed (executed generated code)`);
1728
- for (const c of cases) console.log(` ${c.pass ? 'PASS' : 'FAIL'} ${c.key}${c.pass ? '' : ` , expected ${c.expected}, got ${c.actual}`}`);
1874
+ console.log(`thunder test ${basename(file)} --target ${targetKey}: ${passed}/${cases.length} passed (executed generated code)${errors ? `, ${errors} could not run` : ''}`);
1875
+ for (const c of cases) console.log(` ${c.pass ? `PASS ${c.key}` : caseLine(c).replace(/^(FAIL|ERROR) /, (m) => m.trim().padEnd(6))}`);
1729
1876
  process.exit(bad ? 1 : 0);
1730
1877
  return;
1731
1878
  }
@@ -1953,19 +2100,23 @@ test Example
1953
2100
  targets = Array.from(new Set([...targets, ...LIVE_TARGETS.map((t) => t.key)]));
1954
2101
  for (const t of LIVE_TARGETS) {
1955
2102
  if (!t.available()) { skippedTargets.push(t.key); continue; }
1956
- const actual = t.run(ast);
1957
- if (actual !== null) results[t.key] = actual; else skippedTargets.push(t.key);
2103
+ const run = t.run(ast);
2104
+ if (run.status === 'error' && run.kind === 'missing-toolchain') skippedTargets.push(t.key);
2105
+ else results[t.key] = caseResultsOf(ast, run);
1958
2106
  }
1959
2107
  }
1960
2108
  // --run <targets>: execute specific live targets (TypeScript/JS/Python/C#/Java) and grade real
1961
- // outputs. A null result (e.g. the SDK is not installed) is skipped, leaving it "declared".
2109
+ // outputs. A missing toolchain is skipped, leaving it "declared"; any other failure (not
2110
+ // translated, compile failure, crash, timeout) is graded as an error with its reason.
1962
2111
  if (args.run && args.run.length) {
1963
2112
  results = results || {};
1964
2113
  for (const rt of args.run) {
1965
2114
  if (!RUNNABLE_TARGETS.has(rt.toLowerCase())) continue;
1966
2115
  const key = canonicalTarget(rt);
1967
- const actual = runLiveTarget(ast, key);
1968
- if (actual !== null) results[key] = actual;
2116
+ if (!targets.includes(key)) targets = [...targets, key]; // a target you ran is always shown
2117
+ const run = runLiveTarget(ast, key);
2118
+ if (run.status === 'error' && run.kind === 'missing-toolchain') skippedTargets.push(key);
2119
+ else results[key] = caseResultsOf(ast, run);
1969
2120
  }
1970
2121
  }
1971
2122
  const rep = buildConformance(ast, { targets, results });
@@ -1979,7 +2130,7 @@ test Example
1979
2130
  if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
1980
2131
  if (!rep.total) { console.log(`thunder conform ${basename(file)}: no test cases to conform.`); return; }
1981
2132
 
1982
- const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
2133
+ const cap = (s) => ({ typescript: 'TypeScript', csharp: 'C#', javascript: 'JavaScript' })[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
1983
2134
  const cols = ['Semantic', ...rep.columns.map(cap)];
1984
2135
  const labelW = Math.max(12, ...rep.cases.map((c) => c.key.length));
1985
2136
  const cw = (h) => Math.max(h.length, 8);
@@ -1990,7 +2141,7 @@ test Example
1990
2141
  const sem = c.semanticPass ? 'PASS' : 'FAIL';
1991
2142
  const tcells = rep.columns.map((col) => {
1992
2143
  const s = c.targets[col].status;
1993
- return cell(s === 'pass' ? 'PASS' : s === 'fail' ? 'FAIL' : '—', cw(cap(col)));
2144
+ return cell(s === 'pass' ? 'PASS' : s === 'fail' ? 'FAIL' : s === 'error' ? 'ERROR' : '—', cw(cap(col)));
1994
2145
  });
1995
2146
  console.log(` ${cell(c.key, labelW)} ${cell(sem, cw('Semantic'))} ${tcells.join(' ')}`);
1996
2147
  }
@@ -2000,7 +2151,8 @@ test Example
2000
2151
  console.log(` Target: ${cap(f.target)}`);
2001
2152
  console.log(` Case: ${f.case}`);
2002
2153
  console.log(` Expected: ${f.expected}`);
2003
- console.log(` Actual: ${f.actual}`);
2154
+ if (f.kind && f.kind !== 'assertion-failed') console.log(` Result: ${f.kind === 'not-translated' ? 'not translated' : f.kind === 'missing-input' ? 'missing input' : f.kind} , ${f.message}`);
2155
+ else console.log(` Actual: ${f.actual === null ? 'null' : f.actual}`);
2004
2156
  }
2005
2157
  if (rep.skipped && rep.skipped.length) {
2006
2158
  console.log('');