@skillstech/thunderlang 0.5.11 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +437 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillstech/thunderlang",
3
- "version": "0.5.11",
3
+ "version": "0.5.12",
4
4
  "description": "Deterministic ThunderLang compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -16,6 +16,14 @@
16
16
  "import": "./src/core.mjs",
17
17
  "require": "./dist/core.cjs"
18
18
  },
19
+ "./executed": {
20
+ "types": "./src/executed.d.mts",
21
+ "import": "./src/executed.mjs"
22
+ },
23
+ "./running": {
24
+ "types": "./src/running.d.mts",
25
+ "import": "./src/running.mjs"
26
+ },
19
27
  "./learn": {
20
28
  "types": "./src/learn.d.mts",
21
29
  "import": "./src/learn.mjs",
@@ -41,10 +49,11 @@
41
49
  "node": ">=18"
42
50
  },
43
51
  "scripts": {
44
- "test": "node --test",
52
+ "test": "node --test test/*.test.mjs",
53
+ "accuracy:gate": "node scripts/accuracy-gate.mjs",
45
54
  "build:cjs": "node scripts/build-cjs.mjs",
46
55
  "prepack": "node scripts/build-cjs.mjs",
47
- "prepublishOnly": "node scripts/build-cjs.mjs && node --test",
56
+ "prepublishOnly": "node scripts/build-cjs.mjs && node --test test/*.test.mjs",
48
57
  "check:example": "node src/cli.mjs check ../examples/CreateInvoice.thunder",
49
58
  "build:example": "node src/cli.mjs build ../examples/CreateInvoice.thunder"
50
59
  },
package/src/bicep.mjs ADDED
@@ -0,0 +1,167 @@
1
+ // A small Bicep reader, no library: a file is a list of declarations (`param`, `var`, `resource`, `module`,
2
+ // `output`, `targetScope`, …), each with its decorators (`@secure()`, `@description('…')`), its lines, and the comment
3
+ // above it. Values are parsed by infra-expr.mjs, including nested `resource` declarations inside a resource. A
4
+ // declaration Thunder cannot parse is kept as an error with its line and skipped, never guessed.
5
+ import { tokenize, lineIndex, Parser, ParseError } from './infra-expr.mjs';
6
+ import { docAbove } from './hcl.mjs';
7
+
8
+ /**
9
+ * Parse Bicep source. Returns { decls, comments, errors }. Each decl:
10
+ * { kind: 'param' | 'var' | 'resource' | 'module' | 'output' | 'targetScope' | 'metadata' | 'type' | 'func' | 'import' | 'other',
11
+ * name, type?, typeRaw?, value?, existing?, decorators: [{ name, args }], line, endLine, doc? }
12
+ * `type` is the resource type ('Microsoft.Storage/storageAccounts'), `apiVersion` its version, `path` a module's file.
13
+ */
14
+ export function parseBicep(src) {
15
+ const text = String(src ?? '').replace(/^/, '');
16
+ const lineAt = lineIndex(text);
17
+ const { toks, comments } = tokenize(text, 'bicep', 0, text.length, lineAt);
18
+ const p = new Parser(text, toks, 'bicep', lineAt, { objectKey: nestedResource });
19
+ const decls = [], errors = [];
20
+ let decorators = [];
21
+ for (;;) {
22
+ p.newlines();
23
+ const t = p.peek();
24
+ if (t.k === 'eof') break;
25
+ const start = p.i;
26
+ try {
27
+ if (t.k === 'p' && t.v === '@') { decorators.push(decorator(p)); continue; }
28
+ const d = decl(p);
29
+ if (decorators.length) { d.decorators = decorators; d.line = Math.min(d.line, decorators[0].line); }
30
+ const doc = docAbove(comments, d.line) || '';
31
+ if (doc) d.doc = doc;
32
+ decls.push(d);
33
+ decorators = [];
34
+ } catch (e) {
35
+ if (!(e instanceof ParseError)) throw e;
36
+ errors.push({ line: e.line, why: e.why });
37
+ p.i = resync(toks, start);
38
+ decorators = [];
39
+ }
40
+ }
41
+ return { decls, comments, errors, lineAt, src: text };
42
+ }
43
+
44
+ function resync(toks, i) {
45
+ let depth = 0;
46
+ for (i++; i < toks.length; i++) {
47
+ const t = toks[i];
48
+ if (t.k === 'eof') return i;
49
+ if (t.k === 'p' && (t.v === '{' || t.v === '[' || t.v === '(')) depth++;
50
+ else if (t.k === 'p' && (t.v === '}' || t.v === ']' || t.v === ')')) depth--;
51
+ else if (t.k === 'nl' && depth <= 0) return i + 1;
52
+ }
53
+ return i;
54
+ }
55
+
56
+ function decorator(p) {
57
+ const at = p.next();
58
+ const x = p.postfix(p.primary());
59
+ const name = x.t === 'call' ? x.name.replace(/^sys\./, '') : x.t === 'ref' ? x.path.join('.').replace(/^sys\./, '') : 'decorator';
60
+ return { name, args: x.t === 'call' ? x.args : [], line: p.lineOf(at) };
61
+ }
62
+
63
+ /** A resource type string 'Microsoft.X/y@2023-01-01' split into its type and version. */
64
+ export function splitType(s) {
65
+ const v = String(s ?? '');
66
+ const at = v.lastIndexOf('@');
67
+ return at > 0 ? { type: v.slice(0, at), apiVersion: v.slice(at + 1) } : { type: v, apiVersion: null };
68
+ }
69
+
70
+ /** Skip a type annotation (`string`, `'a' | 'b'`, `{ … }`, `string[]`, `resource 'x'`) up to `=` or the end of the line. */
71
+ function typeText(p) {
72
+ const s = p.peek().s;
73
+ let depth = 0, e = s;
74
+ for (;;) {
75
+ const t = p.toks[p.i];
76
+ if (!t || t.k === 'eof') break;
77
+ if (depth === 0 && t.k === 'p' && t.v === '=') break;
78
+ if (depth === 0 && t.k === 'nl') {
79
+ // A union type may go on over several lines, each starting with `|`.
80
+ let k = p.i;
81
+ while (p.toks[k]?.k === 'nl') k++;
82
+ if (p.toks[k]?.k === 'p' && p.toks[k].v === '|') { p.i = k; continue; }
83
+ break;
84
+ }
85
+ if (t.k === 'p' && (t.v === '{' || t.v === '[' || t.v === '(')) depth++;
86
+ if (t.k === 'p' && (t.v === '}' || t.v === ']' || t.v === ')')) depth--;
87
+ e = t.e; p.i++;
88
+ }
89
+ return p.src.slice(s, e).trim();
90
+ }
91
+
92
+ function restOfStatement(p) {
93
+ typeText(p);
94
+ if (p.toks[p.i]?.k === 'p' && p.toks[p.i].v === '=') { p.i++; typeText(p); }
95
+ }
96
+
97
+ function resourceDecl(p, kw, line) {
98
+ const name = p.next();
99
+ if (name.k !== 'id') throw new ParseError(`Expected the ${kw}'s name`, line);
100
+ const ty = p.next();
101
+ if (ty.k !== 'str') throw new ParseError(`Expected the ${kw === 'module' ? "module's file" : 'resource type'} after ${name.v}`, line);
102
+ const tyNode = p.string(ty);
103
+ let existing = false;
104
+ if (p.isId('existing')) { p.next(); existing = true; }
105
+ p.expect('=');
106
+ const value = p.expr();
107
+ const base = { kind: kw, name: name.v, value, line, endLine: p.lineAt(Math.max(value.s, value.e - 1)), decorators: [] };
108
+ if (kw === 'module') return { ...base, path: tyNode.v ?? p.src.slice(ty.s + 1, ty.e - 1) };
109
+ const { type, apiVersion } = splitType(tyNode.v ?? '');
110
+ return { ...base, type, apiVersion, ...(existing ? { existing: true } : {}) };
111
+ }
112
+
113
+ function decl(p) {
114
+ return p.withNl(false, () => {
115
+ const t = p.next();
116
+ const line = p.lineOf(t);
117
+ if (t.k !== 'id') throw new ParseError(`Expected a declaration, found "${p.src.slice(t.s, t.e).slice(0, 20)}"`, line);
118
+ const end = (value) => p.lineAt(Math.max(value.s, value.e - 1));
119
+ switch (t.v) {
120
+ case 'targetScope': { p.expect('='); const value = p.expr(); return { kind: 'targetScope', name: 'targetScope', value, line, endLine: end(value), decorators: [] }; }
121
+ case 'param': {
122
+ const name = p.next().v;
123
+ const typeRaw = typeText(p);
124
+ let value = null;
125
+ if (p.is('=')) { p.next(); value = p.expr(); }
126
+ return { kind: 'param', name, typeRaw, value, line, endLine: value ? end(value) : line, decorators: [] };
127
+ }
128
+ case 'var': case 'metadata': { const name = p.next().v; const typeRaw = p.is('=') ? '' : typeText(p); p.expect('='); const value = p.expr(); return { kind: t.v, name, ...(typeRaw ? { typeRaw } : {}), value, line, endLine: end(value), decorators: [] }; }
129
+ case 'output': {
130
+ const name = p.next().v;
131
+ let typeRaw;
132
+ if (p.isId('resource')) { p.next(); typeRaw = `resource ${p.src.slice(p.peek().s, p.peek().e)}`; p.next(); }
133
+ else typeRaw = typeText(p);
134
+ p.expect('=');
135
+ const value = p.expr();
136
+ return { kind: 'output', name, typeRaw, value, line, endLine: end(value), decorators: [] };
137
+ }
138
+ case 'resource': case 'module': return resourceDecl(p, t.v, line);
139
+ case 'type': case 'func': case 'import': case 'using': case 'extension': case 'provider': case 'extends': case 'assert': {
140
+ const nm = p.peek();
141
+ restOfStatement(p);
142
+ return { kind: t.v === 'type' || t.v === 'func' ? t.v : t.v === 'assert' ? 'other' : 'import', name: nm.k === 'id' ? nm.v : p.src.slice(nm.s, nm.e), line, endLine: p.lineAt(Math.max(0, p.toks[Math.max(0, p.i - 1)].e - 1)), decorators: [] };
143
+ }
144
+ default: throw new ParseError(`"${t.v}" is not a Bicep declaration Thunder reads`, line);
145
+ }
146
+ });
147
+ }
148
+
149
+ /** Inside a resource's body: `resource child 'type' = { … }` is a nested resource. */
150
+ function nestedResource(p, kt) {
151
+ // Decorators on a nested resource (`@batchSize(1)`) come first.
152
+ if (kt.k === 'p' && kt.v === '@') {
153
+ const decorators = [];
154
+ while (p.is('@')) { decorators.push(decorator(p)); p.newlines(); }
155
+ const r = nestedResource(p, p.peek());
156
+ if (!r) throw new ParseError('Expected a resource after its decorators', decorators[0].line);
157
+ r.nested.decorators = decorators;
158
+ return r;
159
+ }
160
+ if (kt.k !== 'id' || kt.v !== 'resource') return null;
161
+ const nx = p.peek(1);
162
+ if (nx.k !== 'id') return null;
163
+ p.next();
164
+ const line = p.lineOf(kt);
165
+ const d = resourceDecl(p, 'resource', line);
166
+ return { key: 'resource', nested: d, value: d.value, line };
167
+ }
package/src/cli.mjs CHANGED
@@ -22,6 +22,7 @@ import { thunderizeFiles, THUNDER_TEXT_EXT } from './thunderize.mjs';
22
22
  import { sameMeaning, renderSame } from './same.mjs';
23
23
  import { anchorReport } from './anchor.mjs';
24
24
  import { writeRule } from './write.mjs';
25
+ import { thunderWrite } from './write-steps.mjs';
25
26
  import { readCode, searchReading } from './read.mjs';
26
27
  import { readRepo, searchRepo, groupByFile } from './read-repo.mjs';
27
28
  import { promoteDecision } from './promote.mjs';
@@ -45,6 +46,9 @@ import { guardianReport } from './guardian.mjs';
45
46
  import { simulateChange } from './simulate.mjs';
46
47
  import { verifyLedger, explain as ledgerExplain } from './ledger.mjs';
47
48
  import { verifyDiff } from './verify-diff.mjs';
49
+ import { verifyRun, executedText, mergeTraces } from './executed.mjs';
50
+ import { runtimeOverlay, runtimeText, fromTrace, fromStack, fromLogs, fromOtlp, parseStacks, explainError, countWords } from './running.mjs';
51
+ import { thunderModel } from './model.mjs';
48
52
  import { guardSummary } from './guard.mjs';
49
53
  import { draftIntent } from './draft.mjs';
50
54
  import { liftSource, liftAll, liftRepo, languageForFile } from './lift.mjs';
@@ -59,13 +63,14 @@ import { comprehensionLevel, comprehensionReport, LEVELS as COMPREHENSION_LEVELS
59
63
  import { twelveFactorReport } from './twelve-factor.mjs';
60
64
  import { GENERATORS } from './codegen.mjs';
61
65
  import { changeReport } from './changes.mjs';
62
- import { execSync, spawnSync } from 'node:child_process';
66
+ import { execSync, execFileSync, spawnSync } from 'node:child_process';
63
67
  import { diffGraphs, mergeGraphs } from './semantic-diff.mjs';
64
68
  import { applyWaivers, governanceDiagnostics } from './governance.mjs';
65
69
  import { exportIntent, EXPORT_FORMATS } from './exporters.mjs';
66
70
  import { evaluateDecision, simulateLifecycle } from './runtime.mjs';
67
71
  import { runProperties } from './property.mjs';
68
72
  import { runMutations } from './mutate.mjs';
73
+ import { thunderReview, renderReview } from './review.mjs';
69
74
  import { buildConformance } from './conformance.mjs';
70
75
  import { semanticCoverage } from './coverage.mjs';
71
76
  import { runTypescriptTarget } from './target-ts.mjs';
@@ -134,7 +139,7 @@ import { parseEventLog, serializeEventLog, recordEvent, timeline } from './ai-ev
134
139
  const LIFT_EXTS = [
135
140
  '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.rs', '.pl', '.pm', '.t',
136
141
  '.py', '.pyi', '.java', '.cs', '.go', '.cpp', '.cc', '.cxx', '.hpp', '.hh', '.c', '.h',
137
- '.php', '.rb', '.kt', '.kts', '.scala', '.sc', '.ex', '.exs',
142
+ '.php', '.rb', '.kt', '.kts', '.scala', '.sc', '.ex', '.exs', '.swift',
138
143
  ];
139
144
  const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.next', 'build', '.intent', 'coverage', '.vercel']);
140
145
  // ThunderLang source files. `.thunder` is the canonical public extension; `.tl` is an
@@ -202,6 +207,38 @@ function collectIntents(root, acc = []) {
202
207
 
203
208
  // Proof freshness: a proof is valid only for a specific (intent, implementation, dependencies,
204
209
  // compiler, environment) tuple. These helpers capture that tuple so `verify` can mark a proof STALE.
210
+ /**
211
+ * Read the files that changed between two commits (or a commit and the working tree, when head is null) and review
212
+ * them in Thunder. Only git is run (show, diff, ls-files): nothing is fetched and nothing is executed.
213
+ */
214
+ function reviewGit(base, head) {
215
+ const git = (...a) => execFileSync('git', a, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
216
+ try { git('rev-parse', '--is-inside-work-tree'); } catch { throw new Error('not inside a git repository.'); }
217
+ for (const ref of [base, head].filter(Boolean)) {
218
+ 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
+ }
220
+ const root = git('rev-parse', '--show-toplevel').trim();
221
+ const parts = git('diff', '--name-status', '-z', '-M', base, ...(head ? [head] : []), '--').split('\0');
222
+ const changes = [];
223
+ for (let i = 0; i < parts.length && parts[i];) {
224
+ const status = parts[i++];
225
+ if (/^[RC]/.test(status)) changes.push({ old: parts[i++], new: parts[i++] });
226
+ else if (status === 'A') changes.push({ old: null, new: parts[i++] });
227
+ else if (status === 'D') changes.push({ old: parts[i++], new: null });
228
+ else { const p = parts[i++]; changes.push({ old: p, new: p }); }
229
+ }
230
+ if (!head) for (const p of git('ls-files', '--others', '--exclude-standard', '-z').split('\0').filter(Boolean)) changes.push({ old: null, new: p });
231
+ const text = (s) => (s == null || s.includes('\0') ? null : s); // binary files are not read
232
+ const at = (ref, p) => { try { return text(git('show', `${ref}:${p}`)); } catch { return null; } };
233
+ const disk = (p) => { try { return text(readFileSync(join(root, p), 'utf8')); } catch { return null; } };
234
+ const oldFiles = [], newFiles = [];
235
+ for (const c of changes) {
236
+ if (c.old) { const s = at(base, c.old); if (s != null) oldFiles.push({ path: c.old, source: s }); }
237
+ if (c.new) { const s = head ? at(head, c.new) : disk(c.new); if (s != null) newFiles.push({ path: c.new, source: s }); }
238
+ }
239
+ return { ...thunderReview(oldFiles, newFiles), base, head: head ?? 'working tree' };
240
+ }
241
+
205
242
  const gitCmd = (c) => { try { return execSync(`git ${c}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim() || null; } catch { return null; } };
206
243
  const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'poetry.lock', 'Pipfile.lock', 'Cargo.lock', 'go.sum', 'Gemfile.lock', 'composer.lock'];
207
244
  function findLockfile(startDir) {
@@ -273,6 +310,11 @@ function parseArgs(argv) {
273
310
  else if (a === '--inputs') args.inputs = argv[++i];
274
311
  else if (a === '--events') args.events = (argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
275
312
  else if (a === '--decision') args.decision = argv[++i];
313
+ else if (a === '--edit') (args.edit ??= []).push(argv[++i]);
314
+ else if (a === '--apply') args.apply = true;
315
+ else if (a === '--test') args.test = argv[++i];
316
+ else if (a === '--candidate') args.candidate = argv[++i];
317
+ else if (a === '--also') (args.also ??= []).push(argv[++i]);
276
318
  else if (a === '--rule') args.rule = argv[++i];
277
319
  else if (a === '--when') args.when = argv[++i];
278
320
  else if (a === '--to') args.to = argv[++i];
@@ -417,6 +459,12 @@ Prove & verify intent
417
459
  proof <file> the .thunder-proof.json artifact (see also: prove, which emits verdicts)
418
460
  proof --schema emit the canonical proof envelope JSON Schema (intent-proof-v1)
419
461
  verify <proof.json> [src] re-check a proof; reports STALE when impl/deps/compiler moved
462
+ verify --run <folder> [--lang python|js] [--pytest "<args>" | --tests <dir> | --command "<cmd>"]
463
+ proof by running: run the code, compare what happened with Thunder's flows;
464
+ marks matching readings executed, exits 1 if a run contradicts a reading
465
+ runtime <folder> [--traces <file|dir>] [--stack <file>] [--logs <file>] [--otlp <file>] [--member <name>] [--top n] [--json]
466
+ the running system: what happened when it ran, on Thunder's flows (counts per
467
+ question side, Stop, and ending; calls, failures, time); errors explained in Thunder
420
468
  evidence <file> emit evidence-event-v1 JSON (tool_verified) for the shared proof spine
421
469
  (also: prove/verify-diff/conform/drift accept --evidence to emit their own event)
422
470
  conform <file> [--targets a,b] [--run typescript,python,csharp,java,go,rust,kotlin,scala,elixir | --all-targets] [--results <json>] conformance matrix across targets
@@ -439,11 +487,20 @@ Graph & IR
439
487
  human <file> [--json | --format source] experimental compact authoring and a decision reading view
440
488
  --version print the Thunder compiler version
441
489
  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).
442
496
  write <file> --decision <name> --rule <n|otherwise> [--when "<condition>"] [--answer <Outcome>] [--write] [--json]
443
497
  Thunder write: change a number, comparison, text value, or answer in a recovered rule;
444
498
  previews the exact code change and the cases whose answer changes; --write saves it
445
499
  repo <owner/repo | github url | folder> [--json] [--max-files n] Thunder a whole repository (read-only; nothing is executed)
446
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
447
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)
448
505
  text <file> [--json | --format source] experimental Thunder Text rule (.thunder-plain): run its examples [alias: plain]
449
506
  read <file|dir> [--search q] [--kind decision,function,error,test] [--in <lang>] [--from <lang>] [--json]
@@ -481,7 +538,9 @@ function main() {
481
538
  }
482
539
  if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
483
540
  console.log(HELP);
484
- process.exit(cmd ? 0 : 2);
541
+ // exitCode, not exit(): the help is longer than a pipe's buffer, and exit() would cut it off when piped.
542
+ process.exitCode = cmd ? 0 : 2;
543
+ return;
485
544
  }
486
545
  if (cmd === 'read') {
487
546
  try {
@@ -528,6 +587,52 @@ function main() {
528
587
  } catch (e) { console.error(`thunder read: ${e.message}`); process.exitCode = 2; }
529
588
  return;
530
589
  }
590
+ if (cmd === 'write' && args.edit) {
591
+ try {
592
+ if (!file) throw new Error('Use thunder write <file> --edit \'{"op":"setValue","member":"name","step":"line:12","to":10}\' [--apply] [--test "<cmd>"].');
593
+ const paths = [file, ...(args.also || [])];
594
+ const files = paths.map((p) => ({ path: p, source: readFileSync(p, 'utf8') }));
595
+ let edits;
596
+ try { edits = args.edit.flatMap((e) => { const j = JSON.parse(e); return Array.isArray(j) ? j : [j]; }); } catch (e) { throw new Error(`--edit must be JSON: ${e.message}`); }
597
+ const options = args.candidate ? { candidate: { [file]: readFileSync(args.candidate, 'utf8') } } : {};
598
+ const r = thunderWrite(files, edits, options);
599
+ // --test: run the command on the changed code (written to the files for the run, then put back unless --apply).
600
+ if (r.status === 'written' && args.test) {
601
+ const originals = new Map(files.map((f) => [f.path, f.source]));
602
+ for (const [p, src] of Object.entries(r.files)) writeFileSync(p, src);
603
+ const t0 = Date.now();
604
+ const run = spawnSync(args.test, { shell: true, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
605
+ r.proof.run = { command: args.test, passed: run.status === 0, exit: run.status, seconds: Math.round((Date.now() - t0) / 100) / 10, output: `${run.stdout ?? ''}${run.stderr ?? ''}`.split('\n').slice(-20).join('\n') };
606
+ if (!args.apply) for (const [p] of Object.entries(r.files)) writeFileSync(p, originals.get(p));
607
+ }
608
+ const applied = r.status === 'written' && args.apply && (!r.proof?.run || r.proof.run.passed);
609
+ if (applied && !args.test) for (const [p, src] of Object.entries(r.files)) writeFileSync(p, src);
610
+ if (r.status === 'written' && args.apply && r.proof?.run && !r.proof.run.passed) for (const f of files) writeFileSync(f.path, f.source);
611
+ if (args.json) { const { files: _f, ...rest } = r; console.log(JSON.stringify({ ...rest, applied }, null, 2)); if (r.status !== 'written') process.exitCode = 1; return; }
612
+ if (r.status === 'refused') { console.error(`Not changed. ${r.says}`); process.exitCode = 1; return; }
613
+ if (r.status === 'needs-ai') {
614
+ console.log(r.says);
615
+ console.log('\n--- Instruction for an AI coding agent (nothing was changed) ---\n');
616
+ console.log(r.prompt);
617
+ process.exitCode = 1;
618
+ return;
619
+ }
620
+ if (r.before) { console.log('Thunder before:'); for (const l of r.before.split('\n')) console.log(` ${l}`); }
621
+ if (r.after) { console.log('Thunder after:'); for (const l of r.after.split('\n')) console.log(` ${l}`); }
622
+ console.log(`\n${r.author === 'ai' ? 'AI-written change (checked):' : 'Code change:'}\n`);
623
+ process.stdout.write(r.patch);
624
+ console.log('\nProof:');
625
+ for (const c of r.proof.edited.checks) console.log(` edited ${c.member}: ${c.result === 'exact' ? 'reads exactly as the edit says' : c.result}`);
626
+ const u = r.proof.unchanged;
627
+ console.log(` unchanged ${u.checked} other function${u.checked === 1 ? '' : 's'} in the changed file${Object.keys(r.files).length === 1 ? '' : 's'}: ${u.status === 'same' ? 'all mean the same' : u.status}`);
628
+ if (r.proof.run) console.log(` run ${r.proof.run.command}: ${r.proof.run.passed ? 'passed' : `failed (exit ${r.proof.run.exit})`}`);
629
+ if (r.proof.run && !r.proof.run.passed) console.log(r.proof.run.output);
630
+ console.log(`\n${r.says}`);
631
+ console.log(applied ? `\nSaved ${Object.keys(r.files).join(', ')}.` : r.proof?.run && !r.proof.run.passed ? '\nNot saved: the test command failed.' : '\nDry run; nothing was saved. Add --apply to save the change.');
632
+ if (r.proof?.run && !r.proof.run.passed) process.exitCode = 1;
633
+ } catch (e) { console.error(`thunder write: ${e.message}`); process.exitCode = 2; }
634
+ return;
635
+ }
531
636
  if (cmd === 'write') {
532
637
  try {
533
638
  if (!file || !args.decision || !args.rule || (args.when == null && args.answer == null)) throw new Error('Use thunder write <file> --decision <name> --rule <n|otherwise> --when "<condition>" | --answer <Outcome> [--write].');
@@ -601,6 +706,17 @@ function main() {
601
706
  finally { cleanup(); }
602
707
  return;
603
708
  }
709
+ if (cmd === 'review') {
710
+ 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();
715
+ 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
+ else console.log(text);
717
+ } catch (e) { console.error(`thunder review: ${e.message}`); process.exitCode = 2; }
718
+ return;
719
+ }
604
720
  if (cmd === 'same') {
605
721
  try {
606
722
  const [a, b] = args._;
@@ -658,6 +774,56 @@ function main() {
658
774
  console.log(JSON.stringify(intentProofJsonSchema(), null, 2));
659
775
  return;
660
776
  }
777
+ // `thunder verify --run <folder>`: proof by running. Runs the code (its tests, and made-up inputs for functions that
778
+ // look free of side effects), records which side of each question it took and how each call ended, and compares
779
+ // that with the flow Thunder drew. Exit 1 when a run contradicts any reading.
780
+ if (cmd === 'verify' && restArgv.includes('--run')) {
781
+ const opt = (name) => { const i = restArgv.indexOf(name); return i >= 0 ? restArgv[i + 1] : undefined; };
782
+ const folder = opt('--run');
783
+ if (!folder || folder.startsWith('--')) { console.error('usage: thunder verify --run <folder> [--lang python|js] [--pytest "<args>"] [--tests <dir>] [--command "<test command>"] [--cwd <dir>] [--python <path>] [--max-seconds <n>] [--no-generate] [--trace <saved.json>] [--save-trace <file>] [--all] [--json]'); process.exit(2); return; }
784
+ let res;
785
+ try {
786
+ res = verifyRun(folder, { lang: opt('--lang'), pytest: opt('--pytest'), tests: opt('--tests'), command: opt('--command'), cwd: opt('--cwd'), python: opt('--python'), trace: opt('--trace'),
787
+ maxSeconds: opt('--max-seconds') ? Number(opt('--max-seconds')) : undefined, generate: !restArgv.includes('--no-generate') });
788
+ } catch (e) { console.error(`thunder verify --run: ${e.message}`); process.exit(2); return; }
789
+ if (opt('--save-trace')) writeFileSync(opt('--save-trace'), JSON.stringify(res.trace));
790
+ if (restArgv.includes('--json')) console.log(JSON.stringify(res.result, null, 2));
791
+ else console.log(`thunder verify --run ${folder} (${res.result.language})\n${executedText(res.result, { all: restArgv.includes('--all') })}`);
792
+ if (res.result.summary.contradicted) process.exitCode = 1;
793
+ return;
794
+ }
795
+ // `thunder runtime <folder>`: the running system. Places recorded runs (thunder verify --run --save-trace), stack
796
+ // traces, structured logs, and OpenTelemetry spans on the folder's flows, and explains each error in Thunder.
797
+ if (cmd === 'runtime') {
798
+ const opt = (name) => { const i = restArgv.indexOf(name); return i >= 0 ? restArgv[i + 1] : undefined; };
799
+ const folder = restArgv[0];
800
+ const usage = 'usage: thunder runtime <folder> [--traces <file|dir>] [--stack <file>] [--logs <file>] [--otlp <file>] [--member <name>] [--top <n>] [--json]';
801
+ if (!folder || folder.startsWith('--') || !existsSync(folder) || !statSync(folder).isDirectory()) { console.error(folder && !folder.startsWith('--') ? `thunder runtime: ${folder} is not a folder.\n${usage}` : usage); process.exit(2); return; }
802
+ const evidence = [];
803
+ const stacks = [];
804
+ try {
805
+ const traces = opt('--traces');
806
+ if (traces) {
807
+ const t = { files: {}, runs: [] };
808
+ const list = statSync(traces).isDirectory() ? readdirSync(traces).filter((n) => n.endsWith('.json')).map((n) => join(traces, n)) : [traces];
809
+ for (const f of list) mergeTraces(t, JSON.parse(readFileSync(f, 'utf8')));
810
+ evidence.push(...fromTrace(t));
811
+ }
812
+ if (opt('--stack')) { const text = readFileSync(opt('--stack'), 'utf8'); evidence.push(...fromStack(text)); stacks.push(...parseStacks(text)); }
813
+ if (opt('--logs')) evidence.push(...fromLogs(readFileSync(opt('--logs'), 'utf8')));
814
+ if (opt('--otlp')) evidence.push(...fromOtlp(readFileSync(opt('--otlp'), 'utf8')));
815
+ } catch (e) { console.error(`thunder runtime: ${e.message}`); process.exit(2); return; }
816
+ if (!evidence.length) { console.error(`thunder runtime: no evidence given.\n${usage}`); process.exit(2); return; }
817
+ const model = thunderModel(collectReadableFiles(folder, { maxFiles: 5000 }).filter((f) => f.source), { name: basename(resolve(folder)) });
818
+ const overlay = runtimeOverlay(model, evidence);
819
+ const explained = stacks.map((s) => explainError(model, s));
820
+ if (restArgv.includes('--json')) { console.log(JSON.stringify({ ...overlay, errors: explained }, null, 2)); return; }
821
+ const out = [`thunder runtime ${folder}: ${Object.entries(overlay.sources).map(([k, v]) => `${k}: ${countWords(v)} observation${v === 1 ? '' : 's'}`).join(', ')} (counts only from this evidence)`, ''];
822
+ if (explained.length) { out.push('Errors, explained in Thunder:'); for (const x of explained) out.push(` - ${x.text}`); out.push(''); }
823
+ out.push(runtimeText(model, overlay, { member: opt('--member') ?? null, top: opt('--top') ? Number(opt('--top')) : 10 }));
824
+ process.stdout.write(`${out.join('\n').replace(/\n+$/, '')}\n`);
825
+ return;
826
+ }
661
827
  // Verify a .thunder-proof.json against its source: the source hash still matches (no
662
828
  // drift / tampering) and the proof's claims re-derive from the source.
663
829
  if (cmd === 'verify') {