@skillstech/thunderlang 1.6.1 → 1.7.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.
- package/CHANGELOG.md +46 -0
- package/dist/core.cjs +31 -28
- package/dist/index.cjs +292 -59
- package/dist/learn.cjs +81 -22
- package/package.json +1 -1
- package/src/ai.mjs +2 -1
- package/src/atlas.mjs +2 -1
- package/src/behaviour.mjs +246 -0
- package/src/cli-main.mjs +2818 -0
- package/src/cli.mjs +9 -2799
- package/src/conflict.mjs +0 -0
- package/src/core/ThunderDotnet.cs +195 -0
- package/src/core/check.mjs +4 -4
- package/src/core/cli.mjs +7 -2
- package/src/core/csharp-run.mjs +29 -8
- package/src/core/diagnostics.mjs +3 -1
- package/src/core/engine-core.mjs +20 -1
- package/src/core/go-run.mjs +3 -2
- package/src/core/java-run.mjs +3 -3
- package/src/core/kind.mjs +42 -0
- package/src/core/parser.mjs +54 -7
- package/src/core/project.mjs +3 -0
- package/src/core/react-run.mjs +3 -3
- package/src/core/runtime-npm.mjs +79 -0
- package/src/core/runtime-react.mjs +2 -1
- package/src/core/runtime-typescript.mjs +7 -3
- package/src/core/rust-run.mjs +3 -2
- package/src/core/target-csharp.mjs +5 -1
- package/src/core/target-go.mjs +1 -1
- package/src/core/target-python.mjs +1 -1
- package/src/core/target-rust.mjs +1 -1
- package/src/core/target-typescript.mjs +33 -1
- package/src/core/typescript-run.mjs +9 -4
- package/src/decision.mjs +2 -1
- package/src/distributed.mjs +2 -1
- package/src/emit.mjs +2 -2
- package/src/focus.mjs +2 -1
- package/src/intent-atlas.mjs +4 -3
- package/src/mcp.mjs +10 -3
- package/src/passport-fs.mjs +2 -1
- package/src/passport.mjs +2 -1
- package/src/privacy.mjs +2 -1
- package/src/read-repo.mjs +3 -2
- package/src/report.mjs +3 -2
- package/src/review.mjs +2 -1
- package/src/select.mjs +2 -1
- package/src/semantic-diff.mjs +7 -6
- package/src/system.mjs +2 -1
- package/src/text-order.mjs +6 -0
- package/src/thunderize.mjs +2 -1
- package/src/trace-data.mjs +3 -2
- package/src/trace.mjs +4 -3
- package/src/write-across-cli.mjs +22 -4
- package/src/write-across.mjs +2 -1
- package/syntaxes/thunder.tmLanguage.json +196 -0
package/src/cli-main.mjs
ADDED
|
@@ -0,0 +1,2818 @@
|
|
|
1
|
+
// ThunderLang CLI (MVP, deterministic). Commands: check | graph | proof | build.
|
|
2
|
+
//
|
|
3
|
+
// The emit stage writes the artifacts the ecosystem consumes to `.intent/<mission>/` by DEFAULT,
|
|
4
|
+
// NOT `dist/` , OpenThunder's scanner excludes dist/node_modules, so proof artifacts must live in a
|
|
5
|
+
// committed, scannable location. `.intent/` mirrors the ecosystem's dot-dir convention (.openthunder/).
|
|
6
|
+
//
|
|
7
|
+
// thunder check <file> parse + semantic diagnostics (exit 1 on error)
|
|
8
|
+
// thunder graph <file> [--out .intent] contract-graph.json + architecture-graph.json
|
|
9
|
+
// intent proof <file> [--out .intent] .thunder-proof.json
|
|
10
|
+
// intent build <file> [--out .intent] [--no-ai] all artifacts + docs + mermaid + testplan
|
|
11
|
+
//
|
|
12
|
+
// --no-ai is the default and only mode today; the flag is accepted for forward-compatibility.
|
|
13
|
+
|
|
14
|
+
import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync } from 'node:fs';
|
|
15
|
+
import { basename, join, relative, dirname, resolve } from 'node:path';
|
|
16
|
+
import { parseIntent, slug, subjectName, KNOWN_LENSES } from './parse.mjs';
|
|
17
|
+
import { previewHumanContract, renderHumanContract } from './human-contract.mjs';
|
|
18
|
+
import { previewPlainContract } from './plain-contract.mjs';
|
|
19
|
+
import { thunderRepo, renderThunderRepo, parseGitHub, cloneGitHub } from './thunder-repo.mjs';
|
|
20
|
+
import { thunderizeFiles, THUNDER_TEXT_EXT } from './thunderize.mjs';
|
|
21
|
+
import { sameMeaning, renderSame } from './same.mjs';
|
|
22
|
+
import { anchorReport } from './anchor.mjs';
|
|
23
|
+
import { writeRule } from './write.mjs';
|
|
24
|
+
import { thunderWrite } from './write-steps.mjs';
|
|
25
|
+
import { readCode, searchReading } from './read.mjs';
|
|
26
|
+
import { readRepo, searchRepo, groupByFile } from './read-repo.mjs';
|
|
27
|
+
import { promoteDecision } from './promote.mjs';
|
|
28
|
+
import { collectReadableFiles } from './read-repo-fs.mjs';
|
|
29
|
+
import { accessFlow, accessText } from './flow/access.mjs';
|
|
30
|
+
import { translateDecisions } from './translate.mjs';
|
|
31
|
+
import {
|
|
32
|
+
buildContractGraph, buildArchitectureGraph, buildImplementationPlan,
|
|
33
|
+
semanticDiagnostics, buildProof, sha256, COMPILER_VERSION,
|
|
34
|
+
} from './emit.mjs';
|
|
35
|
+
import { toSarif } from './sarif.mjs';
|
|
36
|
+
import { renderMarkdown, renderLensDoc, renderMermaid, renderTestplan } from './compile.mjs';
|
|
37
|
+
import { getCompletions, getHover, getCodeActions, autocorrectSource } from './intellisense.mjs';
|
|
38
|
+
import { startLspServer } from './lsp.mjs';
|
|
39
|
+
import { startMcpServer } from './mcp.mjs';
|
|
40
|
+
import { formatSource } from './format.mjs';
|
|
41
|
+
import { applyEdits } from './patch.mjs';
|
|
42
|
+
import { buildReport } from './report.mjs';
|
|
43
|
+
import { scanProject } from './scan.mjs';
|
|
44
|
+
import { VIEWS } from './scan-queries.mjs';
|
|
45
|
+
import { guardianReport } from './guardian.mjs';
|
|
46
|
+
import { simulateChange } from './simulate.mjs';
|
|
47
|
+
import { verifyLedger, explain as ledgerExplain } from './ledger.mjs';
|
|
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';
|
|
52
|
+
import { LEVELS, readLevel, renderLevel, findFocus, nearestLevel } from './read-level.mjs';
|
|
53
|
+
import { traceMain } from './trace-cli.mjs';
|
|
54
|
+
import { passportMain } from './passport-cli.mjs';
|
|
55
|
+
import { isWriteAcross, writeAcrossMain } from './write-across-cli.mjs';
|
|
56
|
+
import { whyMain } from './why-cli.mjs';
|
|
57
|
+
import { tryMain } from './try-cli.mjs';
|
|
58
|
+
import { replayMain } from './replay-cli.mjs';
|
|
59
|
+
import { homeText, helpFor, knownCommands, unknownCommandText, noProjectText, doctorMain, completionMain } from './cli-home.mjs';
|
|
60
|
+
import { paint, paintHelp, paintThunder, useColor } from './term.mjs';
|
|
61
|
+
import { coreMain } from './core/cli.mjs';
|
|
62
|
+
import { behaviourCheck } from './behaviour.mjs';
|
|
63
|
+
import { findProjectRoot } from './core/project.mjs';
|
|
64
|
+
import { pythonToCore } from './core/from-python.mjs';
|
|
65
|
+
import { guardSummary } from './guard.mjs';
|
|
66
|
+
import { draftIntent } from './draft.mjs';
|
|
67
|
+
import { liftSource, liftAll, liftRepo, languageForFile } from './lift.mjs';
|
|
68
|
+
import { approveIntent, checkDrift, buildDriftHandoff } from './drift.mjs';
|
|
69
|
+
import { buildMissionIndex } from './atlas.mjs';
|
|
70
|
+
import { parseSelection, regionMetrics, selectCandidate } from './select.mjs';
|
|
71
|
+
import { buildIntentGraph, safeGraph } from './intent-graph.mjs';
|
|
72
|
+
import { buildAtlas, searchAtlas, expandNode } from './intent-atlas.mjs';
|
|
73
|
+
import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
|
|
74
|
+
import { buildFocusGraph, intentBrief, makeScope } from './focus.mjs';
|
|
75
|
+
import { comprehensionLevel, comprehensionReport, LEVELS as COMPREHENSION_LEVELS } from './comprehension.mjs';
|
|
76
|
+
import { twelveFactorReport } from './twelve-factor.mjs';
|
|
77
|
+
import { GENERATORS, generateWithDiagnostics } from './codegen.mjs';
|
|
78
|
+
import { changeReport } from './changes.mjs';
|
|
79
|
+
import { execSync, execFileSync, spawnSync } from 'node:child_process';
|
|
80
|
+
import { diffGraphs, mergeGraphs } from './semantic-diff.mjs';
|
|
81
|
+
import { applyWaivers, governanceDiagnostics } from './governance.mjs';
|
|
82
|
+
import { exportIntent, EXPORT_FORMATS } from './exporters.mjs';
|
|
83
|
+
import { evaluateDecision, simulateLifecycle } from './runtime.mjs';
|
|
84
|
+
import { runProperties } from './property.mjs';
|
|
85
|
+
import { runMutations } from './mutate.mjs';
|
|
86
|
+
import { thunderReview, renderReview } from './review.mjs';
|
|
87
|
+
import { buildConformance } from './conformance.mjs';
|
|
88
|
+
import { semanticCoverage } from './coverage.mjs';
|
|
89
|
+
import { runTypescriptTarget } from './target-ts.mjs';
|
|
90
|
+
import { runPythonTarget, pythonAvailable } from './target-py.mjs';
|
|
91
|
+
import { runCSharpTarget, csharpAvailable } from './target-cs.mjs';
|
|
92
|
+
import { runJavaTarget, javaAvailable } from './target-java.mjs';
|
|
93
|
+
import { runGoTarget, goAvailable } from './target-go.mjs';
|
|
94
|
+
import { runRustTarget, rustAvailable } from './target-rust.mjs';
|
|
95
|
+
import { runKotlinTarget, kotlinAvailable } from './target-kotlin.mjs';
|
|
96
|
+
import { runScalaTarget, scalaAvailable } from './target-scala.mjs';
|
|
97
|
+
import { runElixirTarget, elixirAvailable } from './target-elixir.mjs';
|
|
98
|
+
import { errorResult, runFailure } from './target-result.mjs';
|
|
99
|
+
import { byText } from './text-order.mjs';
|
|
100
|
+
|
|
101
|
+
// The live-target registry: one entry per canonical target that can be compiled + executed.
|
|
102
|
+
// `available()` is a (cached) toolchain probe; TypeScript/JS runs in-process so it is always live.
|
|
103
|
+
const LIVE_TARGETS = [
|
|
104
|
+
{ key: 'typescript', run: runTypescriptTarget, available: () => true },
|
|
105
|
+
{ key: 'python', run: runPythonTarget, available: pythonAvailable },
|
|
106
|
+
{ key: 'csharp', run: runCSharpTarget, available: csharpAvailable },
|
|
107
|
+
{ key: 'java', run: runJavaTarget, available: javaAvailable },
|
|
108
|
+
{ key: 'go', run: runGoTarget, available: goAvailable },
|
|
109
|
+
{ key: 'rust', run: runRustTarget, available: rustAvailable },
|
|
110
|
+
{ key: 'kotlin', run: runKotlinTarget, available: kotlinAvailable },
|
|
111
|
+
{ key: 'scala', run: runScalaTarget, available: scalaAvailable },
|
|
112
|
+
{ key: 'elixir', run: runElixirTarget, available: elixirAvailable },
|
|
113
|
+
];
|
|
114
|
+
const LIVE_BY_KEY = new Map(LIVE_TARGETS.map((t) => [t.key, t]));
|
|
115
|
+
LIVE_BY_KEY.set('javascript', LIVE_BY_KEY.get('typescript')); // js is the same in-process runner
|
|
116
|
+
// All canonical targets available to run right now (used by --all-targets).
|
|
117
|
+
const availableLiveTargets = () => LIVE_TARGETS.filter((t) => t.available());
|
|
118
|
+
const RUNNABLE_TARGETS = new Set([
|
|
119
|
+
'typescript', 'ts', 'javascript', 'js', 'python', 'py', 'csharp', 'cs', 'c#', 'java',
|
|
120
|
+
'go', 'golang', 'rust', 'rs', 'kotlin', 'kt', 'scala', 'sc', 'elixir', 'ex',
|
|
121
|
+
]);
|
|
122
|
+
// Map an alias to its canonical target key + the adapter that executes it.
|
|
123
|
+
const TARGET_ALIASES = {
|
|
124
|
+
ts: 'typescript', js: 'javascript', py: 'python', cs: 'csharp', 'c#': 'csharp',
|
|
125
|
+
golang: 'go', rs: 'rust', kt: 'kotlin', sc: 'scala', ex: 'elixir',
|
|
126
|
+
};
|
|
127
|
+
const canonicalTarget = (t) => TARGET_ALIASES[String(t).toLowerCase()] || String(t).toLowerCase();
|
|
128
|
+
// Execute a live target. Returns { status: 'ok', results: { "Test / case": caseResult } } or a
|
|
129
|
+
// whole-run { status: 'error', kind, message } (e.g. kind 'missing-toolchain' when the SDK is not
|
|
130
|
+
// installed). A failure is never turned into a null answer.
|
|
131
|
+
function runLiveTarget(ast, target) {
|
|
132
|
+
const entry = LIVE_BY_KEY.get(canonicalTarget(target));
|
|
133
|
+
if (!entry) return runFailure('missing-toolchain', `Thunder has no live runner for "${target}".`);
|
|
134
|
+
return entry.run(ast);
|
|
135
|
+
}
|
|
136
|
+
// Grade a live run against the intent's test cases. A case the target could not produce (not
|
|
137
|
+
// translated, compile failure, crash, timeout) is an error, never a pass and never a null answer.
|
|
138
|
+
function gradeRun(ast, run) {
|
|
139
|
+
const cs = [];
|
|
140
|
+
for (const t of ast.tests || []) {
|
|
141
|
+
if (!(ast.decisions || []).some((d) => d.name === t.name)) continue;
|
|
142
|
+
for (const c of t.cases || []) {
|
|
143
|
+
const key = `${t.name} / ${c.name || 'case'}`;
|
|
144
|
+
const r = run.status === 'ok'
|
|
145
|
+
? (run.results[key] || errorResult('runtime-error', `The target reported no result for ${key}.`))
|
|
146
|
+
: errorResult(run.kind, run.message);
|
|
147
|
+
if (r.status === 'error') { cs.push({ key, expected: c.expect, status: 'error', kind: r.kind, message: r.message, pass: false }); continue; }
|
|
148
|
+
const pass = c.expect == null || String(r.value) === String(c.expect);
|
|
149
|
+
cs.push({ key, expected: c.expect, actual: r.value, status: pass ? 'pass' : 'fail', ...(pass ? {} : { kind: 'assertion-failed' }), pass });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return cs;
|
|
153
|
+
}
|
|
154
|
+
// Per-case results for conformance: the run's own results, or the whole-run failure on every case.
|
|
155
|
+
function caseResultsOf(ast, run) {
|
|
156
|
+
if (run.status === 'ok') return run.results;
|
|
157
|
+
const out = {};
|
|
158
|
+
for (const t of ast.tests || []) for (const c of t.cases || []) out[`${t.name} / ${c.name || 'case'}`] = errorResult(run.kind, run.message);
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
const caseLine = (c) => (c.status === 'error'
|
|
162
|
+
? `ERROR ${c.key} , ${c.kind === 'not-translated' ? 'not translated' : c.kind === 'missing-input' ? 'missing input' : c.kind}: ${c.message}`
|
|
163
|
+
: `FAIL ${c.key} , expected ${c.expected}, got ${c.actual === null ? 'null' : c.actual}`);
|
|
164
|
+
import { importIntent, importReport, detectFormat, IMPORT_FORMATS } from './importers.mjs';
|
|
165
|
+
import { runTests } from './testing.mjs';
|
|
166
|
+
import { resolveObligations } from './obligations.mjs';
|
|
167
|
+
import { toEvidenceEvents, verifyDiffToEvidence, conformToEvidence, driftToEvidence } from './evidence.mjs';
|
|
168
|
+
import { evaluateOutcomes } from './outcome.mjs';
|
|
169
|
+
import { analyzeStyle } from './style.mjs';
|
|
170
|
+
import { intentProofJsonSchema, validateProof } from './proof-schema.mjs';
|
|
171
|
+
import { graphToSource } from './graph-source.mjs';
|
|
172
|
+
import { migrateGraph, validateGraph } from './migrate.mjs';
|
|
173
|
+
import { SCHEMA_VERSION, NODE_TYPES, RELATIONSHIP_TYPES, DIAGNOSTIC_RULES, ALL_DIAGNOSTICS, intentGraphJsonSchema } from './intent-schema.mjs';
|
|
174
|
+
import { CLASSIFICATIONS } from './classification.mjs';
|
|
175
|
+
import {
|
|
176
|
+
buildManifest, buildImplementationPrompt, resolveState, productionGate, adoptRegion, parseMarkers,
|
|
177
|
+
contractHash, implementationHash, recordDecision, approvalFor, emptyApprovals, makeEvent,
|
|
178
|
+
} from './ai.mjs';
|
|
179
|
+
import { parseEventLog, serializeEventLog, recordEvent, timeline } from './ai-events.mjs';
|
|
180
|
+
|
|
181
|
+
// Recursively collect supported source files, skipping vendored / build dirs.
|
|
182
|
+
// Kept in sync with lift.mjs languageForFile(): every language the lift adapters support,
|
|
183
|
+
// so repo-mode discovery matches the advertised multi-language lift surface.
|
|
184
|
+
const LIFT_EXTS = [
|
|
185
|
+
'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.rs', '.pl', '.pm', '.t',
|
|
186
|
+
'.py', '.pyi', '.java', '.cs', '.go', '.cpp', '.cc', '.cxx', '.hpp', '.hh', '.c', '.h',
|
|
187
|
+
'.php', '.rb', '.kt', '.kts', '.scala', '.sc', '.ex', '.exs', '.swift',
|
|
188
|
+
];
|
|
189
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.next', 'build', '.intent', 'coverage', '.vercel']);
|
|
190
|
+
// ThunderLang source files. `.thunder` is the canonical public extension; `.tl` is an
|
|
191
|
+
// accepted shorthand; `.intent` stays supported so legacy IntentLang sources keep working.
|
|
192
|
+
const SOURCE_EXTS = ['.thunder', '.tl', '.intent'];
|
|
193
|
+
const isSourceFile = (name) => SOURCE_EXTS.some((e) => name.endsWith(e));
|
|
194
|
+
const stripSourceExt = (name) => name.replace(/\.(thunder|tl|intent)$/i, '');
|
|
195
|
+
function collectFiles(root, acc = []) {
|
|
196
|
+
for (const name of readdirSync(root)) {
|
|
197
|
+
if (SKIP_DIRS.has(name)) continue;
|
|
198
|
+
const full = join(root, name);
|
|
199
|
+
const st = statSync(full);
|
|
200
|
+
if (st.isDirectory()) collectFiles(full, acc);
|
|
201
|
+
else if (LIFT_EXTS.some((e) => name.endsWith(e)) && !name.endsWith('.d.ts')) acc.push(full);
|
|
202
|
+
}
|
|
203
|
+
return acc;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// `thunder read <dir>`: one searchable reading of a whole repository, grouped by file.
|
|
207
|
+
function readFolder(dir, args) {
|
|
208
|
+
const index = readRepo(collectReadableFiles(dir));
|
|
209
|
+
const items = searchRepo(index, {
|
|
210
|
+
query: args.search || '', kinds: args.kind || [], languages: args.langs || [],
|
|
211
|
+
path: args.pathPrefix || '', answer: args.answer || '', input: args.input || '',
|
|
212
|
+
});
|
|
213
|
+
if (args.json) { console.log(JSON.stringify({ ...index, items }, null, 2)); return; }
|
|
214
|
+
const c = index.counts;
|
|
215
|
+
const langs = Object.entries(index.languages).map(([l, n]) => `${l} ${n}`).join(', ') || 'none';
|
|
216
|
+
console.log(`${dir}: ${index.files.length} files read (${langs}). ${c.route} route(s), ${c.decision} decision(s), ${c.function} other function(s) (${c.guarded} with checks), ${c.error} error(s), ${c.test} test(s). Inferred from code; confirm before relying on it.`);
|
|
217
|
+
if (index.skipped.length) console.log(`${index.skipped.length} file(s) skipped: ${index.skipped.slice(0, 5).map((s) => `${s.path} (${s.reason})`).join('; ')}${index.skipped.length > 5 ? '; ...' : ''}`);
|
|
218
|
+
const filtered = items.length !== index.items.length;
|
|
219
|
+
if (!filtered && index.answers.length) {
|
|
220
|
+
console.log(`\nAnswers the code gives: ${index.answers.slice(0, 12).map((a) => `${a.name} (${a.decisions.length})`).join(', ')}`);
|
|
221
|
+
console.log('Narrow with --answer <Outcome>, --input <name>, --search <words>, --kind, --lang, or --path.');
|
|
222
|
+
}
|
|
223
|
+
if (!items.length) { console.log('\nNothing matches. Try fewer words or fewer filters.'); return; }
|
|
224
|
+
const limit = Number.isFinite(args.limit) && args.limit > 0 ? args.limit : (filtered ? Infinity : 40);
|
|
225
|
+
let shown = 0;
|
|
226
|
+
for (const g of groupByFile(items)) {
|
|
227
|
+
if (shown >= limit) break;
|
|
228
|
+
console.log(`\n${g.file} (${g.language})`);
|
|
229
|
+
for (const it of g.items) {
|
|
230
|
+
if (shown++ >= limit) break;
|
|
231
|
+
console.log(` [${it.kind}${it.status === 'partial' ? ', partly read' : ''}] ${it.name} line ${it.line}: ${it.says}`);
|
|
232
|
+
if (args.inLang && it.thunder) {
|
|
233
|
+
for (const l of translateDecisions(parseIntent(it.thunder), args.inLang).split('\n').slice(2)) console.log(` ${l}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (items.length > shown) console.log(`\n${items.length - Math.min(shown, items.length)} more. Narrow the search, or pass --limit ${items.length}.`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Walk a directory for authored source files (skips the .intent/ output dir).
|
|
241
|
+
function collectIntents(root, acc = []) {
|
|
242
|
+
const st = statSync(root);
|
|
243
|
+
if (!st.isDirectory()) return isSourceFile(root) ? [root] : acc;
|
|
244
|
+
for (const name of readdirSync(root)) {
|
|
245
|
+
if (SKIP_DIRS.has(name)) continue;
|
|
246
|
+
const full = join(root, name);
|
|
247
|
+
if (statSync(full).isDirectory()) collectIntents(full, acc);
|
|
248
|
+
else if (isSourceFile(name)) acc.push(full);
|
|
249
|
+
}
|
|
250
|
+
return acc;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Proof freshness: a proof is valid only for a specific (intent, implementation, dependencies,
|
|
254
|
+
// compiler, environment) tuple. These helpers capture that tuple so `verify` can mark a proof STALE.
|
|
255
|
+
/**
|
|
256
|
+
* Read the files that changed between two commits (or a commit and the working tree, when head is null) and review
|
|
257
|
+
* them in Thunder. Only git is run (show, diff, ls-files): nothing is fetched and nothing is executed.
|
|
258
|
+
*/
|
|
259
|
+
function reviewGit(base, head, paths = []) {
|
|
260
|
+
const git = (...a) => execFileSync('git', a, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
261
|
+
try { git('rev-parse', '--is-inside-work-tree'); } catch { throw new Error('not inside a git repository.'); }
|
|
262
|
+
for (const ref of [base, head].filter(Boolean)) {
|
|
263
|
+
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).`); }
|
|
264
|
+
}
|
|
265
|
+
const root = git('rev-parse', '--show-toplevel').trim();
|
|
266
|
+
// --paths: git pathspecs with glob magic, so `src/**` and `*.py` mean what they look like.
|
|
267
|
+
const spec = paths.map((p) => `:(glob)${p}`);
|
|
268
|
+
const parts = git('diff', '--name-status', '-z', '-M', base, ...(head ? [head] : []), '--', ...spec).split('\0');
|
|
269
|
+
const changes = [];
|
|
270
|
+
for (let i = 0; i < parts.length && parts[i];) {
|
|
271
|
+
const status = parts[i++];
|
|
272
|
+
if (/^[RC]/.test(status)) changes.push({ old: parts[i++], new: parts[i++] });
|
|
273
|
+
else if (status === 'A') changes.push({ old: null, new: parts[i++] });
|
|
274
|
+
else if (status === 'D') changes.push({ old: parts[i++], new: null });
|
|
275
|
+
else { const p = parts[i++]; changes.push({ old: p, new: p }); }
|
|
276
|
+
}
|
|
277
|
+
if (!head) for (const p of git('ls-files', '--others', '--exclude-standard', '-z', '--', ...spec).split('\0').filter(Boolean)) changes.push({ old: null, new: p });
|
|
278
|
+
const text = (s) => (s == null || s.includes('\0') ? null : s); // binary files are not read
|
|
279
|
+
const at = (ref, p) => { try { return text(git('show', `${ref}:${p}`)); } catch { return null; } };
|
|
280
|
+
const disk = (p) => { try { return text(readFileSync(join(root, p), 'utf8')); } catch { return null; } };
|
|
281
|
+
const oldFiles = [], newFiles = [];
|
|
282
|
+
for (const c of changes) {
|
|
283
|
+
if (c.old) { const s = at(base, c.old); if (s != null) oldFiles.push({ path: c.old, source: s }); }
|
|
284
|
+
if (c.new) { const s = head ? at(head, c.new) : disk(c.new); if (s != null) newFiles.push({ path: c.new, source: s }); }
|
|
285
|
+
}
|
|
286
|
+
return { ...thunderReview(oldFiles, newFiles), base, head: head ?? 'working tree' };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const gitCmd = (c) => { try { return execSync(`git ${c}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim() || null; } catch { return null; } };
|
|
290
|
+
const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'poetry.lock', 'Pipfile.lock', 'Cargo.lock', 'go.sum', 'Gemfile.lock', 'composer.lock'];
|
|
291
|
+
function findLockfile(startDir) {
|
|
292
|
+
let dir = startDir || '.';
|
|
293
|
+
for (let i = 0; i < 6; i++) {
|
|
294
|
+
for (const lf of LOCKFILES) { const p = join(dir, lf); if (existsSync(p)) return p; }
|
|
295
|
+
const parent = dirname(dir); if (parent === dir) break; dir = parent;
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
function freshnessFor(file, proof, envName) {
|
|
300
|
+
const dir = dirname(file) || '.';
|
|
301
|
+
const lock = findLockfile(dir);
|
|
302
|
+
return {
|
|
303
|
+
intentHash: proof.sourceHash,
|
|
304
|
+
compilerVersion: proof.compilerVersion,
|
|
305
|
+
implementation: gitCmd('rev-parse HEAD'),
|
|
306
|
+
dependencies: lock ? { file: basename(lock), hash: sha256(readFileSync(lock, 'utf8')) } : null,
|
|
307
|
+
environment: envName || null,
|
|
308
|
+
generatedAt: proof.generatedAt,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
// Given a proof's recorded freshness, recompute the current tuple and list what has drifted.
|
|
312
|
+
function stalenessReasons(freshness, srcDir) {
|
|
313
|
+
const reasons = [];
|
|
314
|
+
if (!freshness) return reasons;
|
|
315
|
+
if (freshness.implementation) { const now = gitCmd('rev-parse HEAD'); if (now && now !== freshness.implementation) reasons.push(`implementation moved: proof at ${freshness.implementation.slice(0, 7)}, now ${now.slice(0, 7)}`); }
|
|
316
|
+
if (freshness.dependencies) { const lock = findLockfile(srcDir); const now = lock ? sha256(readFileSync(lock, 'utf8')) : null; if (now && now !== freshness.dependencies.hash) reasons.push(`dependency lockfile changed (${freshness.dependencies.file})`); }
|
|
317
|
+
if (freshness.compilerVersion && freshness.compilerVersion !== COMPILER_VERSION) reasons.push(`compiler upgraded: proof ${freshness.compilerVersion}, now ${COMPILER_VERSION}`);
|
|
318
|
+
return reasons;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function parseArgs(argv) {
|
|
322
|
+
const args = { _: [], out: '.intent', noAi: false };
|
|
323
|
+
for (let i = 0; i < argv.length; i++) {
|
|
324
|
+
const a = argv[i];
|
|
325
|
+
if (a === '--out') { args.out = argv[++i]; args.outExplicit = true; }
|
|
326
|
+
else if (a === '--no-ai') args.noAi = true;
|
|
327
|
+
else if (a === '--position') args.position = argv[++i];
|
|
328
|
+
else if (a === '--from') args.from = argv[++i];
|
|
329
|
+
else if (a === '--intent') args.intent = argv[++i];
|
|
330
|
+
else if (a === '--by') args.by = argv[++i];
|
|
331
|
+
else if (a === '--at') args.at = argv[++i];
|
|
332
|
+
else if (a === '--json') args.json = true;
|
|
333
|
+
else if (a === '--review') args.review = true;
|
|
334
|
+
else if (a === '--agent-brief') args.agentBrief = true;
|
|
335
|
+
else if (a === '--openthunder') {
|
|
336
|
+
if (!argv[i + 1] || argv[i + 1].startsWith('--')) throw new Error('--openthunder requires a JSON report path');
|
|
337
|
+
args.openthunder = argv[++i];
|
|
338
|
+
}
|
|
339
|
+
else if (a === '--targets') args.targets = (argv[++i] || '').split(',').filter(Boolean);
|
|
340
|
+
else if (a === '--product') args.product = argv[++i];
|
|
341
|
+
else if (a === '--allow-pending') args.allowPending = true;
|
|
342
|
+
else if (a === '--mode') args.mode = argv[++i];
|
|
343
|
+
else if (a === '--role') args.role = argv[++i];
|
|
344
|
+
else if (a === '--note') args.note = argv[++i];
|
|
345
|
+
else if (a === '--search') args.search = argv[++i];
|
|
346
|
+
else if (a === '--level') args.level = argv[++i] ?? '';
|
|
347
|
+
else if (a === '--focus') args.focus = argv[++i];
|
|
348
|
+
else if (a === '--kind') args.kind = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
|
|
349
|
+
else if (a === '--in') args.inLang = argv[++i];
|
|
350
|
+
else if (a === '--answer') args.answer = argv[++i];
|
|
351
|
+
else if (a === '--promote') args.promote = argv[++i];
|
|
352
|
+
else if (a === '--input') args.input = argv[++i];
|
|
353
|
+
else if (a === '--lang') args.langs = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
|
|
354
|
+
else if (a === '--path') args.pathPrefix = argv[++i];
|
|
355
|
+
else if (a === '--limit') args.limit = Number(argv[++i]);
|
|
356
|
+
else if (a === '--expand') args.expand = argv[++i];
|
|
357
|
+
else if (a === '--now') args.now = argv[++i];
|
|
358
|
+
else if (a === '--format') args.format = argv[++i];
|
|
359
|
+
else if (a === '--base') args.base = argv[++i];
|
|
360
|
+
else if (a === '--head') args.head = argv[++i];
|
|
361
|
+
else if (a === '--paths') args.paths = (argv[++i] || '').split(/[,\n]/).map((p) => p.trim()).filter(Boolean);
|
|
362
|
+
else if (a === '--inputs') args.inputs = argv[++i];
|
|
363
|
+
else if (a === '--events') args.events = (argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
364
|
+
else if (a === '--decision') args.decision = argv[++i];
|
|
365
|
+
else if (a === '--edit') (args.edit ??= []).push(argv[++i]);
|
|
366
|
+
else if (a === '--apply') args.apply = true;
|
|
367
|
+
else if (a === '--test') args.test = argv[++i];
|
|
368
|
+
else if (a === '--behaviour' || a === '--behavior') args.behaviour = true;
|
|
369
|
+
else if (a === '--candidate') args.candidate = argv[++i];
|
|
370
|
+
else if (a === '--also') (args.also ??= []).push(argv[++i]);
|
|
371
|
+
else if (a === '--rule') args.rule = argv[++i];
|
|
372
|
+
else if (a === '--when') args.when = argv[++i];
|
|
373
|
+
else if (a === '--to') args.to = argv[++i];
|
|
374
|
+
else if (a === '--force') args.force = true;
|
|
375
|
+
else if (a === '--mission') args.mission = true;
|
|
376
|
+
else if (a === '--core') args.core = true;
|
|
377
|
+
else if (a === '--as-core') args.asCore = true;
|
|
378
|
+
else if (a === '--access') args.access = true;
|
|
379
|
+
else if (a === '--write' || a === '-w') args.write = true;
|
|
380
|
+
else if (a === '--check') args.check = true;
|
|
381
|
+
else if (a === '--schema') args.schema = true;
|
|
382
|
+
else if (a === '--all') args.all = true;
|
|
383
|
+
else if (a === '--contracts') args.contracts = true;
|
|
384
|
+
else if (a === '--strict') args.strict = true;
|
|
385
|
+
else if (a === '--changed') args.changed = true;
|
|
386
|
+
else if (a === '--properties') args.properties = true;
|
|
387
|
+
else if (a === '--scenarios') args.scenarios = true;
|
|
388
|
+
else if (a === '--mutate') args.mutate = true;
|
|
389
|
+
else if (a === '--safe') args.safe = true;
|
|
390
|
+
else if (a === '--evals') args.evals = true;
|
|
391
|
+
else if (a === '--coverage') args.coverage = true;
|
|
392
|
+
else if (a === '--run') args.run = (argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
393
|
+
else if (a === '--results') args.results = argv[++i];
|
|
394
|
+
else if (a === '--cases') args.cases = argv[++i];
|
|
395
|
+
else if (a === '--seed') args.seed = argv[++i];
|
|
396
|
+
else if (a === '--ir') args.ir = argv[++i];
|
|
397
|
+
else if (a === '--subject') args.subject = argv[++i];
|
|
398
|
+
else if (a === '--lens') args.lens = argv[++i];
|
|
399
|
+
else if (a === '--nodes') args.nodes = argv[++i];
|
|
400
|
+
else if (a === '--depth') args.depth = argv[++i];
|
|
401
|
+
else if (a === '--dir') args.dir = argv[++i];
|
|
402
|
+
else if (a === '--observed') args.observed = true;
|
|
403
|
+
else if (a === '--learning') args.learning = true;
|
|
404
|
+
else if (a === '--governed') args.governed = true;
|
|
405
|
+
else if (a === '--target') args.target = argv[++i];
|
|
406
|
+
else if (a === '--all-targets') args.allTargets = true;
|
|
407
|
+
else if (a === '--evidence') args.evidence = true;
|
|
408
|
+
else if (a === '--env') args.env = argv[++i];
|
|
409
|
+
else if (a === '--brief') args.brief = argv[++i];
|
|
410
|
+
else if (a === '--after') args.after = argv[++i];
|
|
411
|
+
else if (a === '--before') args.before = argv[++i];
|
|
412
|
+
else if (a === '--edits') args.edits = argv[++i];
|
|
413
|
+
else if (a === '--set-goal') args.setGoal = argv[++i];
|
|
414
|
+
else if (a === '--add-guarantee') (args.addGuarantee ||= []).push(argv[++i]);
|
|
415
|
+
else if (a === '--add-never') (args.addNever ||= []).push(argv[++i]);
|
|
416
|
+
else if (a === '--remove-guarantee') (args.removeGuarantee ||= []).push(argv[++i]);
|
|
417
|
+
else if (a === '--remove-never') (args.removeNever ||= []).push(argv[++i]);
|
|
418
|
+
else args._.push(a);
|
|
419
|
+
}
|
|
420
|
+
return args;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const writeJson = (dir, name, obj) => {
|
|
424
|
+
mkdirSync(dir, { recursive: true });
|
|
425
|
+
writeFileSync(join(dir, name), JSON.stringify(obj, null, 2) + '\n');
|
|
426
|
+
return join(dir, name);
|
|
427
|
+
};
|
|
428
|
+
const writeText = (dir, name, text) => {
|
|
429
|
+
mkdirSync(dir, { recursive: true });
|
|
430
|
+
writeFileSync(join(dir, name), text);
|
|
431
|
+
return join(dir, name);
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
// Persist an intent-ai-v1 event to the append-only sink at .intent/ai-events.jsonl.
|
|
435
|
+
// The durable audit trail RM / OpenThunder / Studio can replay. Returns the file path.
|
|
436
|
+
const AI_EVENT_LOG = 'ai-events.jsonl';
|
|
437
|
+
const sinkEvent = (root, event) => {
|
|
438
|
+
const dir = join(root, '.intent');
|
|
439
|
+
const path = join(dir, AI_EVENT_LOG);
|
|
440
|
+
const log = existsSync(path) ? parseEventLog(readFileSync(path, 'utf8')) : undefined;
|
|
441
|
+
mkdirSync(dir, { recursive: true });
|
|
442
|
+
writeFileSync(path, serializeEventLog(recordEvent(log, event)));
|
|
443
|
+
return path;
|
|
444
|
+
};
|
|
445
|
+
const readEventLog = (root) => {
|
|
446
|
+
const path = join(root, '.intent', AI_EVENT_LOG);
|
|
447
|
+
return existsSync(path) ? parseEventLog(readFileSync(path, 'utf8')) : parseEventLog('');
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
function load(file) {
|
|
451
|
+
const source = readFileSync(file, 'utf8');
|
|
452
|
+
const ast = parseIntent(source);
|
|
453
|
+
return { source, ast, sourceHash: sha256(source), sourceFile: basename(file) };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function printDiagnostics(diags) {
|
|
457
|
+
for (const d of diags) {
|
|
458
|
+
const tag = d.waived ? ' (WAIVED)' : '';
|
|
459
|
+
console.log(` [${d.level}]${tag} ${d.code}: ${d.message}`);
|
|
460
|
+
if (d.waived) console.log(` waived by: ${d.waiver.approvedBy} , ${d.waiver.reason}`);
|
|
461
|
+
else if (d.why) console.log(` why: ${d.why}`);
|
|
462
|
+
if (d.fix && d.fix.length) console.log(` fix: ${d.fix[0].label}`);
|
|
463
|
+
}
|
|
464
|
+
// A waived diagnostic is on the record but does not fail the build (governed exception).
|
|
465
|
+
const errors = diags.filter((d) => d.level === 'error' && !d.waived).length;
|
|
466
|
+
const warnings = diags.filter((d) => d.level === 'warning' && !d.waived).length;
|
|
467
|
+
const waived = diags.filter((d) => d.waived).length;
|
|
468
|
+
console.log(` ${errors} error(s), ${warnings} warning(s)${waived ? `, ${waived} waived` : ''}`);
|
|
469
|
+
return errors;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const HELP = `⚡ Thunder™: every command. Most people only need the first four groups.
|
|
473
|
+
|
|
474
|
+
usage: thunder <command> [file] [options] Help for one command: thunder help <command>
|
|
475
|
+
|
|
476
|
+
Start
|
|
477
|
+
doctor [--json] is this computer ready? Thunder, Node.js, Python, PATH, and optional toolchains (offline)
|
|
478
|
+
completion <zsh|bash|fish> a script that completes thunder commands when you press Tab
|
|
479
|
+
|
|
480
|
+
Write and run programs (Thunder Core, docs/core.md)
|
|
481
|
+
new <dir> create a Thunder Core project: thunder.toml, src/main.thunder, tests/
|
|
482
|
+
run | build | test | check | format in a project (a folder with thunder.toml), or on a .thunder file: a file
|
|
483
|
+
whose first line starts a mission is a mission, any other is a program (--core or
|
|
484
|
+
--mission says which). run/test need Python 3.10+, or add
|
|
485
|
+
--engine thunder to run them on the Thunder engine (no Python; programs that Use a
|
|
486
|
+
Python module are refused there). --target typescript compiles to TypeScript instead
|
|
487
|
+
(generated/typescript/; runs on Node 22.6+, or with the typescript package);
|
|
488
|
+
--target csharp compiles to C# (generated/csharp/; builds and runs with the .NET 8+ SDK)
|
|
489
|
+
--target go compiles to Go (generated/go/; needs the go toolchain to run)
|
|
490
|
+
--target java compiles to Java (generated/java/; runs with a JDK 17+)
|
|
491
|
+
|
|
492
|
+
Read and understand code
|
|
493
|
+
read <file|dir> [--search q] [--kind decision,function,error,test] [--in <lang>] [--from <lang>] [--json]
|
|
494
|
+
read <file|dir> --level big-picture|flow|details|text|original [--focus "<action or rule>"] [--json]
|
|
495
|
+
read at one depth, from the same model OpenThunder shows: the big picture, one action's flow,
|
|
496
|
+
its exact details, its Thunder Text, or the original lines
|
|
497
|
+
read <dir> --access which web routes limit a record chosen by the request to the caller (TypeScript/JavaScript)
|
|
498
|
+
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
|
|
499
|
+
for a folder also: [--answer <Outcome>] [--input <name>] [--lang go,rust] [--path <prefix>] [--limit n]
|
|
500
|
+
--promote <decision> [--out <file>] turn a recovered decision into a contract with starter examples
|
|
501
|
+
read code you don't know: its decision rules as ThunderLang + plain English,
|
|
502
|
+
optionally rewritten in a language you know (--in typescript|python|go|rust|csharp|java)
|
|
503
|
+
replay <recording.json> [--step n] [--json] the Time Machine: step through a run recorded with thunder run --record
|
|
504
|
+
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)
|
|
505
|
+
why <run.json> [--step n] [--json] what an AI agent did and why it stopped, in plain words, from its OpenTelemetry record
|
|
506
|
+
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)
|
|
507
|
+
review <base-ref> [head-ref] [--format markdown|json] [--paths <glob,...>] [--out <file>]
|
|
508
|
+
review in Thunder: what changed in meaning between two git commits (head: the working tree
|
|
509
|
+
when omitted), as Markdown for a pull request comment; read from git, no network
|
|
510
|
+
trace <folder…> [--json] [--out f] Thunder Trace: routes, events, tables, and packages linked across repositories, cited repo@sha:file:line
|
|
511
|
+
trace impact <thing | --diff [--base ref]> <folder…> what a change can affect in other repositories (one hop, ranked by risk)
|
|
512
|
+
passport <folder…> [--base ref] [--run "part: cmd"…] [--purpose …] an evidence record: behavior, links, effects, evidence with its limits, what is not verified
|
|
513
|
+
passport check <passport.json> which of its claims are still about the code as it is now (current or stale)
|
|
514
|
+
repo <owner/repo | github url | folder> [--json] [--max-files n] Thunder a whole repository (read-only; nothing is executed)
|
|
515
|
+
thunderize <folder | owner/repo> [--out <dir>] [--json] the whole app in Thunder Text: one .thunder-text per file + APP.thunder-text
|
|
516
|
+
|
|
517
|
+
Change code
|
|
518
|
+
write <file> --edit '<json>' [--edit …] | --edits <list.json|-> [--also <file>] [--apply] [--test "<cmd>"] [--candidate <file>] [--json]
|
|
519
|
+
Writing in Thunder: change a step, question, Stop, input, or function in Thunder; the code is
|
|
520
|
+
written as a minimal patch (TS/JS, Python, Go) and proven (the edited steps mean exactly
|
|
521
|
+
the edit; everything else means the same). Conditions and values in Thunder's words
|
|
522
|
+
("amount is at least 100", "name is nothing") or as code; steps by their line in thunder read.
|
|
523
|
+
Dry run by default; --apply saves; --test runs a command on the changed code. Other cases
|
|
524
|
+
print an instruction for an AI coding agent; --candidate checks code it wrote (AI-written).
|
|
525
|
+
write <file> --decision <name> --rule <n|otherwise> [--when "<condition>"] [--answer <Outcome>] [--write] [--json]
|
|
526
|
+
Thunder write: change a number, comparison, text value, or answer in a recovered rule;
|
|
527
|
+
previews the exact code change and the cases whose answer changes; --write saves it
|
|
528
|
+
write <folder…> --decision <name> --rule <n> --when "<condition>" [--write] [--run "part: cmd"] [--passport f.json]
|
|
529
|
+
one rule change in every service that implements it (TypeScript, C#, Python…):
|
|
530
|
+
the plan first; --write changes all of them or none; tests and a passport as proof
|
|
531
|
+
|
|
532
|
+
────────────────────────────────────────────────────────────────────────
|
|
533
|
+
Advanced: rules and missions (ThunderLang™ intent files), proofs, and tools for editors and CI.
|
|
534
|
+
The flow: author intent, inspect it, run and prove it, then keep real code aligned with it.
|
|
535
|
+
thunder mission <Name> <command> run any command on a mission by name
|
|
536
|
+
|
|
537
|
+
Author
|
|
538
|
+
init [Name] scaffold a runnable starter mission (Name.thunder) [alias: new --mission Name]
|
|
539
|
+
mission <Name> [cmd] resolve a mission by name and run a command on it (list | <Name> | <Name> <cmd>)
|
|
540
|
+
draft --brief <json|-> scaffold a rigorous intent draft + gap checklist from a brief
|
|
541
|
+
edit <file> [--edits <json|->] [--set-goal ..] [--add-guarantee ..] [--write] structural edits, comments kept
|
|
542
|
+
fmt <file|dir> [--write|--check] canonical formatting (whitespace only; comments kept)
|
|
543
|
+
source <file|graph.json> regenerate .thunder from a persisted graph
|
|
544
|
+
|
|
545
|
+
Inspect
|
|
546
|
+
check <file|dir> [--json|--format sarif] parse + lint + explainable diagnostics; gate a whole dir
|
|
547
|
+
report [dir] [--json] repo-wide intent health: severity + area counts, coverage
|
|
548
|
+
risks | gaps | unverified | coverage | unknowns | contradictions [dir] [--json] focused scan queries
|
|
549
|
+
focus <mission|query|--nodes a,b> [--depth N] [--dir <d>] [--json] Intent Lens: focused graph + brief
|
|
550
|
+
comprehension <file|dir> [--observed] [--learning] [--governed] [--json] the C0..C7 understanding level
|
|
551
|
+
twelve-factor <file> [--json] score against the 13 humanlayer/12-factor-agents principles [alias: 12factor]
|
|
552
|
+
explain <IL-CODE> explain a diagnostic code (area, severity, what it blocks)
|
|
553
|
+
rules [--json] list the whole canonical diagnostic catalog
|
|
554
|
+
notes <file> [--lens <lens>] [--json] ThunderLens: the compiled note blocks by lens (not verification)
|
|
555
|
+
docs <file> [--lens <lens>] [--out <dir>] render a mission as Markdown docs (per-audience with --lens)
|
|
556
|
+
index <dir> the Mission Atlas inventory
|
|
557
|
+
atlas <dir> [--search q | --expand id] the whole-system Atlas
|
|
558
|
+
atlas <dir> --review [--json | --agent-brief] [--openthunder report.json] [--strict]
|
|
559
|
+
execute contract cases, rank review gaps, compare OpenThunder snapshots
|
|
560
|
+
|
|
561
|
+
Run & test
|
|
562
|
+
run <file> --inputs '<json>' execute the decision(s) deterministically
|
|
563
|
+
test <file> [--contracts | --properties | --scenarios | --mutate | --evals | --changed | --coverage] [--strict]
|
|
564
|
+
test <file> --target typescript|python|csharp|java|go|rust|kotlin|scala|elixir run the tests against the EXECUTED generated code
|
|
565
|
+
test <file> --all-targets run the tests against every AVAILABLE target in one pass
|
|
566
|
+
simulate <file> --events a,b,c walk the lifecycle(s) over events
|
|
567
|
+
outcomes <file> evaluate outcome contracts vs delivery results
|
|
568
|
+
style <file> resolve style intents vs the canonical token space
|
|
569
|
+
gen <file> [--target typescript|csharp|java|python] [--out <dir>] deterministic code scaffold (types + decision logic + TODOs)
|
|
570
|
+
build <file> generate docs, contract graph, test plan, and .thunder-proof.json
|
|
571
|
+
|
|
572
|
+
Prove & verify intent
|
|
573
|
+
prove <file> emit an intent-proof-v1 artifact (honest verdicts + freshness)
|
|
574
|
+
proof <file> the .thunder-proof.json artifact (see also: prove, which emits verdicts)
|
|
575
|
+
proof --schema emit the canonical proof envelope JSON Schema (intent-proof-v1)
|
|
576
|
+
verify <proof.json> [src] re-check a proof; reports STALE when impl/deps/compiler moved
|
|
577
|
+
verify --run <folder> [--lang python|js] [--pytest "<args>" | --tests <dir> | --command "<cmd>"]
|
|
578
|
+
proof by running: run the code, compare what happened with Thunder's flows;
|
|
579
|
+
marks matching readings executed, exits 1 if a run contradicts a reading
|
|
580
|
+
runtime <folder> [--traces <file|dir>] [--stack <file>] [--logs <file>] [--otlp <file>] [--member <name>] [--top n] [--json]
|
|
581
|
+
the running system: what happened when it ran, on Thunder's flows (counts per
|
|
582
|
+
question side, Stop, and ending; calls, failures, time); errors explained in Thunder
|
|
583
|
+
evidence <file> emit evidence-event-v1 JSON (tool_verified) for the shared proof spine
|
|
584
|
+
(also: prove/verify-diff/conform/drift accept --evidence to emit their own event)
|
|
585
|
+
conform <file> [--targets a,b] [--run typescript,python,csharp,java,go,rust,kotlin,scala,elixir | --all-targets] [--results <json>] conformance matrix across targets
|
|
586
|
+
|
|
587
|
+
Real code vs intent (drift)
|
|
588
|
+
lift <file> [--from <lang>] lift source code into inferred intent
|
|
589
|
+
drift <codeFile> --intent <file.intent> [--from <lang>] check intent vs code drift
|
|
590
|
+
approve <file> --by <name> approve intent (drift baseline)
|
|
591
|
+
verify-diff <intent> --after <code> [--before <code>] gate a code change against its intent
|
|
592
|
+
changes [<base>..<head> | <base>] [--json] Change Lens: what a branch/PR changed by meaning
|
|
593
|
+
guardian <before> <after> drift: what changed, what risk, what to reverify, what learning is stale
|
|
594
|
+
impact <base> <proposed> Simulator: estimate a change's blast radius + risk BEFORE building it
|
|
595
|
+
diff <before> <after> semantic diff (by meaning)
|
|
596
|
+
merge <base> <ours> <theirs> deterministic 3-way semantic merge
|
|
597
|
+
handoff <file> the OpenThunder drift handoff
|
|
598
|
+
ledger <file.json> [--subject <id>] verify the tamper-evident history + explain why/who/what changed
|
|
599
|
+
guard <file> [--json] preview the runtime guard (redacted fields, enforced decisions)
|
|
600
|
+
|
|
601
|
+
Graph & IR
|
|
602
|
+
human <file> [--json | --format source] experimental compact authoring and a decision reading view
|
|
603
|
+
--version print the Thunder compiler version
|
|
604
|
+
anchor <file> [--json] show every Thunder step with its exact place in the file, and line coverage
|
|
605
|
+
text <file> [--json | --format source] experimental Thunder Text rule (.thunder-plain): run its examples [alias: plain]
|
|
606
|
+
graph <file> [--safe] the canonical Intent Graph (intent-graph-v1); --safe = display-safe on stdout
|
|
607
|
+
migrate <graph.json> [--to <version>] upgrade a persisted graph
|
|
608
|
+
validate <graph.json> [--json] check a graph is canonical (anti-fork)
|
|
609
|
+
schema emit the canonical graph schema + diagnostic catalog
|
|
610
|
+
|
|
611
|
+
Interop
|
|
612
|
+
export <file> --format <dmn|bpmn|smv|jsonschema|openapi|tokens|mermaid|css|playwright> render to a standard format
|
|
613
|
+
import <file> [--format dmn|bpmn] [--json] lift DMN/BPMN into intent
|
|
614
|
+
|
|
615
|
+
Fix
|
|
616
|
+
scan [dir] [--json] [--ir <path>] Scanner: intent -> Intent IR -> Fable findings -> risk themes
|
|
617
|
+
code-actions <file> [--json] available quick-fixes, safety-graded (safe | reviewable)
|
|
618
|
+
apply-fix <file> [--write] apply the SAFE autocorrects (header aliases, stray colons)
|
|
619
|
+
|
|
620
|
+
Servers
|
|
621
|
+
lsp start the Language Server (LSP over stdio, for editors)
|
|
622
|
+
mcp start the MCP server (for AI coding agents; stdio)
|
|
623
|
+
|
|
624
|
+
Common options: --out <dir>, --json, --no-ai. See https://thunderlang.dev/docs`;
|
|
625
|
+
|
|
626
|
+
function main() {
|
|
627
|
+
const [cmd, ...restArgv] = process.argv.slice(2);
|
|
628
|
+
const args = parseArgs(restArgv);
|
|
629
|
+
const file = args._[0];
|
|
630
|
+
if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
|
|
631
|
+
console.log(`thunder ${COMPILER_VERSION} (the Thunder™ compiler, also called ThunderLang™)`);
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
const known = [...new Set([...knownCommands(HELP), ...Object.keys(VIEWS)])].sort();
|
|
635
|
+
if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
636
|
+
// `thunder help <command>`: just that command's lines from the full list.
|
|
637
|
+
const topic = cmd === 'help' ? restArgv.find((x) => !x.startsWith('-')) : null;
|
|
638
|
+
if (topic) {
|
|
639
|
+
const h = helpFor(topic, HELP);
|
|
640
|
+
if (h) { console.log(`${paintHelp(h)}\n\n${paint('All commands: thunder help --all')}`); process.exitCode = 0; }
|
|
641
|
+
else { console.error(paint(unknownCommandText(topic, known), useColor(process.stderr))); process.exitCode = 2; }
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
// The short home screen first; every command with --all. Exit codes are unchanged (2 with no command at all).
|
|
645
|
+
// exitCode, not exit(): the full help is longer than a pipe's buffer, and exit() would cut it off when piped.
|
|
646
|
+
console.log(restArgv.includes('--all') ? paintHelp(HELP) : paint(homeText(COMPILER_VERSION, known.length)));
|
|
647
|
+
process.exitCode = cmd ? 0 : 2;
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
// thunder doctor: is this computer ready? Offline; changes nothing (src/cli-home.mjs).
|
|
651
|
+
if (cmd === 'completion') { process.exitCode = completionMain(restArgv, known); return; }
|
|
652
|
+
if (cmd === 'doctor') { process.exitCode = doctorMain(restArgv, { version: COMPILER_VERSION, cliPath: process.argv[1] }); return; }
|
|
653
|
+
// A command Thunder doesn't have (and not a file): say so, and suggest the closest ones, instead of failing later.
|
|
654
|
+
if (!known.includes(cmd) && !cmd.startsWith('-') && !existsSync(cmd)) { console.error(paint(unknownCommandText(cmd, known), useColor(process.stderr))); process.exitCode = 2; return; }
|
|
655
|
+
// Thunder Trace: links between repositories and what a change can affect (src/trace-cli.mjs).
|
|
656
|
+
if (cmd === 'trace') { process.exitCode = traceMain(restArgv); return; }
|
|
657
|
+
if (cmd === 'passport') { passportMain(restArgv).then((code) => { process.exitCode = code; }); return; }
|
|
658
|
+
// Thunder Why: an AI agent's run explained in plain words, from its OpenTelemetry record (src/why-cli.mjs).
|
|
659
|
+
if (cmd === 'why') { process.exitCode = whyMain(restArgv); return; }
|
|
660
|
+
// Thunder Try: try a rule from your code with your own values, and see the answer and why (src/try-cli.mjs).
|
|
661
|
+
if (cmd === 'try') { tryMain(restArgv).then((code) => { process.exitCode = code; }); return; }
|
|
662
|
+
// The Thunder Time Machine: step through a recording made with thunder run --record (src/replay-cli.mjs).
|
|
663
|
+
if (cmd === 'replay') { replayMain(restArgv).then((code) => { process.exitCode = code; }); return; }
|
|
664
|
+
// Thunder Core (programs you write and run): thunder new <dir>, and run/build/test/check/format inside a
|
|
665
|
+
// project with thunder.toml (or with --core). Mission files fall through unchanged. See src/core/cli.mjs.
|
|
666
|
+
const coreCode = coreMain(cmd, restArgv);
|
|
667
|
+
if (coreCode !== null) { process.exitCode = coreCode; return; }
|
|
668
|
+
if (cmd === 'read') {
|
|
669
|
+
try {
|
|
670
|
+
if (!file) throw new Error('Use thunder read <file> [--search q] [--kind decision,function,error,test] [--in <lang>] [--json].');
|
|
671
|
+
if (args.level != null) {
|
|
672
|
+
// The five reading levels, from the same model OpenThunder shows (src/read-level.mjs).
|
|
673
|
+
const ids = LEVELS.map((l) => l.id);
|
|
674
|
+
if (!ids.includes(args.level)) {
|
|
675
|
+
const near = nearestLevel(args.level);
|
|
676
|
+
throw new Error(`there is no level "${args.level}". The levels are: ${ids.join(', ')}.${near ? ` Did you mean --level ${near}?` : ''}`);
|
|
677
|
+
}
|
|
678
|
+
const isDir = statSync(file).isDirectory();
|
|
679
|
+
const files = isDir ? collectReadableFiles(file, { maxFiles: 5000, templates: true }).filter((f) => f.source) : [{ path: basename(file), source: readFileSync(file, 'utf8') }];
|
|
680
|
+
// One Angular component file: its templateUrl file is read with it, so the screen shows its template.
|
|
681
|
+
if (!isDir) for (const tu of files[0].source.matchAll(/templateUrl\s*:\s*['"`]([^'"`]+)['"`]/g)) { try { files.push({ path: tu[1].replace(/^\.\//, ''), source: readFileSync(join(dirname(file), tu[1]), 'utf8') }); } catch { /* not there: the screen says so */ } }
|
|
682
|
+
const model = thunderModel(files, { name: basename(resolve(file)) });
|
|
683
|
+
const focus = findFocus(model, args.focus);
|
|
684
|
+
if (focus.error) throw new Error(focus.error);
|
|
685
|
+
const r = readLevel(model, args.level, focus.id);
|
|
686
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
|
|
687
|
+
console.log(paint(renderLevel(r, { sources: Object.fromEntries(files.map((f) => [f.path, f.source])), file })));
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (args.access) {
|
|
691
|
+
// Ownership on web routes: the same accessFlow() the readings and OpenThunder use (docs/access-flow.md).
|
|
692
|
+
const isDir = statSync(file).isDirectory();
|
|
693
|
+
const files = isDir ? collectReadableFiles(file, { maxFiles: 20000 }).filter((f) => f.source) : [{ path: basename(file), source: readFileSync(file, 'utf8') }];
|
|
694
|
+
const report = accessFlow(files);
|
|
695
|
+
if (args.json) { console.log(JSON.stringify(report, null, 2)); return; }
|
|
696
|
+
console.log(paint(accessText(report)));
|
|
697
|
+
if (report.summary.unguarded) process.exitCode = 1;
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
if (statSync(file).isDirectory()) { readFolder(file, args); return; }
|
|
701
|
+
if (args.asCore) {
|
|
702
|
+
// Reading and writing are one language: the reader's meaning tree printed as Thunder Core (docs/core.md).
|
|
703
|
+
if (!/\.py$/i.test(file) && (args.from || 'python') !== 'python') throw new Error('--as-core reads Python for now (other languages next).');
|
|
704
|
+
const r = pythonToCore(readFileSync(file, 'utf8'));
|
|
705
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
|
|
706
|
+
console.log(paintThunder(r.core.trimEnd()));
|
|
707
|
+
const all = [...r.module.notTranslated, ...r.functions.flatMap((f) => f.notTranslated)];
|
|
708
|
+
const exact = r.functions.filter((f) => f.exact);
|
|
709
|
+
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)` : ''}.`);
|
|
710
|
+
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('; ')}`);
|
|
711
|
+
const assumes = r.functions.flatMap((f) => f.assumptions.map((a) => `${f.name}, line ${a.line}: ${a.says}`));
|
|
712
|
+
for (const a of assumes) console.error(` assumes: ${a}`);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (args.promote) {
|
|
716
|
+
const items = statSync(file).isDirectory()
|
|
717
|
+
? searchRepo(readRepo(collectReadableFiles(file)), { path: args.pathPrefix || '' })
|
|
718
|
+
: readCode(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) }).items.map((it) => ({ ...it, file: basename(file) }));
|
|
719
|
+
const matches = items.filter((it) => it.kind === 'decision' && it.name === args.promote);
|
|
720
|
+
if (!matches.length) throw new Error(`No decision named ${args.promote}. Run thunder read ${file} --kind decision to list them.`);
|
|
721
|
+
if (matches.length > 1) throw new Error(`${matches.length} decisions are named ${args.promote} (${matches.map((m) => m.file).join(', ')}). Narrow with --path.`);
|
|
722
|
+
const p = promoteDecision(matches[0]);
|
|
723
|
+
if (!p.ok) throw new Error(p.reason);
|
|
724
|
+
const report = previewHumanContract(p.source);
|
|
725
|
+
if (args.out) {
|
|
726
|
+
writeFileSync(args.out, p.source);
|
|
727
|
+
console.error(`Wrote ${args.out}: ${report.tests.total} examples recording what the code does today (${report.tests.passed} pass).`);
|
|
728
|
+
console.error(`Next: confirm each answer with a person, then: thunder human ${args.out} --format source > ${p.name}.thunder`);
|
|
729
|
+
} else process.stdout.write(p.source);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
const reading = readCode(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) });
|
|
733
|
+
const items = searchReading(reading, { query: args.search || '', kinds: args.kind || [] });
|
|
734
|
+
if (args.json) { console.log(JSON.stringify({ ...reading, items }, null, 2)); return; }
|
|
735
|
+
const c = reading.counts;
|
|
736
|
+
console.log(`${basename(file)} (${reading.language}${reading.detected ? ', detected' : ''}): ${c.decision} decision(s), ${c.function} other function(s), ${c.error} error(s), ${c.test} test(s). Inferred from code; confirm before relying on it.`);
|
|
737
|
+
if (!items.length) console.log('\nNothing matches. Try fewer words or remove --kind.');
|
|
738
|
+
for (const it of items) {
|
|
739
|
+
console.log(`\n[${it.kind}${it.status === 'partial' ? ', partly read' : ''}] ${it.name} (line ${it.line})`);
|
|
740
|
+
if (it.doc) console.log(` Author's note: "${it.doc}"`);
|
|
741
|
+
console.log(` ${it.says}`);
|
|
742
|
+
if (it.thunder) {
|
|
743
|
+
console.log('');
|
|
744
|
+
for (const l of it.thunder.split('\n')) console.log(` ${l}`);
|
|
745
|
+
if (args.inLang) {
|
|
746
|
+
const code = translateDecisions(parseIntent(it.thunder), args.inLang).split('\n').slice(2);
|
|
747
|
+
console.log(`\n In ${args.inLang}:`);
|
|
748
|
+
for (const l of code) console.log(` ${l}`);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
for (const u of it.unread || []) console.log(` not read (line ${u.line}): ${u.text} ${u.reason}`);
|
|
752
|
+
}
|
|
753
|
+
} catch (e) { console.error(`thunder read: ${e.message}`); process.exitCode = 2; }
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
// One rule change written into every service that implements it (src/write-across-cli.mjs).
|
|
757
|
+
if (cmd === 'write' && isWriteAcross(restArgv)) { writeAcrossMain(restArgv).then((code) => { process.exitCode = code; }); return; }
|
|
758
|
+
// thunder write <file> --edits <list.json | ->: the edits from a file (or stdin), the same JSON as --edit.
|
|
759
|
+
if (cmd === 'write' && args.edits && !args.edit) args.edit = [args.edits === '-' ? readFileSync(0, 'utf8') : readFileSync(args.edits, 'utf8')];
|
|
760
|
+
if (cmd === 'write' && args.edit) {
|
|
761
|
+
try {
|
|
762
|
+
if (!file) throw new Error('Use thunder write <file> --edit \'{"op":"setValue","member":"name","step":"line:12","to":10}\' [--apply] [--test "<cmd>"].');
|
|
763
|
+
const paths = [file, ...(args.also || [])];
|
|
764
|
+
const files = paths.map((p) => ({ path: p, source: readFileSync(p, 'utf8') }));
|
|
765
|
+
let edits;
|
|
766
|
+
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}`); }
|
|
767
|
+
const options = args.candidate ? { candidate: { [file]: readFileSync(args.candidate, 'utf8') } } : {};
|
|
768
|
+
const r = thunderWrite(files, edits, options);
|
|
769
|
+
// --test: run the command on the changed code (written to the files for the run, then put back unless --apply).
|
|
770
|
+
if (r.status === 'written' && args.test) {
|
|
771
|
+
const originals = new Map(files.map((f) => [f.path, f.source]));
|
|
772
|
+
for (const [p, src] of Object.entries(r.files)) writeFileSync(p, src);
|
|
773
|
+
const t0 = Date.now();
|
|
774
|
+
const run = spawnSync(args.test, { shell: true, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
775
|
+
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') };
|
|
776
|
+
if (!args.apply) for (const [p] of Object.entries(r.files)) writeFileSync(p, originals.get(p));
|
|
777
|
+
}
|
|
778
|
+
// --behaviour: run each edited Python function before and after on inputs made from its code (it runs the code).
|
|
779
|
+
if (r.status === 'written' && args.behaviour) {
|
|
780
|
+
const originals = new Map(files.map((f) => [f.path, f.source]));
|
|
781
|
+
const edited = (r.proof.edited.checks ?? []).filter((c) => c.file && r.files[c.file] != null);
|
|
782
|
+
r.proof.behaviour = edited.map((c) => behaviourCheck({ path: c.file, name: c.member, before: originals.get(c.file) ?? '', after: r.files[c.file] }));
|
|
783
|
+
if (!edited.length) r.proof.behaviour = [{ status: 'not-run', says: 'Behaviour not checked: this edit names no function to run.' }];
|
|
784
|
+
}
|
|
785
|
+
const broken = (r.proof?.behaviour ?? []).some((b) => b.status === 'broken');
|
|
786
|
+
if (broken && args.apply) for (const f of files) writeFileSync(f.path, f.source);
|
|
787
|
+
const applied = r.status === 'written' && args.apply && !broken && (!r.proof?.run || r.proof.run.passed);
|
|
788
|
+
if (applied && !args.test) for (const [p, src] of Object.entries(r.files)) writeFileSync(p, src);
|
|
789
|
+
if (r.status === 'written' && args.apply && r.proof?.run && !r.proof.run.passed) for (const f of files) writeFileSync(f.path, f.source);
|
|
790
|
+
if (args.json) { const { files: _f, ...rest } = r; console.log(JSON.stringify({ ...rest, applied }, null, 2)); if (r.status !== 'written') process.exitCode = 1; return; }
|
|
791
|
+
if (r.status === 'refused') { console.error(`Not changed. ${r.says}`); process.exitCode = 1; return; }
|
|
792
|
+
if (r.status === 'needs-ai') {
|
|
793
|
+
console.log(r.says);
|
|
794
|
+
console.log('\n--- Instruction for an AI coding agent (nothing was changed) ---\n');
|
|
795
|
+
console.log(r.prompt);
|
|
796
|
+
process.exitCode = 1;
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
if (r.before) { console.log('Thunder before:'); for (const l of r.before.split('\n')) console.log(` ${l}`); }
|
|
800
|
+
if (r.after) { console.log('Thunder after:'); for (const l of r.after.split('\n')) console.log(` ${l}`); }
|
|
801
|
+
console.log(`\n${r.author === 'ai' ? 'AI-written change (checked):' : 'Code change:'}\n`);
|
|
802
|
+
process.stdout.write(r.patch);
|
|
803
|
+
console.log('\nProof:');
|
|
804
|
+
for (const c of r.proof.edited.checks) console.log(` edited ${c.member}: ${c.result === 'exact' ? 'reads exactly as the edit says' : c.result}`);
|
|
805
|
+
const u = r.proof.unchanged;
|
|
806
|
+
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}`);
|
|
807
|
+
if (r.proof.run) console.log(` run ${r.proof.run.command}: ${r.proof.run.passed ? 'passed' : `failed (exit ${r.proof.run.exit})`}`);
|
|
808
|
+
if (r.proof.run && !r.proof.run.passed) console.log(r.proof.run.output);
|
|
809
|
+
for (const b of r.proof.behaviour ?? []) {
|
|
810
|
+
console.log(` behaviour ${b.function ?? ''}${b.function ? ': ' : ''}${b.status === 'changed' ? `${b.changes.length} of ${b.inputs} inputs give a different answer` : b.status === 'same' ? `all ${b.inputs} inputs give the same answer` : b.status === 'broken' ? `the changed file does not load (${b.reason})` : `not checked (${b.reason ?? b.says})`}`);
|
|
811
|
+
for (const ex of b.examples ?? []) console.log(` ${ex}`);
|
|
812
|
+
if (b.status === 'same' || b.status === 'changed') console.log(' (tested on these inputs only; not a proof)');
|
|
813
|
+
}
|
|
814
|
+
console.log(`\n${r.says}`);
|
|
815
|
+
console.log(applied ? `\nSaved ${Object.keys(r.files).join(', ')}.` : broken ? '\nNot saved: the changed file does not load.' : r.proof?.run && !r.proof.run.passed ? '\nNot saved: the test command failed.' : '\nDry run; nothing was saved. Add --apply to save the change.');
|
|
816
|
+
if ((r.proof?.run && !r.proof.run.passed) || broken) process.exitCode = 1;
|
|
817
|
+
} catch (e) { console.error(`thunder write: ${e.message}`); process.exitCode = 2; }
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
if (cmd === 'write') {
|
|
821
|
+
try {
|
|
822
|
+
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].');
|
|
823
|
+
const source = readFileSync(file, 'utf8');
|
|
824
|
+
const r = writeRule({ source, language: args.from, file: basename(file), decision: args.decision, rule: args.rule === 'otherwise' ? 'otherwise' : Number(args.rule), when: args.when ?? null, answer: args.answer ?? null });
|
|
825
|
+
if (r.ok && args.write) writeFileSync(file, r.source);
|
|
826
|
+
if (args.json) { const { source: _s, ...rest } = r; console.log(JSON.stringify({ ...rest, written: !!(r.ok && args.write) }, null, 2)); if (!r.ok) process.exitCode = 1; return; }
|
|
827
|
+
if (!r.ok) {
|
|
828
|
+
console.error(`Not changed. ${file} is untouched.`);
|
|
829
|
+
for (const p of r.problems) console.error(` ${p}`);
|
|
830
|
+
process.exitCode = 1;
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
console.log(`${r.decision}, rule ${r.rule}`);
|
|
834
|
+
console.log(` was: ${r.before}`);
|
|
835
|
+
console.log(` now: ${r.after}`);
|
|
836
|
+
console.log('\nCode change (only these characters):');
|
|
837
|
+
for (const c of r.change) console.log(` line ${c.line}, column ${c.column}: ${c.before} -> ${c.after}`);
|
|
838
|
+
console.log('\nChecked by reading the file again: this rule reads as intended; every other rule and function reads exactly as before.');
|
|
839
|
+
console.log(`\n${r.cases.note}`);
|
|
840
|
+
const names = r.cases.changed[0] ? Object.keys(r.cases.changed[0].inputs) : [];
|
|
841
|
+
for (const c of r.cases.changed.slice(0, 8)) console.log(` ${names.map((n) => `${n} ${JSON.stringify(c.inputs[n])}`).join(', ')}: ${c.before} -> ${c.after}`);
|
|
842
|
+
if (r.cases.changed.length > 8) console.log(` ...and ${r.cases.changed.length - 8} more (use --json for all).`);
|
|
843
|
+
console.log(args.write ? `\nSaved ${file}. Run your tests before you commit.` : '\nPreview only; nothing was saved. Add --write to save the change.');
|
|
844
|
+
} catch (e) { console.error(`thunder write: ${e.message}`); process.exitCode = 2; }
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
if (cmd === 'anchor') {
|
|
848
|
+
try {
|
|
849
|
+
if (!file) throw new Error('Use thunder anchor <file> [--json].');
|
|
850
|
+
const r = anchorReport(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) });
|
|
851
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
|
|
852
|
+
console.log(`${basename(file)} (${r.language}): ${Math.round(r.coverage * 1000) / 10}% of code lines are anchored to a Thunder step.`);
|
|
853
|
+
for (const f of r.functions) {
|
|
854
|
+
console.log(`\n${f.name} (line ${f.line}) ${Math.round(f.coverage * 100)}% anchored${f.missing.length ? `; not yet anchored: line ${f.missing.join(', ')}` : ''}`);
|
|
855
|
+
for (const s of f.steps) console.log(` ${s.path.padEnd(5)} ${s.span.startLine === s.span.endLine ? `L${s.span.startLine}` : `L${s.span.startLine}-${s.span.endLine}`}`.padEnd(18) + `${s.kind.padEnd(7)} ${s.says}`);
|
|
856
|
+
}
|
|
857
|
+
} catch (e) { console.error(`thunder anchor: ${e.message}`); process.exitCode = 2; }
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
if (cmd === 'repo') {
|
|
861
|
+
try {
|
|
862
|
+
if (!file) throw new Error('Use thunder repo <owner/repo | https://github.com/owner/repo | folder> [--json].');
|
|
863
|
+
const report = thunderRepo(file, { maxFiles: args.maxFiles ? Number(args.maxFiles) : undefined });
|
|
864
|
+
console.log(args.json ? JSON.stringify(report, null, 2) : renderThunderRepo(report));
|
|
865
|
+
process.exitCode = report.errors.length ? 1 : 0;
|
|
866
|
+
} catch (e) { console.error(`thunder repo: ${e.message}`); process.exitCode = 2; }
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
if (cmd === 'thunderize') {
|
|
870
|
+
let cleanup = () => {};
|
|
871
|
+
try {
|
|
872
|
+
if (!file) throw new Error('Use thunder thunderize <folder | owner/repo> [--out <dir>] [--json].');
|
|
873
|
+
let root = file, name = basename(resolve(file));
|
|
874
|
+
const gh = !existsSync(file) && parseGitHub(file);
|
|
875
|
+
if (gh) { const c = cloneGitHub(gh); root = c.root; cleanup = c.cleanup; name = `${gh.owner}/${gh.repo}`; }
|
|
876
|
+
else if (!existsSync(file) || !statSync(file).isDirectory()) throw new Error(`${file} is not a folder or a GitHub repository.`);
|
|
877
|
+
const app = thunderizeFiles(collectReadableFiles(root), { name });
|
|
878
|
+
if (args.out) {
|
|
879
|
+
for (const f of app.files) { const dest = join(args.out, f.out); mkdirSync(dirname(dest), { recursive: true }); writeFileSync(dest, f.text); }
|
|
880
|
+
mkdirSync(args.out, { recursive: true });
|
|
881
|
+
writeFileSync(join(args.out, `APP${THUNDER_TEXT_EXT}`), app.index);
|
|
882
|
+
}
|
|
883
|
+
if (args.json) console.log(JSON.stringify(app, null, 2));
|
|
884
|
+
else {
|
|
885
|
+
process.stdout.write(app.index);
|
|
886
|
+
if (args.out) console.log(`\nWrote ${app.files.length + 1} Thunder Text files to ${args.out} (start with APP${THUNDER_TEXT_EXT}).`);
|
|
887
|
+
else console.log(`\nAdd --out <dir> to write every file's Thunder Text.`);
|
|
888
|
+
}
|
|
889
|
+
} catch (e) { console.error(`thunder thunderize: ${e.message}`); process.exitCode = 2; }
|
|
890
|
+
finally { cleanup(); }
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
if (cmd === 'review') {
|
|
894
|
+
try {
|
|
895
|
+
const base = args.base ?? args._[0], head = args.head ?? (args.base ? null : args._[1]);
|
|
896
|
+
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.');
|
|
897
|
+
if (args.format && !['markdown', 'json'].includes(args.format)) throw new Error(`--format ${args.format} is not one of markdown, json.`);
|
|
898
|
+
const json = args.json || args.format === 'json';
|
|
899
|
+
const r = reviewGit(base, head ?? null, args.paths ?? []);
|
|
900
|
+
const text = json ? JSON.stringify(r, null, 2) : renderReview(r, { footer: `<sub>\`thunder review ${base}${head ? ` ${head}` : ''}\` · Thunder compiler ${COMPILER_VERSION}</sub>` }).trimEnd();
|
|
901
|
+
if (args.outExplicit) { mkdirSync(dirname(resolve(args.out)), { recursive: true }); writeFileSync(args.out, `${text}\n`); console.log(`thunder review: ${r.says} Wrote ${args.out}.`); }
|
|
902
|
+
else console.log(text);
|
|
903
|
+
} catch (e) { console.error(`thunder review: ${e.message}`); process.exitCode = 2; }
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
if (cmd === 'same') {
|
|
907
|
+
try {
|
|
908
|
+
const [a, b] = args._;
|
|
909
|
+
if (!a || !b) throw new Error('Use thunder same <old> <new> [--json]. Each can be a file or a folder, in any language Thunder reads.');
|
|
910
|
+
const load = (p) => {
|
|
911
|
+
if (!existsSync(p)) throw new Error(`${p} does not exist.`);
|
|
912
|
+
return statSync(p).isDirectory() ? collectReadableFiles(p) : [{ path: basename(p), source: readFileSync(p, 'utf8') }];
|
|
913
|
+
};
|
|
914
|
+
const r = sameMeaning(load(a), load(b));
|
|
915
|
+
console.log(args.json ? JSON.stringify(r, null, 2) : renderSame(r).trimEnd());
|
|
916
|
+
process.exitCode = r.verdict === 'same' ? 0 : 1;
|
|
917
|
+
} catch (e) { console.error(`thunder same: ${e.message}`); process.exitCode = 2; }
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if (cmd === 'plain' || cmd === 'text') {
|
|
921
|
+
try {
|
|
922
|
+
if (!file) throw new Error('Use thunder plain <file> [--json | --format source].');
|
|
923
|
+
if (args.format && args.format !== 'source') throw new Error('The supported format is source; omit --format to run the examples.');
|
|
924
|
+
const report = previewPlainContract(readFileSync(file, 'utf8'));
|
|
925
|
+
if (args.json) console.log(JSON.stringify(report, null, 2));
|
|
926
|
+
else if (args.format === 'source') process.stdout.write(report.canonicalSource);
|
|
927
|
+
else {
|
|
928
|
+
console.log(`${report.model.title}: ${report.tests.passed} of ${report.tests.total} examples pass. Application: not checked.`);
|
|
929
|
+
for (const r of report.tests.results) if (!r.pass) console.log(` failed: ${r.name}: expected ${r.expected}, got ${r.actual}`);
|
|
930
|
+
}
|
|
931
|
+
process.exitCode = report.tests.failed ? 1 : 0;
|
|
932
|
+
} catch (e) { console.error(`thunder plain: ${e.message}`); process.exitCode = 2; }
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
if (cmd === 'human') {
|
|
936
|
+
try {
|
|
937
|
+
if (!file) throw new Error('Use thunder human <file> [--json | --format source].');
|
|
938
|
+
if (args.format && args.format !== 'source') throw new Error('The supported format is source; omit --format for the reading view.');
|
|
939
|
+
const report = previewHumanContract(readFileSync(file, 'utf8'));
|
|
940
|
+
if (args.json) console.log(JSON.stringify(report, null, 2));
|
|
941
|
+
else if (args.format === 'source') process.stdout.write(report.canonicalSource);
|
|
942
|
+
else console.log(renderHumanContract(report));
|
|
943
|
+
process.exitCode = report.tests.failed ? 1 : report.tests.total ? 0 : 2;
|
|
944
|
+
} catch (e) { console.error(`thunder human: ${e.message}`); process.exitCode = 2; }
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
// `schema` takes no file (it emits the canonical Intent Graph schema).
|
|
948
|
+
if (cmd === 'schema') {
|
|
949
|
+
const out = {
|
|
950
|
+
schemaVersion: SCHEMA_VERSION, nodeTypes: NODE_TYPES, relationshipTypes: RELATIONSHIP_TYPES,
|
|
951
|
+
classifications: CLASSIFICATIONS, diagnostics: DIAGNOSTIC_RULES, jsonSchema: intentGraphJsonSchema(),
|
|
952
|
+
};
|
|
953
|
+
if (args.out && args.out !== '.intent') { const p = writeJson(args.out, 'intent-graph.schema.json', out); console.log(`wrote ${p.replace(process.cwd() + '/', '')}`); }
|
|
954
|
+
else console.log(JSON.stringify(out, null, 2));
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
// `thunder proof --schema` emits the canonical proof envelope JSON Schema (no file needed).
|
|
958
|
+
// This is the "shared envelope" schema siblings sign (STW) and re-verify (RM/OT) against.
|
|
959
|
+
if (cmd === 'proof' && args.schema) {
|
|
960
|
+
console.log(JSON.stringify(intentProofJsonSchema(), null, 2));
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
// `thunder verify --run <folder>`: proof by running. Runs the code (its tests, and made-up inputs for functions that
|
|
964
|
+
// look free of side effects), records which side of each question it took and how each call ended, and compares
|
|
965
|
+
// that with the flow Thunder drew. Exit 1 when a run contradicts any reading.
|
|
966
|
+
if (cmd === 'verify' && restArgv.includes('--run')) {
|
|
967
|
+
const opt = (name) => { const i = restArgv.indexOf(name); return i >= 0 ? restArgv[i + 1] : undefined; };
|
|
968
|
+
const folder = opt('--run');
|
|
969
|
+
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; }
|
|
970
|
+
let res;
|
|
971
|
+
try {
|
|
972
|
+
res = verifyRun(folder, { lang: opt('--lang'), pytest: opt('--pytest'), tests: opt('--tests'), command: opt('--command'), cwd: opt('--cwd'), python: opt('--python'), trace: opt('--trace'),
|
|
973
|
+
maxSeconds: opt('--max-seconds') ? Number(opt('--max-seconds')) : undefined, generate: !restArgv.includes('--no-generate') });
|
|
974
|
+
} catch (e) { console.error(`thunder verify --run: ${e.message}`); process.exit(2); return; }
|
|
975
|
+
if (opt('--save-trace')) writeFileSync(opt('--save-trace'), JSON.stringify(res.trace));
|
|
976
|
+
if (restArgv.includes('--json')) console.log(JSON.stringify(res.result, null, 2));
|
|
977
|
+
else console.log(`thunder verify --run ${folder} (${res.result.language})\n${executedText(res.result, { all: restArgv.includes('--all') })}`);
|
|
978
|
+
if (res.result.summary.contradicted) process.exitCode = 1;
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
// `thunder runtime <folder>`: the running system. Places recorded runs (thunder verify --run --save-trace), stack
|
|
982
|
+
// traces, structured logs, and OpenTelemetry spans on the folder's flows, and explains each error in Thunder.
|
|
983
|
+
if (cmd === 'runtime') {
|
|
984
|
+
const opt = (name) => { const i = restArgv.indexOf(name); return i >= 0 ? restArgv[i + 1] : undefined; };
|
|
985
|
+
const folder = restArgv[0];
|
|
986
|
+
const usage = 'usage: thunder runtime <folder> [--traces <file|dir>] [--stack <file>] [--logs <file>] [--otlp <file>] [--member <name>] [--top <n>] [--json]';
|
|
987
|
+
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; }
|
|
988
|
+
const evidence = [];
|
|
989
|
+
const stacks = [];
|
|
990
|
+
try {
|
|
991
|
+
const traces = opt('--traces');
|
|
992
|
+
if (traces) {
|
|
993
|
+
const t = { files: {}, runs: [] };
|
|
994
|
+
const list = statSync(traces).isDirectory() ? readdirSync(traces).filter((n) => n.endsWith('.json')).map((n) => join(traces, n)) : [traces];
|
|
995
|
+
for (const f of list) mergeTraces(t, JSON.parse(readFileSync(f, 'utf8')));
|
|
996
|
+
evidence.push(...fromTrace(t));
|
|
997
|
+
}
|
|
998
|
+
if (opt('--stack')) { const text = readFileSync(opt('--stack'), 'utf8'); evidence.push(...fromStack(text)); stacks.push(...parseStacks(text)); }
|
|
999
|
+
if (opt('--logs')) evidence.push(...fromLogs(readFileSync(opt('--logs'), 'utf8')));
|
|
1000
|
+
if (opt('--otlp')) evidence.push(...fromOtlp(readFileSync(opt('--otlp'), 'utf8')));
|
|
1001
|
+
} catch (e) { console.error(`thunder runtime: ${e.message}`); process.exit(2); return; }
|
|
1002
|
+
if (!evidence.length) { console.error(`thunder runtime: no evidence given.\n${usage}`); process.exit(2); return; }
|
|
1003
|
+
const model = thunderModel(collectReadableFiles(folder, { maxFiles: 5000, templates: true }).filter((f) => f.source), { name: basename(resolve(folder)) });
|
|
1004
|
+
const overlay = runtimeOverlay(model, evidence);
|
|
1005
|
+
const explained = stacks.map((s) => explainError(model, s));
|
|
1006
|
+
if (restArgv.includes('--json')) { console.log(JSON.stringify({ ...overlay, errors: explained }, null, 2)); return; }
|
|
1007
|
+
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)`, ''];
|
|
1008
|
+
if (explained.length) { out.push('Errors, explained in Thunder:'); for (const x of explained) out.push(` - ${x.text}`); out.push(''); }
|
|
1009
|
+
out.push(runtimeText(model, overlay, { member: opt('--member') ?? null, top: opt('--top') ? Number(opt('--top')) : 10 }));
|
|
1010
|
+
process.stdout.write(`${out.join('\n').replace(/\n+$/, '')}\n`);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
// Verify a .thunder-proof.json against its source: the source hash still matches (no
|
|
1014
|
+
// drift / tampering) and the proof's claims re-derive from the source.
|
|
1015
|
+
if (cmd === 'verify') {
|
|
1016
|
+
const proofPath = args._[0];
|
|
1017
|
+
if (!proofPath) { console.error('usage: thunder verify <proof.json> [<source.intent>]'); process.exit(2); return; }
|
|
1018
|
+
let proof;
|
|
1019
|
+
try { proof = JSON.parse(readFileSync(proofPath, 'utf8')); } catch { console.error('thunder verify: proof is not valid JSON'); process.exit(2); return; }
|
|
1020
|
+
const srcPath = args._[1] || proof.sourceFile;
|
|
1021
|
+
if (!srcPath || !existsSync(srcPath)) { console.error(`thunder verify: source not found (${srcPath || 'none'}). Pass it: thunder verify <proof.json> <source.intent>`); process.exit(2); return; }
|
|
1022
|
+
const src = readFileSync(srcPath, 'utf8');
|
|
1023
|
+
const ast = parseIntent(src);
|
|
1024
|
+
const diags = semanticDiagnostics(ast);
|
|
1025
|
+
const hashMatch = sha256(src) === proof.sourceHash;
|
|
1026
|
+
const semanticNow = !diags.some((d) => d.level === 'error');
|
|
1027
|
+
const semanticMatch = proof.verification ? semanticNow === !!proof.verification.semanticPassed : true;
|
|
1028
|
+
const guaranteesMatch = !Array.isArray(proof.guarantees) || proof.guarantees.length === (ast.guarantees || []).length;
|
|
1029
|
+
const neverMatch = !Array.isArray(proof.neverRules) || proof.neverRules.length === (ast.neverRules || []).length;
|
|
1030
|
+
// Structural gate: the envelope must be a well-formed intent-proof-v1 document first.
|
|
1031
|
+
const structure = validateProof(proof);
|
|
1032
|
+
const valid = structure.valid && hashMatch && semanticMatch && guaranteesMatch && neverMatch;
|
|
1033
|
+
// Freshness: even if the intent still matches, the proof is STALE if the implementation,
|
|
1034
|
+
// dependencies, or compiler moved since it was generated. A stale proof must not read green.
|
|
1035
|
+
const staleReasons = valid ? stalenessReasons(proof.freshness, dirname(srcPath) || '.') : [];
|
|
1036
|
+
const stale = staleReasons.length > 0;
|
|
1037
|
+
const status = !valid ? 'FAILED' : stale ? 'STALE' : 'VALID';
|
|
1038
|
+
const result = { schema: 'intent-verify-v1', proof: proofPath, source: srcPath, valid, stale, status, staleReasons, checks: { wellFormed: structure.valid, hashMatch, semanticMatch, guaranteesMatch, neverMatch }, structureErrors: structure.errors };
|
|
1039
|
+
if (args.json) { console.log(JSON.stringify(result, null, 2)); process.exit(valid && !stale ? 0 : 1); return; }
|
|
1040
|
+
console.log(`thunder verify ${basename(proofPath)}: ${status} (source ${basename(srcPath)})`);
|
|
1041
|
+
if (!structure.valid) { console.log(` X proof is not a well-formed intent-proof-v1 document:`); for (const e of structure.errors) console.log(` ${e.path || '(root)'}: ${e.message}`); }
|
|
1042
|
+
if (!hashMatch) console.log(' X source hash does not match , the source has changed since the proof was generated (drift or tampering).');
|
|
1043
|
+
if (!semanticMatch) console.log(' X the proof claims a different semantic result than the source produces now.');
|
|
1044
|
+
if (!guaranteesMatch) console.log(' X guarantee count differs from the proof.');
|
|
1045
|
+
if (!neverMatch) console.log(' X never-rule count differs from the proof.');
|
|
1046
|
+
if (stale) { console.log(' ! proof is STALE , the intent still matches, but the world moved since it was generated:'); for (const r of staleReasons) console.log(` ${r}`); console.log(' regenerate: thunder prove ' + basename(srcPath)); }
|
|
1047
|
+
if (valid && !stale) console.log(` ok proof matches source and is fresh (hash + ${(proof.guarantees || []).length} guarantee(s), ${(proof.neverRules || []).length} never-rule(s)).`);
|
|
1048
|
+
process.exit(valid && !stale ? 0 : 1);
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// Explain a diagnostic code from the canonical catalog. `thunder explain IL-DEC-001`.
|
|
1053
|
+
if (cmd === 'explain') {
|
|
1054
|
+
const code = file;
|
|
1055
|
+
if (!code) { console.error('usage: thunder explain <IL-CODE>'); process.exit(2); return; }
|
|
1056
|
+
const rule = ALL_DIAGNOSTICS.find((r) => r.ruleId.toLowerCase() === code.toLowerCase());
|
|
1057
|
+
if (args.json) { console.log(JSON.stringify(rule || { ruleId: code, found: false }, null, 2)); process.exit(rule ? 0 : 1); return; }
|
|
1058
|
+
if (!rule) { console.error(`thunder explain: "${code}" is not in the diagnostic catalog. Run "intent rules" for the full list.`); process.exit(1); return; }
|
|
1059
|
+
console.log(`${rule.ruleId} (area: ${rule.area})`);
|
|
1060
|
+
console.log(` ${rule.summary}`);
|
|
1061
|
+
console.log(` severity: ${rule.severity}${rule.blocks && rule.blocks.length ? ` | blocks: ${rule.blocks.join(', ')}` : ' | does not block a phase'}`);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// The whole canonical diagnostic catalog (IL owns it; editors/CI/OT consume it).
|
|
1066
|
+
if (cmd === 'rules') {
|
|
1067
|
+
if (args.json) { console.log(JSON.stringify(ALL_DIAGNOSTICS, null, 2)); return; }
|
|
1068
|
+
const byArea = {};
|
|
1069
|
+
for (const r of ALL_DIAGNOSTICS) (byArea[r.area] ||= []).push(r);
|
|
1070
|
+
console.log(`thunder rules: ${ALL_DIAGNOSTICS.length} diagnostics in ${Object.keys(byArea).length} areas\n`);
|
|
1071
|
+
for (const area of Object.keys(byArea).sort()) {
|
|
1072
|
+
console.log(`${area}`);
|
|
1073
|
+
for (const r of byArea[area]) {
|
|
1074
|
+
const blocks = r.blocks && r.blocks.length ? `blocks ${r.blocks.join(', ')}` : 'non-blocking';
|
|
1075
|
+
console.log(` ${r.ruleId.padEnd(16)} [${r.severity}, ${blocks}] ${r.summary}`);
|
|
1076
|
+
}
|
|
1077
|
+
console.log();
|
|
1078
|
+
}
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// `thunder notes <file> [--lens <lens>] [--json]` , the ThunderLens report: the compiled
|
|
1083
|
+
// semantic comments (`note <lens>:`) grouped by lens, each with its target and source
|
|
1084
|
+
// line. Notes explain meaning for a reader; they are NEVER verification.
|
|
1085
|
+
if (cmd === 'notes') {
|
|
1086
|
+
if (!file) { console.error('usage: intent notes <file> [--lens <lens>] [--json]'); process.exit(2); return; }
|
|
1087
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1088
|
+
let notes = ast.notes || [];
|
|
1089
|
+
if (args.lens) notes = notes.filter((n) => n.lens === args.lens);
|
|
1090
|
+
if (args.json) {
|
|
1091
|
+
console.log(JSON.stringify({ schema: 'intent-notes-v1', mission: ast.mission || null, lens: args.lens || null, count: notes.length, notes }, null, 2));
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
const scope = args.lens ? ` (lens: ${args.lens})` : '';
|
|
1095
|
+
console.log(`thunder notes ${basename(file)}${scope}: ${notes.length} note${notes.length === 1 ? '' : 's'}`);
|
|
1096
|
+
const known = new Set(KNOWN_LENSES);
|
|
1097
|
+
const byLens = {};
|
|
1098
|
+
for (const n of notes) (byLens[n.lens] ||= []).push(n);
|
|
1099
|
+
for (const lens of Object.keys(byLens).sort()) {
|
|
1100
|
+
console.log(`\n${lens}${known.has(lens) ? '' : ' (unknown lens)'}`);
|
|
1101
|
+
for (const n of byLens[lens]) {
|
|
1102
|
+
const label = n.targetKind === 'mission' ? (ast.mission || 'mission') : n.targetPath.split('.').slice(3).join('.');
|
|
1103
|
+
console.log(` [${n.targetKind}] ${label} , line ${n.sourceSpan.line}`);
|
|
1104
|
+
for (const line of String(n.text).split('\n')) console.log(` ${line.trim()}`);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// `thunder docs <file> [--lens <lens>] [--out <dir>]` , render a mission as Markdown docs.
|
|
1111
|
+
// With --lens, produce an audience-specific doc with that lens's notes woven inline.
|
|
1112
|
+
if (cmd === 'docs') {
|
|
1113
|
+
if (!file) { console.error('usage: intent docs <file> [--lens <lens>] [--out <dir>]'); process.exit(2); return; }
|
|
1114
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1115
|
+
const md = args.lens ? renderLensDoc(ast, args.lens) : renderMarkdown(ast);
|
|
1116
|
+
if (args.outExplicit) {
|
|
1117
|
+
const suffix = args.lens ? `.${args.lens}` : '';
|
|
1118
|
+
const p = writeText(args.out, `${slug(ast.mission)}${suffix}.md`, md.endsWith('\n') ? md : md + '\n');
|
|
1119
|
+
console.log(`wrote ${p.replace(process.cwd() + '/', '')}`);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
console.log(md);
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// `thunder code-actions <file> [--json]` , the available quick-fixes, each safety-graded
|
|
1127
|
+
// (safe autocorrects + reviewable diagnostic fixes). The IDE lightbulb's data source.
|
|
1128
|
+
if (cmd === 'code-actions') {
|
|
1129
|
+
if (!file) { console.error('usage: intent code-actions <file> [--json]'); process.exit(2); return; }
|
|
1130
|
+
const source = readFileSync(file, 'utf8');
|
|
1131
|
+
const actions = getCodeActions(source, semanticDiagnostics(parseIntent(source)));
|
|
1132
|
+
if (args.json) { console.log(JSON.stringify({ schema: 'intent-code-actions-v1', count: actions.length, actions }, null, 2)); return; }
|
|
1133
|
+
console.log(`thunder code-actions ${basename(file)}: ${actions.length} action${actions.length === 1 ? '' : 's'}`);
|
|
1134
|
+
for (const a of actions) console.log(` [${a.safety}] ${a.kind}${a.line ? ` (line ${a.line})` : ''} ${a.title}`);
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// `thunder apply-fix <file> [--write]` , apply the SAFE autocorrects only (header aliases,
|
|
1139
|
+
// stray colons). Reviewable quick-fixes are reported, never applied blindly.
|
|
1140
|
+
if (cmd === 'apply-fix') {
|
|
1141
|
+
if (!file) { console.error('usage: intent apply-fix <file> [--write]'); process.exit(2); return; }
|
|
1142
|
+
const source = readFileSync(file, 'utf8');
|
|
1143
|
+
const { fixed, changes } = autocorrectSource(source);
|
|
1144
|
+
const reviewable = getCodeActions(source, semanticDiagnostics(parseIntent(source))).filter((a) => a.safety !== 'safe');
|
|
1145
|
+
if (args.json) { console.log(JSON.stringify({ applied: changes, reviewableRemaining: reviewable.length, changed: fixed !== source }, null, 2)); }
|
|
1146
|
+
else {
|
|
1147
|
+
console.log(`thunder apply-fix ${basename(file)}: ${changes.length} safe fix${changes.length === 1 ? '' : 'es'}${args.write ? ' applied' : ' (dry run; pass --write)'}`);
|
|
1148
|
+
for (const c of changes) console.log(` line ${c.line}: "${c.from}" -> "${c.to}" [${c.rule}]`);
|
|
1149
|
+
if (reviewable.length) console.log(` ${reviewable.length} reviewable quick-fix(es) left for a human (run: intent code-actions ${basename(file)})`);
|
|
1150
|
+
}
|
|
1151
|
+
if (args.write && fixed !== source) { writeFileSync(file, fixed); if (!args.json) console.log(` wrote ${basename(file)}`); }
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// `thunder focus <mission|query|--nodes a,b> [--depth N] [--dir <d>] [--json]` , Intent Lens:
|
|
1156
|
+
// a focused Focus Graph + Intent Brief around a selected scope, built over the Atlas.
|
|
1157
|
+
if (cmd === 'focus') {
|
|
1158
|
+
const dir = args.dir || '.';
|
|
1159
|
+
const files = existsSync(dir) && statSync(dir).isDirectory() ? collectIntents(dir) : (file && existsSync(file) ? [file] : []);
|
|
1160
|
+
if (!files.length) { console.error(`thunder focus: no .intent files under ${dir}`); process.exit(2); return; }
|
|
1161
|
+
const atlas = buildAtlas(files.map((f) => buildIntentGraph(parseIntent(readFileSync(f, 'utf8')))));
|
|
1162
|
+
// Resolve seeds: --nodes ids, or a mission/feature query, or (default) all missions.
|
|
1163
|
+
let seeds = [];
|
|
1164
|
+
let scopeType = 'custom';
|
|
1165
|
+
let scopeTitle = null;
|
|
1166
|
+
if (args.nodes) { seeds = args.nodes.split(',').map((s) => s.trim()).filter(Boolean); scopeType = 'custom'; scopeTitle = `${seeds.length} selected node(s)`; }
|
|
1167
|
+
else if (file && !existsSync(file)) {
|
|
1168
|
+
const hit = searchAtlas(atlas, file)[0];
|
|
1169
|
+
if (!hit) { console.error(`thunder focus: no Atlas node matches "${file}"`); process.exit(1); return; }
|
|
1170
|
+
seeds = [hit.id]; scopeType = hit.type === 'Mission' ? 'mission' : 'feature'; scopeTitle = hit.title || hit.id;
|
|
1171
|
+
} else { seeds = atlas.missions.map((m) => m.id); scopeType = 'capability'; scopeTitle = 'whole project'; }
|
|
1172
|
+
const scope = makeScope({ type: scopeType, title: scopeTitle, seeds, createdAt: null });
|
|
1173
|
+
const focus = buildFocusGraph(atlas, { seeds, depth: args.depth ? Number(args.depth) : 2, scope });
|
|
1174
|
+
const brief = intentBrief(focus);
|
|
1175
|
+
if (args.json) { console.log(JSON.stringify({ scope, brief, focus }, null, 2)); return; }
|
|
1176
|
+
console.log(`thunder focus , ${scope.title} [${scope.type}] (${scope.scopeId})`);
|
|
1177
|
+
console.log(` what: ${brief.what || '(unnamed)'}${brief.confidence ? ` confidence: ${brief.confidence}` : ''}`);
|
|
1178
|
+
if (brief.who.length) console.log(` who: ${brief.who.join(', ')}`);
|
|
1179
|
+
console.log(` focus graph: ${focus.overview.nodes} node(s), ${focus.overview.relationships} edge(s), depth ${focus.depth}`);
|
|
1180
|
+
const br = focus.overview.byReason;
|
|
1181
|
+
console.log(` by reason: ${Object.entries(br).map(([k, v]) => `${v} ${k}`).join(', ')}`);
|
|
1182
|
+
if (brief.guarantees.length) console.log(` guarantees: ${brief.guarantees.length} prohibitions: ${brief.prohibitions.length} verification: ${brief.verification}`);
|
|
1183
|
+
if (brief.risks) console.log(` risks in scope: ${brief.risks}`);
|
|
1184
|
+
if (brief.unknowns.length) console.log(` unknowns: ${brief.unknowns.join('; ')}`);
|
|
1185
|
+
if (brief.needsReview) console.log(' note: scope includes low-confidence inferred intent , review before trusting.');
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// `thunder comprehension <file|dir> [--observed] [--learning] [--governed] [--json]` , the C0..C7
|
|
1190
|
+
// understanding level of each mission (Comprehension Contract). IL scores the intent side (C1..C4);
|
|
1191
|
+
// --observed (OpenThunder/runtime), --learning (Skills Tech Talk), --governed (Guardian) lift the
|
|
1192
|
+
// joint level to C5/C6/C7 when a sibling attaches its evidence.
|
|
1193
|
+
if (cmd === 'comprehension') {
|
|
1194
|
+
const root = file || '.';
|
|
1195
|
+
const files = existsSync(root) && statSync(root).isDirectory() ? collectIntents(root) : (existsSync(root) ? [root] : []);
|
|
1196
|
+
if (!files.length) { console.error(`thunder comprehension: no .intent files under ${root}`); process.exit(2); return; }
|
|
1197
|
+
const opts = { observed: !!args.observed, learningPath: !!args.learning, governed: !!args.governed };
|
|
1198
|
+
const asts = files.map((f) => parseIntent(readFileSync(f, 'utf8')));
|
|
1199
|
+
const report = comprehensionReport(asts, opts);
|
|
1200
|
+
if (args.json) { console.log(JSON.stringify(report, null, 2)); return; }
|
|
1201
|
+
console.log(`thunder comprehension ${root}: ${report.count} mission(s)`);
|
|
1202
|
+
console.log(` distribution: ${COMPREHENSION_LEVELS.map((l) => `${l.level}:${report.byLevel[l.level]}`).join(' ')}`);
|
|
1203
|
+
for (const m of report.missions) {
|
|
1204
|
+
console.log(`\n ${m.mission || '(unnamed)'} , ${m.level} ${m.levelName}`);
|
|
1205
|
+
console.log(` ${m.means}`);
|
|
1206
|
+
if (m.missing.length) {
|
|
1207
|
+
const next = m.missing[0];
|
|
1208
|
+
console.log(` next: reach ${next.level} ${next.name} , ${next.need} [${next.owner}]`);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
return;
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
// `thunder twelve-factor <file> [--json]` , score an intent against the 13 principles of
|
|
1215
|
+
// humanlayer/12-factor-agents (deterministic conformance lens). Per-factor verdict + score.
|
|
1216
|
+
if (cmd === 'twelve-factor' || cmd === '12factor') {
|
|
1217
|
+
if (!file) { console.error('usage: intent twelve-factor <file> [--json]'); process.exit(2); return; }
|
|
1218
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1219
|
+
const report = twelveFactorReport(ast);
|
|
1220
|
+
if (args.json) { console.log(JSON.stringify(report, null, 2)); return; }
|
|
1221
|
+
const mark = { satisfied: 'ok ', partial: '~ ', absent: 'MISS' };
|
|
1222
|
+
console.log(`12-factor conformance: ${report.subject || '(unnamed)'} , ${report.score}/100 (${report.grade})`);
|
|
1223
|
+
console.log(` ${report.counts.satisfied} satisfied · ${report.counts.partial} partial · ${report.counts.absent} absent\n`);
|
|
1224
|
+
for (const f of report.factors) {
|
|
1225
|
+
console.log(` [${mark[f.verdict]}] F${String(f.factor).padStart(2)} ${f.name}`);
|
|
1226
|
+
console.log(` ${f.evidence}`);
|
|
1227
|
+
if (f.fix) console.log(` fix: ${f.fix}`);
|
|
1228
|
+
}
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
// `thunder gen <file> [--target typescript|csharp|java|python] [--out <dir>]` , deterministic code scaffold from
|
|
1233
|
+
// intent. Generates the typed contract + the decision logic (already executable) and leaves
|
|
1234
|
+
// honest TODO markers for business logic. No AI. Prints, or writes with --out.
|
|
1235
|
+
if (cmd === 'gen') {
|
|
1236
|
+
if (!file) { console.error(`usage: intent gen <file> [--target ${Object.keys(GENERATORS).join('|')}] [--out <dir>]`); process.exit(2); return; }
|
|
1237
|
+
const target = (args.target || 'typescript').toLowerCase();
|
|
1238
|
+
const generate = GENERATORS[target];
|
|
1239
|
+
if (!generate) { console.error(`thunder gen: unknown target "${target}" (have: ${Object.keys(GENERATORS).join(', ')})`); process.exit(2); return; }
|
|
1240
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1241
|
+
// IL-GEN-001: a rule condition the target cannot express fails generation for that rule. The code
|
|
1242
|
+
// is still emitted (that rule throws at runtime with the same message), and the command exits 1.
|
|
1243
|
+
const { code, diagnostics } = generateWithDiagnostics(ast, target);
|
|
1244
|
+
const reportGen = () => {
|
|
1245
|
+
for (const d of diagnostics) console.error(`thunder gen: error ${d.code} (decision ${d.decision}, rule ${d.rule}): ${d.message}`);
|
|
1246
|
+
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}".`);
|
|
1247
|
+
};
|
|
1248
|
+
if (args.json) { console.log(JSON.stringify({ schema: 'intent-codegen-v1', target, code, diagnostics }, null, 2)); process.exit(diagnostics.length ? 1 : 0); return; }
|
|
1249
|
+
if (args.outExplicit) {
|
|
1250
|
+
const ext = target.startsWith('ts') || target === 'typescript' ? 'ts' : target === 'python' ? 'py' : target === 'csharp' ? 'cs' : target;
|
|
1251
|
+
// Java requires a public class to live in a file of exactly its name (RefundDecision.java).
|
|
1252
|
+
const subject = subjectName(ast) || 'intent';
|
|
1253
|
+
const fileName = ext === 'java' ? `${(subject[0].toUpperCase() + subject.slice(1)).replace(/[^A-Za-z0-9]/g, '')}.java` : `${slug(subject)}.${ext}`;
|
|
1254
|
+
const p = writeText(args.out, fileName, code.endsWith('\n') ? code : code + '\n');
|
|
1255
|
+
console.log(`wrote ${p.replace(process.cwd() + '/', '')}`);
|
|
1256
|
+
reportGen();
|
|
1257
|
+
if (diagnostics.length) process.exit(1);
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
console.log(code);
|
|
1261
|
+
reportGen();
|
|
1262
|
+
if (diagnostics.length) { process.exit(1); return; }
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
// `thunder changes [<base>..<head> | <base>] [--json]` , Change Lens: what a branch / PR / commit
|
|
1267
|
+
// range changed BY MEANING. git-diffs the .intent files, semantic-diffs each, and reports the
|
|
1268
|
+
// behavior-level changes + regression risk. Default: HEAD vs the working tree.
|
|
1269
|
+
if (cmd === 'changes') {
|
|
1270
|
+
const git = (c) => { try { return execSync(`git ${c}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }); } catch { return null; } };
|
|
1271
|
+
if (git('rev-parse --is-inside-work-tree') === null) { console.error('thunder changes: not a git repository'); process.exit(2); return; }
|
|
1272
|
+
const range = file || '';
|
|
1273
|
+
let base, head; // head === null means "the working tree"
|
|
1274
|
+
if (range.includes('..')) { [base, head] = range.split('..'); head = head || 'HEAD'; }
|
|
1275
|
+
else if (range) { base = range; head = null; }
|
|
1276
|
+
else { base = 'HEAD'; head = null; }
|
|
1277
|
+
const diffSpec = head ? `${base} ${head}` : base;
|
|
1278
|
+
const names = (git(`diff --name-only ${diffSpec} -- "*.thunder" "*.tl" "*.intent"`) || '').split('\n').map((s) => s.trim()).filter(Boolean);
|
|
1279
|
+
if (!names.length) { console.log(`thunder changes ${range || `${base}..working-tree`}: no source files changed`); return; }
|
|
1280
|
+
const readAt = (ref, p) => (ref === null ? (existsSync(p) ? readFileSync(p, 'utf8') : null) : git(`show ${ref}:${p}`));
|
|
1281
|
+
const toGraph = (src) => (src != null ? buildIntentGraph(parseIntent(src)) : null);
|
|
1282
|
+
const pairs = names.map((p) => ({ path: p, before: toGraph(readAt(base, p)), after: toGraph(readAt(head, p)) }));
|
|
1283
|
+
const report = changeReport(pairs);
|
|
1284
|
+
if (args.json) { console.log(JSON.stringify(report, null, 2)); process.exit(report.verdict === 'review' ? 1 : 0); return; }
|
|
1285
|
+
const t = report.totals;
|
|
1286
|
+
console.log(`thunder changes ${range || `${base}..working-tree`}: ${report.verdict.toUpperCase()}`);
|
|
1287
|
+
console.log(` ${t.files} file(s) , +${t.added} / -${t.removed} / ~${t.changed} nodes${t.invalidatedApprovals ? `, ${t.invalidatedApprovals} approval(s) invalidated` : ''}`);
|
|
1288
|
+
if (report.regressions.length) {
|
|
1289
|
+
console.log(' regression risk (a promise or its proof was removed or weakened):');
|
|
1290
|
+
for (const r of report.regressions) console.log(` - ${r.kind === 'weakened' ? 'weakened' : 'removed'} ${r.thing}: ${r.title}`);
|
|
1291
|
+
}
|
|
1292
|
+
const nonReg = report.highlights.filter((h) => !(h.kind === 'removed' && report.regressions.includes(h)));
|
|
1293
|
+
for (const h of nonReg.slice(0, 12)) console.log(` ${h.kind === 'added' ? '+' : h.kind === 'removed' ? '-' : '~'} ${h.kind} ${h.thing}: ${h.title}`);
|
|
1294
|
+
process.exit(report.verdict === 'review' ? 1 : 0);
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// Language Server (LSP over stdio) for editors. Long-running; no file argument.
|
|
1299
|
+
if (cmd === 'lsp') {
|
|
1300
|
+
startLspServer();
|
|
1301
|
+
return; // keep the process alive on stdin
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
// MCP server (Model Context Protocol over stdio) , makes ThunderLang a native tool for AI
|
|
1305
|
+
// coding agents. Long-running; no file argument. Point an MCP client at `thunder mcp`.
|
|
1306
|
+
if (cmd === 'mcp') {
|
|
1307
|
+
startMcpServer();
|
|
1308
|
+
return; // keep the process alive on stdin
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// Scaffold a runnable starter mission (deterministic, no AI). `thunder init [Name]`.
|
|
1312
|
+
if (cmd === 'init' || cmd === 'new') {
|
|
1313
|
+
const name = stripSourceExt(file || 'Mission');
|
|
1314
|
+
const target = join(args.out && args.out !== '.intent' ? args.out : '.', `${name}.thunder`);
|
|
1315
|
+
if (existsSync(target) && !args.force) {
|
|
1316
|
+
console.error(`thunder init: ${target} already exists (use --force to overwrite).`);
|
|
1317
|
+
process.exit(1); return;
|
|
1318
|
+
}
|
|
1319
|
+
const starter = `# A mission: what one part of your product must do, the rules it follows, and examples that prove them.
|
|
1320
|
+
# Run the examples: thunder test ${basename(target)}
|
|
1321
|
+
# Try the rule: thunder try ${basename(target)}
|
|
1322
|
+
mission ${name}
|
|
1323
|
+
use product
|
|
1324
|
+
|
|
1325
|
+
goal
|
|
1326
|
+
Describe what this mission must achieve.
|
|
1327
|
+
|
|
1328
|
+
guarantee an example property that must always hold
|
|
1329
|
+
because state why it matters
|
|
1330
|
+
verify a test that proves it
|
|
1331
|
+
|
|
1332
|
+
never
|
|
1333
|
+
do something this mission must never do
|
|
1334
|
+
|
|
1335
|
+
# A rule that decides: people 18 or older are allowed. Try it: thunder try ${basename(target)}
|
|
1336
|
+
decision Example
|
|
1337
|
+
inputs
|
|
1338
|
+
age
|
|
1339
|
+
rule adult
|
|
1340
|
+
when age >= 18
|
|
1341
|
+
return Allowed
|
|
1342
|
+
default
|
|
1343
|
+
return Blocked
|
|
1344
|
+
|
|
1345
|
+
# Examples that prove the rule. Run them: thunder test ${basename(target)}
|
|
1346
|
+
test Example
|
|
1347
|
+
case adult
|
|
1348
|
+
given age 20
|
|
1349
|
+
expect Allowed
|
|
1350
|
+
case minor
|
|
1351
|
+
given age 10
|
|
1352
|
+
expect Blocked
|
|
1353
|
+
`;
|
|
1354
|
+
if (target.includes('/')) mkdirSync(dirname(target), { recursive: true });
|
|
1355
|
+
writeFileSync(target, starter);
|
|
1356
|
+
console.log(paint([
|
|
1357
|
+
`Created ${target}: a starter mission, the ThunderLang™ format for a product's rules and the examples that prove them.`,
|
|
1358
|
+
'',
|
|
1359
|
+
'Try it:',
|
|
1360
|
+
` thunder test ${target} run the examples written in the file`,
|
|
1361
|
+
` thunder try ${target} try the rule with your own values`,
|
|
1362
|
+
` thunder check ${target} look for mistakes, explained in plain words`,
|
|
1363
|
+
'',
|
|
1364
|
+
'Just starting out? A program in plain words is easier: thunder new hello',
|
|
1365
|
+
].join('\n')));
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
if (!file && cmd !== 'draft' && cmd !== 'mission' && !(cmd === 'test' && args.changed)) {
|
|
1370
|
+
if (['run', 'test', 'build', 'check'].includes(cmd)) console.error(paint(noProjectText(cmd, process.cwd()), useColor(process.stderr)));
|
|
1371
|
+
else console.error(`thunder ${cmd}: missing a file argument. See: thunder help ${cmd}`);
|
|
1372
|
+
process.exit(2);
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
// `thunder mission <Name> [<verb> ...]` , noun-first ergonomics: resolve a mission by name
|
|
1376
|
+
// anywhere in the project, then run any verb on it without typing a path.
|
|
1377
|
+
// `thunder mission list` lists every mission. `thunder mission <Name>` prints a summary.
|
|
1378
|
+
if (cmd === 'mission') {
|
|
1379
|
+
const scanRoot = process.cwd();
|
|
1380
|
+
const parsed = collectIntents(scanRoot)
|
|
1381
|
+
.map((f) => { try { return { file: f, ast: parseIntent(readFileSync(f, 'utf8')) }; } catch { return null; } })
|
|
1382
|
+
.filter((x) => x && x.ast && x.ast.mission);
|
|
1383
|
+
const raw = process.argv.slice(3); // [Name|list, verb?, ...passthrough]
|
|
1384
|
+
const nameArg = raw[0];
|
|
1385
|
+
|
|
1386
|
+
if (!nameArg || nameArg === 'list') {
|
|
1387
|
+
if (!parsed.length) { console.log('thunder mission list: no missions found under the current directory.'); return; }
|
|
1388
|
+
console.log(`thunder mission list: ${parsed.length} mission(s)`);
|
|
1389
|
+
for (const { file: f, ast } of parsed.sort((a, b) => byText((a.ast.mission || ''), b.ast.mission || ''))) {
|
|
1390
|
+
const g = (ast.guarantees || []).length, n = (ast.neverRules || []).length, t = (ast.tests || []).length;
|
|
1391
|
+
console.log(` ${(ast.mission || '(unnamed)').padEnd(26)} ${relative(scanRoot, f)} (${g} guarantee(s), ${n} never, ${t} test(s))`);
|
|
1392
|
+
}
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
1397
|
+
const matches = parsed.filter((x) => x.ast.mission === nameArg);
|
|
1398
|
+
const hit = matches[0] || parsed.find((x) => norm(x.ast.mission) === norm(nameArg));
|
|
1399
|
+
if (!hit) { console.error(`thunder mission: no mission named "${nameArg}". Try: thunder mission list`); process.exit(2); return; }
|
|
1400
|
+
if (matches.length > 1) console.error(`thunder mission: ${matches.length} missions named "${nameArg}"; using ${relative(scanRoot, hit.file)}`);
|
|
1401
|
+
|
|
1402
|
+
const verb = raw[1];
|
|
1403
|
+
if (!verb) {
|
|
1404
|
+
const a = hit.ast;
|
|
1405
|
+
console.log(`mission ${a.mission} (${relative(scanRoot, hit.file)})`);
|
|
1406
|
+
if (a.goal) console.log(` goal: ${a.goal}`);
|
|
1407
|
+
if ((a.guarantees || []).length) { console.log(' guarantees:'); for (const g of a.guarantees) console.log(` - ${g.statement}`); }
|
|
1408
|
+
if ((a.neverRules || []).length) { console.log(' never:'); for (const nr of a.neverRules) console.log(` - ${nr.statement}`); }
|
|
1409
|
+
if ((a.targets || []).length) console.log(` targets: ${a.targets.join(', ')}`);
|
|
1410
|
+
if ((a.tests || []).length) console.log(` tests: ${a.tests.length}`);
|
|
1411
|
+
console.log(` try: thunder mission ${a.mission} check | run | test | prove | build`);
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// Delegate to `thunder <verb> <file> <passthrough>` in a child so every flag is honored exactly.
|
|
1416
|
+
const res = spawnSync(process.execPath, [process.argv[1], verb, hit.file, ...raw.slice(2)], { stdio: 'inherit' });
|
|
1417
|
+
process.exit(res.status == null ? 0 : res.status);
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
// IntentLift: lift source CODE into inferred .intent drafts (not intent parsing).
|
|
1421
|
+
if (cmd === 'lift') {
|
|
1422
|
+
// Repo mode: walk a directory, lift each file, emit drafts + a repo summary.
|
|
1423
|
+
if (args.from === 'repo') {
|
|
1424
|
+
const root = file;
|
|
1425
|
+
const files = collectFiles(root).map((f) => ({ file: relative(root, f), source: readFileSync(f, 'utf8') }));
|
|
1426
|
+
// Per-file language auto-detection (unless --from overrides). "repo" is not a language.
|
|
1427
|
+
const override = args.from && args.from !== 'repo' ? args.from : undefined;
|
|
1428
|
+
const res = liftRepo(files, { language: override });
|
|
1429
|
+
const outputs = res.missions.map((m) => ({
|
|
1430
|
+
mission: m.mission,
|
|
1431
|
+
file: args.out ? join(args.out, m.outName) : null,
|
|
1432
|
+
confidence: m.summary.confidence, reviewed: false,
|
|
1433
|
+
evidenceCount: m.summary.evidenceCount, unknowns: m.summary.unknowns,
|
|
1434
|
+
}));
|
|
1435
|
+
if (args.json) {
|
|
1436
|
+
const { missions, ...rest } = res; void missions;
|
|
1437
|
+
console.log(JSON.stringify({ sourceRoot: root, ...rest, outputs }, null, 2));
|
|
1438
|
+
return;
|
|
1439
|
+
}
|
|
1440
|
+
if (args.out) {
|
|
1441
|
+
for (const m of res.missions) writeText(args.out, m.outName, m.intentText);
|
|
1442
|
+
console.log(`thunder lift repo ${root} -> ${res.missionsGenerated} mission(s) in ${args.out}`);
|
|
1443
|
+
console.log(` confidence: ${JSON.stringify(res.confidenceSummary)} | ${res.unknowns} unknown(s) total`);
|
|
1444
|
+
} else {
|
|
1445
|
+
console.log(`thunder lift repo ${root}: ${res.missionsGenerated} mission(s)`);
|
|
1446
|
+
for (const m of res.missions) console.log(` ${m.mission} (${m.summary.confidence}) <- ${m.sourceFile}`);
|
|
1447
|
+
}
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// --all: lift EVERY function into its own mission (the Intent Atlas view of a file).
|
|
1452
|
+
if (args.all) {
|
|
1453
|
+
const src = readFileSync(file, 'utf8');
|
|
1454
|
+
const res = liftAll(src, { language: args.from || languageForFile(file), file: basename(file) });
|
|
1455
|
+
if (!res.ok) { console.error(res.error); process.exit(1); }
|
|
1456
|
+
if (args.json) { console.log(JSON.stringify(res, null, 2)); return; }
|
|
1457
|
+
console.log(`thunder lift --all ${basename(file)}: ${res.count} mission(s) inferred`);
|
|
1458
|
+
for (const m of res.missions) console.log(` ${m.mission} (${m.fn}, confidence ${m.confidence})`);
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// Single-file mode. Auto-detect language by extension (consistent with --all / repo modes).
|
|
1463
|
+
const src = readFileSync(file, 'utf8');
|
|
1464
|
+
const res = liftSource(src, { language: args.from || languageForFile(file), file: basename(file) });
|
|
1465
|
+
if (!res.ok) { console.error(res.error); process.exit(1); }
|
|
1466
|
+
if (args.json) { console.log(JSON.stringify(res.summary, null, 2)); return; }
|
|
1467
|
+
if (args.out) {
|
|
1468
|
+
const p = writeText(args.out, `${slug(res.lifted.mission)}.thunder`, res.intentText);
|
|
1469
|
+
console.log(`thunder lift ${basename(file)} -> ${p.replace(process.cwd() + '/', '')}`);
|
|
1470
|
+
} else {
|
|
1471
|
+
console.log(res.intentText);
|
|
1472
|
+
}
|
|
1473
|
+
printDiagnostics(res.diagnostics);
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// Approve an inferred/reviewed intent: reviewed:true + source hash + reviewer.
|
|
1478
|
+
if (cmd === 'approve') {
|
|
1479
|
+
const text = readFileSync(file, 'utf8');
|
|
1480
|
+
const res = approveIntent(text, { approvedBy: args.by || null, approvedAt: args.at || null });
|
|
1481
|
+
// args.out defaults to '.intent'; approve writes back to the file unless a real --out was given.
|
|
1482
|
+
const target = args.out && args.out !== '.intent' ? args.out : file;
|
|
1483
|
+
writeFileSync(target, res.text);
|
|
1484
|
+
console.log(`thunder approve ${basename(file)} -> reviewed: true (${res.approval.source_hash.slice(0, 24)}...)`);
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// Handoff: emit the il-to-ot-drift-v1 pack OpenThunder consumes for deep verification.
|
|
1489
|
+
if (cmd === 'handoff') {
|
|
1490
|
+
const text = readFileSync(file, 'utf8');
|
|
1491
|
+
const pack = buildDriftHandoff(text, { generatedAt: args.at || null });
|
|
1492
|
+
const out = JSON.stringify(pack, null, 2);
|
|
1493
|
+
if (args.out && args.out !== '.intent') {
|
|
1494
|
+
const p = writeText(args.out, `${slug(pack.mission)}.drift-handoff.json`, out);
|
|
1495
|
+
console.log(`thunder handoff ${basename(file)} -> ${p.replace(process.cwd() + '/', '')} (kind ${pack.kind}, approved ${pack.approved})`);
|
|
1496
|
+
} else {
|
|
1497
|
+
console.log(out);
|
|
1498
|
+
}
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// Drift: does the implementation still satisfy the approved intent?
|
|
1503
|
+
if (cmd === 'drift') {
|
|
1504
|
+
if (!args.intent) { console.error('usage: intent drift <codeFile> --intent <file.intent> [--from <lang>] [--json]'); process.exit(2); }
|
|
1505
|
+
const intentText = readFileSync(args.intent, 'utf8');
|
|
1506
|
+
const codeText = readFileSync(file, 'utf8');
|
|
1507
|
+
const language = args.from && args.from !== 'repo' ? args.from : languageForFile(file);
|
|
1508
|
+
const res = checkDrift(intentText, codeText, { language });
|
|
1509
|
+
if (args.evidence) {
|
|
1510
|
+
const ctx = { compilerVersion: COMPILER_VERSION, occurredAt: new Date().toISOString(), missionName: parseIntent(intentText).mission || null, intentHash: sha256(intentText), codeHash: sha256(codeText) };
|
|
1511
|
+
console.log(JSON.stringify(driftToEvidence(res, ctx), null, 2));
|
|
1512
|
+
process.exit(res.status === 'drift' ? 1 : 0); return;
|
|
1513
|
+
}
|
|
1514
|
+
if (args.json) { console.log(JSON.stringify(res, null, 2)); }
|
|
1515
|
+
else {
|
|
1516
|
+
console.log(`thunder drift: ${res.status.toUpperCase()} (${res.summary.blocking} blocking)`);
|
|
1517
|
+
for (const f of res.findings) console.log(` [${f.level}] ${f.code}: ${f.message}`);
|
|
1518
|
+
}
|
|
1519
|
+
process.exit(res.status === 'drift' ? 1 : 0);
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
// Intent AI implementations (intent-ai-v1): declare + list + manifest + prompt handoff.
|
|
1523
|
+
if (cmd === 'ai') {
|
|
1524
|
+
const sub = args._[0];
|
|
1525
|
+
const target = args._[1] || '.';
|
|
1526
|
+
if (sub === 'list') {
|
|
1527
|
+
const root = target;
|
|
1528
|
+
const parsed = collectIntents(root).map((f) => {
|
|
1529
|
+
const source = readFileSync(f, 'utf8');
|
|
1530
|
+
return { path: relative(root, f), source, ast: parseIntent(source) };
|
|
1531
|
+
});
|
|
1532
|
+
const manifest = buildManifest(parsed, { projectId: args.product });
|
|
1533
|
+
if (args.json) { console.log(JSON.stringify(manifest, null, 2)); return; }
|
|
1534
|
+
console.log(`thunder ai list ${root}: ${manifest.summary.total} AI implementation(s)`);
|
|
1535
|
+
for (const im of manifest.implementations) {
|
|
1536
|
+
console.log(` ${im.id.padEnd(28)} ${im.status.padEnd(9)} risk:${im.risk} approval:${im.approval} scope:${im.scope}`);
|
|
1537
|
+
}
|
|
1538
|
+
console.log(` ${JSON.stringify(manifest.summary.byStatus)} | ${manifest.summary.approvalRequired} require approval`);
|
|
1539
|
+
console.log(' note: PENDING = declared, no target region yet. OpenThunder verifies + advances state.');
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
if (sub === 'generate') {
|
|
1543
|
+
// Provider-neutral: emit the structured handoff prompt for one mission's .intent file.
|
|
1544
|
+
const file = args._[1];
|
|
1545
|
+
if (!file) { console.error('usage: intent ai generate <file.intent> [--from <lang>]'); process.exit(2); return; }
|
|
1546
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1547
|
+
if (!ast.implementation) { console.error(`thunder ai generate: ${basename(file)} has no "implement with ai" block.`); process.exit(2); return; }
|
|
1548
|
+
const prompt = buildImplementationPrompt(ast, { language: args.from || 'typescript' });
|
|
1549
|
+
if (args.out && args.out !== '.intent') { const p = writeText(args.out, `${slug(ast.mission)}.prompt.md`, prompt); console.log(`wrote ${p.replace(process.cwd() + '/', '')}`); }
|
|
1550
|
+
else console.log(prompt);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
if (sub === 'gate') {
|
|
1554
|
+
// Production gate: resolve each implementation's real state (declaration + region + proof).
|
|
1555
|
+
const root = target;
|
|
1556
|
+
const parsed = collectIntents(root).map((f) => ({ file: f, ast: parseIntent(readFileSync(f, 'utf8')) }));
|
|
1557
|
+
const manifest = buildManifest(parsed.map((p) => ({ path: relative(root, p.file), source: '', ast: p.ast })), { projectId: args.product });
|
|
1558
|
+
const apf = join(root, '.intent', 'ai-approvals.json');
|
|
1559
|
+
const approvals = existsSync(apf) ? JSON.parse(readFileSync(apf, 'utf8')) : emptyApprovals();
|
|
1560
|
+
const resolved = manifest.implementations.map((im) => {
|
|
1561
|
+
const ast = parsed.find((p) => (p.ast.implementation?.id || slug(p.ast.mission || '')) === im.id)?.ast;
|
|
1562
|
+
let region = null;
|
|
1563
|
+
if (im.targetLocation) {
|
|
1564
|
+
const tp = join(root, im.targetLocation);
|
|
1565
|
+
if (existsSync(tp)) region = parseMarkers(readFileSync(tp, 'utf8')).regions.find((r) => r.id === im.id) || null;
|
|
1566
|
+
}
|
|
1567
|
+
const pf = join(root, im.proofLocation);
|
|
1568
|
+
const proof = existsSync(pf) ? JSON.parse(readFileSync(pf, 'utf8')) : null;
|
|
1569
|
+
const st = resolveState({ ast, region, proof, approval: approvalFor(approvals, im.id) });
|
|
1570
|
+
return { id: im.id, status: st.status, approvalRequired: im.approval !== 'none', reasons: st.reasons };
|
|
1571
|
+
});
|
|
1572
|
+
const gate = productionGate(resolved, { allowPending: args.allowPending });
|
|
1573
|
+
if (args.json) { console.log(JSON.stringify({ ...gate, mode: args.mode || 'production', resolved }, null, 2)); process.exit(gate.ok ? 0 : 1); return; }
|
|
1574
|
+
console.log(`thunder ai gate ${root} (${args.mode || 'production'}): ${gate.ok ? 'PASS' : 'BLOCKED'} , ${resolved.length} implementation(s)`);
|
|
1575
|
+
for (const r of resolved) console.log(` ${r.id.padEnd(28)} ${r.status}${r.reasons?.[0] ? ` , ${r.reasons[0].code}: ${r.reasons[0].message}` : ''}`);
|
|
1576
|
+
if (!gate.ok) console.log(` ${gate.blocking.length} implementation(s) block production. Use --allow-pending for dev builds.`);
|
|
1577
|
+
process.exit(gate.ok ? 0 : 1);
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
if (sub === 'adopt') {
|
|
1581
|
+
// Rewrite an AI-managed region to human-owned, preserving provenance.
|
|
1582
|
+
const file = args._[1]; const id = args._[2];
|
|
1583
|
+
if (!file || !id) { console.error('usage: intent ai adopt <targetFile> <id> [--from <lang>]'); process.exit(2); return; }
|
|
1584
|
+
const code = readFileSync(file, 'utf8');
|
|
1585
|
+
const res = adoptRegion(code, id, args.from || languageForFile(file));
|
|
1586
|
+
if (!res) { console.error(`thunder ai adopt: no AI-managed region "${id}" in ${basename(file)}.`); process.exit(2); return; }
|
|
1587
|
+
writeFileSync(file, res.code);
|
|
1588
|
+
console.log(`thunder ai adopt ${id} -> human-owned (origin="ai" ownership="human") in ${basename(file)}`);
|
|
1589
|
+
return;
|
|
1590
|
+
}
|
|
1591
|
+
if (sub === 'approve' || sub === 'reject') {
|
|
1592
|
+
// Record a human decision bound to the reviewed hashes. Refuses stale/unverified.
|
|
1593
|
+
const root = args._[1] || '.'; const id = args._[2];
|
|
1594
|
+
if (!id) { console.error(`usage: intent ai ${sub} <dir> <id> --by <reviewer> [--role <role>] [--note <note>]`); process.exit(2); return; }
|
|
1595
|
+
const parsed = collectIntents(root).map((f) => ({ file: f, ast: parseIntent(readFileSync(f, 'utf8')) }));
|
|
1596
|
+
const manifest = buildManifest(parsed.map((p) => ({ path: relative(root, p.file), source: '', ast: p.ast })), {});
|
|
1597
|
+
const im = manifest.implementations.find((x) => x.id === id);
|
|
1598
|
+
const ast = parsed.find((p) => (p.ast.implementation?.id || slug(p.ast.mission || '')) === id)?.ast;
|
|
1599
|
+
if (!im || !ast) { console.error(`thunder ai ${sub}: no implementation "${id}" found under ${root}.`); process.exit(2); return; }
|
|
1600
|
+
let region = null;
|
|
1601
|
+
if (im.targetLocation && existsSync(join(root, im.targetLocation))) region = parseMarkers(readFileSync(join(root, im.targetLocation), 'utf8')).regions.find((r) => r.id === id) || null;
|
|
1602
|
+
const pf = join(root, im.proofLocation);
|
|
1603
|
+
const proof = existsSync(pf) ? JSON.parse(readFileSync(pf, 'utf8')) : null;
|
|
1604
|
+
const state = resolveState({ ast, region, proof });
|
|
1605
|
+
if (!region) { console.error(`INTENT-AI-501: cannot ${sub} "${id}" , no generated region yet (state ${state.status}).`); process.exit(1); return; }
|
|
1606
|
+
if (sub === 'approve' && !['VERIFIED', 'VERIFIED_AWAITING_APPROVAL'].includes(state.status)) {
|
|
1607
|
+
console.error(`INTENT-AI-502: cannot approve "${id}" in state ${state.status}${state.reasons?.[0] ? ` (${state.reasons[0].code})` : ''}. Approve only verified, non-stale work.`);
|
|
1608
|
+
process.exit(1); return;
|
|
1609
|
+
}
|
|
1610
|
+
const apf = join(root, '.intent', 'ai-approvals.json');
|
|
1611
|
+
const store = existsSync(apf) ? JSON.parse(readFileSync(apf, 'utf8')) : emptyApprovals();
|
|
1612
|
+
const at = new Date().toISOString();
|
|
1613
|
+
const { store: next, error } = recordDecision(store, id, {
|
|
1614
|
+
decision: sub === 'approve' ? 'approved' : 'rejected',
|
|
1615
|
+
by: args.by, role: args.role, note: args.note,
|
|
1616
|
+
contractHash: contractHash(ast), implementationHash: implementationHash(region.code), at,
|
|
1617
|
+
});
|
|
1618
|
+
if (error) { console.error(`thunder ai ${sub}: ${error}`); process.exit(2); return; }
|
|
1619
|
+
writeJson(join(root, '.intent'), 'ai-approvals.json', next);
|
|
1620
|
+
const event = makeEvent(sub === 'approve' ? 'IntentAiImplementationApproved' : 'IntentAiImplementationRejected', {
|
|
1621
|
+
implementationId: id, missionId: ast.mission, contractHash: contractHash(ast), implementationHash: implementationHash(region.code),
|
|
1622
|
+
timestamp: at, toolVersion: 'thunderlang', actorType: 'human', actorId: args.by || null, previousStatus: state.status,
|
|
1623
|
+
newStatus: sub === 'approve' ? 'APPROVED' : 'REJECTED',
|
|
1624
|
+
});
|
|
1625
|
+
const logPath = sinkEvent(root, event);
|
|
1626
|
+
console.log(`thunder ai ${sub} ${id} by ${args.by || '(anonymous)'}${args.role ? ` [${args.role}]` : ''} -> ${sub === 'approve' ? 'APPROVED' : 'REJECTED'} (bound to current hashes)`);
|
|
1627
|
+
console.log(` logged ${event.type} to ${logPath.replace(process.cwd() + '/', '')}`);
|
|
1628
|
+
if (args.json) console.log(JSON.stringify(event, null, 2));
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
// `thunder ai events [dir] [--subject <implId>] [--json]` , read the append-only audit log.
|
|
1632
|
+
if (sub === 'events') {
|
|
1633
|
+
const root = args._[1] || '.';
|
|
1634
|
+
const log = readEventLog(root);
|
|
1635
|
+
const events = args.subject ? log.events.filter((e) => e.implementationId === args.subject) : log.events;
|
|
1636
|
+
if (args.json) { console.log(JSON.stringify({ ...log, events }, null, 2)); return; }
|
|
1637
|
+
console.log(`thunder ai events ${root}: ${events.length} event${events.length === 1 ? '' : 's'}${args.subject ? ` for ${args.subject}` : ''}`);
|
|
1638
|
+
for (const e of events) {
|
|
1639
|
+
const who = e.actorId ? ` by ${e.actorId}` : '';
|
|
1640
|
+
const move = e.previousStatus || e.newStatus ? ` (${e.previousStatus || '?'} -> ${e.newStatus || '?'})` : '';
|
|
1641
|
+
console.log(` ${e.timestamp || '(no time)'} ${e.type}${who}${e.implementationId ? ` [${e.implementationId}]` : ''}${move}`);
|
|
1642
|
+
}
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
if (sub === 'select') {
|
|
1646
|
+
// Deterministic candidate selection: AI generates N candidates in
|
|
1647
|
+
// .intent/candidates/<id>/; IL picks by the mission's selection policy.
|
|
1648
|
+
const root = args._[1] || '.'; const id = args._[2];
|
|
1649
|
+
if (!id) { console.error('usage: intent ai select <dir> <id> [--json]'); process.exit(2); return; }
|
|
1650
|
+
const ast = collectIntents(root).map((f) => parseIntent(readFileSync(f, 'utf8')))
|
|
1651
|
+
.find((a) => (a.implementation?.id || slug(a.mission || '')) === id);
|
|
1652
|
+
const policy = parseSelection(ast?.selection || []);
|
|
1653
|
+
const cdir = join(root, '.intent', 'candidates', id);
|
|
1654
|
+
if (!existsSync(cdir)) { console.error(`thunder ai select: no candidates at ${relative(process.cwd(), cdir)}.`); process.exit(2); return; }
|
|
1655
|
+
const candidates = readdirSync(cdir).filter((n) => !n.endsWith('.proof.json') && !n.endsWith('.json')).map((name) => {
|
|
1656
|
+
const code = readFileSync(join(cdir, name), 'utf8');
|
|
1657
|
+
const region = parseMarkers(code).regions.find((r) => r.id === id);
|
|
1658
|
+
const proofFile = join(cdir, name.replace(/\.[^.]+$/, '') + '.proof.json');
|
|
1659
|
+
let checksPassed;
|
|
1660
|
+
if (existsSync(proofFile)) { const pr = JSON.parse(readFileSync(proofFile, 'utf8')); checksPassed = Object.values(pr.checks || {}).every((v) => v !== 'failed'); }
|
|
1661
|
+
return { id: name, metrics: regionMetrics(region ? region.code : code), checksPassed };
|
|
1662
|
+
});
|
|
1663
|
+
const result = selectCandidate(candidates, policy);
|
|
1664
|
+
if (args.json) { console.log(JSON.stringify({ ...result, policy }, null, 2)); return; }
|
|
1665
|
+
console.log(`thunder ai select ${id}: ${result.winner ? result.winner.id : '(none eligible)'} wins (${result.eligibleCount}/${candidates.length} eligible)`);
|
|
1666
|
+
console.log(` policy: prefer ${result.prefer.map((p) => `${p.direction} ${p.metric}`).join(', ')}${policy.requireAllChecks ? '; require all checks' : ''}`);
|
|
1667
|
+
for (const c of result.ranking) console.log(` ${c.id.padEnd(20)} ${JSON.stringify(c.metrics)}${c.checksPassed === false ? ' [checks FAILED]' : ''}`);
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
console.error(`thunder ai ${sub || ''}: IL supports list | generate | gate | adopt | approve | reject | select. OpenThunder runs verification.`);
|
|
1671
|
+
process.exit(2);
|
|
1672
|
+
return;
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
// Semantic diff: compare two snapshots (dirs or .intent files) by meaning.
|
|
1676
|
+
if (cmd === 'diff') {
|
|
1677
|
+
const b = args._[0]; const a = args._[1];
|
|
1678
|
+
if (!b || !a) { console.error('usage: thunder diff <before-dir|file> <after-dir|file> [--json]'); process.exit(2); return; }
|
|
1679
|
+
const snap = (p) => {
|
|
1680
|
+
if (statSync(p).isDirectory()) return buildAtlas(collectIntents(p).map((f) => buildIntentGraph(parseIntent(readFileSync(f, 'utf8')))));
|
|
1681
|
+
return buildIntentGraph(parseIntent(readFileSync(p, 'utf8')));
|
|
1682
|
+
};
|
|
1683
|
+
const diff = diffGraphs(snap(b), snap(a));
|
|
1684
|
+
if (args.json) { console.log(JSON.stringify(diff, null, 2)); return; }
|
|
1685
|
+
console.log(`thunder diff ${b} -> ${a}: +${diff.summary.added} / -${diff.summary.removed} / ~${diff.summary.changed} node(s), +${diff.summary.relationshipsAdded} / -${diff.summary.relationshipsRemoved} edge(s)`);
|
|
1686
|
+
if (Object.keys(diff.summary.addedByType).length) console.log(` added: ${JSON.stringify(diff.summary.addedByType)}`);
|
|
1687
|
+
if (Object.keys(diff.summary.removedByType).length) console.log(` removed: ${JSON.stringify(diff.summary.removedByType)}`);
|
|
1688
|
+
for (const c of diff.changedNodes.slice(0, 8)) console.log(` ~ ${c.type} ${c.id}`);
|
|
1689
|
+
if (diff.invalidatedApprovals.length) console.log(` approvals invalidated by the change: ${diff.invalidatedApprovals.join(', ')}`);
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
// Semantic merge: 3-way merge of two concurrent Intent versions over a common base.
|
|
1694
|
+
if (cmd === 'merge') {
|
|
1695
|
+
const [bp, op, tp] = [args._[0], args._[1], args._[2]];
|
|
1696
|
+
if (!bp || !op || !tp) { console.error('usage: intent merge <base> <ours> <theirs> [--json]'); process.exit(2); return; }
|
|
1697
|
+
const snap = (p) => statSync(p).isDirectory()
|
|
1698
|
+
? buildAtlas(collectIntents(p).map((f) => buildIntentGraph(parseIntent(readFileSync(f, 'utf8')))))
|
|
1699
|
+
: buildIntentGraph(parseIntent(readFileSync(p, 'utf8')));
|
|
1700
|
+
const res = mergeGraphs(snap(bp), snap(op), snap(tp));
|
|
1701
|
+
if (args.json) { console.log(JSON.stringify(res, null, 2)); process.exit(res.clean ? 0 : 1); return; }
|
|
1702
|
+
console.log(`thunder merge: ${res.clean ? 'CLEAN' : 'CONFLICTS'} , ${res.summary.nodes} node(s), ${res.summary.conflicts} conflict(s)`);
|
|
1703
|
+
for (const c of res.conflicts) console.log(` conflict: ${c.type} ${c.id} (changed differently on both sides)`);
|
|
1704
|
+
process.exit(res.clean ? 0 : 1);
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
// Intent Runtime: EXECUTE intent , evaluate decisions against concrete inputs.
|
|
1709
|
+
if (cmd === 'run') {
|
|
1710
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1711
|
+
let inputs = {};
|
|
1712
|
+
if (args.inputs) { try { inputs = JSON.parse(args.inputs); } catch { console.error('thunder run: --inputs must be JSON'); process.exit(2); return; } }
|
|
1713
|
+
let decisions = ast.decisions || [];
|
|
1714
|
+
if (args.decision) decisions = decisions.filter((d) => slug(d.name) === slug(args.decision));
|
|
1715
|
+
if (!decisions.length) { console.error('thunder run: no decision to run' + (args.decision ? ` matching "${args.decision}"` : '')); process.exit(2); return; }
|
|
1716
|
+
const runs = decisions.map((d) => evaluateDecision(d, inputs));
|
|
1717
|
+
if (args.json) { console.log(JSON.stringify(runs.length === 1 ? runs[0] : runs, null, 2)); return; }
|
|
1718
|
+
for (const r of runs) {
|
|
1719
|
+
console.log(`decision ${r.decision}: ${r.result === null ? '(undecided)' : r.result}${r.matched ? ` [rule: ${r.matched}]` : ''}`);
|
|
1720
|
+
for (const t of r.trace) console.log(` ${t.matched ? '>' : ' '} ${t.rule || '(rule)'}${t.when ? `: when ${t.when}` : ''}${t.error ? ` !! ${t.error}` : t.matched ? ' (matched)' : ''}`);
|
|
1721
|
+
}
|
|
1722
|
+
process.exit(runs.some((r) => r.undecided || !r.ok) ? 1 : 0);
|
|
1723
|
+
return;
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
// Outcome contracts: evaluate each commitment against the delivery result that measures it.
|
|
1727
|
+
if (cmd === 'outcomes') {
|
|
1728
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1729
|
+
const r = evaluateOutcomes(ast);
|
|
1730
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.missed > 0 ? 1 : 0); return; }
|
|
1731
|
+
if (r.total === 0) { console.log(`thunder outcomes ${basename(file)}: no outcome contracts found.`); return; }
|
|
1732
|
+
console.log(`thunder outcomes ${basename(file)}: ${r.met} met, ${r.missed} missed, ${r.pending} pending`);
|
|
1733
|
+
for (const e of r.evaluations) {
|
|
1734
|
+
const tag = e.status === 'met' ? 'MET ' : e.status === 'missed' ? 'MISSED' : 'PENDING';
|
|
1735
|
+
const detail = e.comparable ? `actual ${e.actual} vs target ${e.target} (${e.direction})${e.improvement != null ? `, ${e.improvement >= 0 ? '+' : ''}${e.improvement} vs baseline` : ''}` : `no measured result yet (target ${e.target})`;
|
|
1736
|
+
console.log(` ${tag} ${e.contract} , ${detail}`);
|
|
1737
|
+
}
|
|
1738
|
+
process.exit(r.missed > 0 ? 1 : 0);
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// Style intent: resolve brand/visual language against the canonical token address space.
|
|
1743
|
+
if (cmd === 'style') {
|
|
1744
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1745
|
+
const r = analyzeStyle(ast);
|
|
1746
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.diagnostics.some((d) => d.severity === 'blocker') ? 1 : 0); return; }
|
|
1747
|
+
if (r.styleIntents.length === 0) { console.log(`thunder style ${basename(file)}: no style intents found.`); return; }
|
|
1748
|
+
console.log(`thunder style ${basename(file)}: ${r.styleIntents.length} style intent(s)`);
|
|
1749
|
+
for (const s of r.styleIntents) {
|
|
1750
|
+
const a11y = s.accessibility ? `${s.accessibility.target} (${s.accessibility.classification}, verified=${s.accessibility.verified})` : 'no target';
|
|
1751
|
+
console.log(` ${s.name} , a11y ${a11y}, ${s.tokens.length} token(s)${s.appliesTo ? `, applies_to ${s.appliesTo}` : ''}`);
|
|
1752
|
+
for (const t of s.tokens) console.log(` ${t.canonical ? ' ' : '?'} ${t.path} = ${t.value ?? '(unset)'}`);
|
|
1753
|
+
}
|
|
1754
|
+
for (const d of r.diagnostics) console.log(` [${d.severity}] ${d.ruleId}: ${d.message}`);
|
|
1755
|
+
process.exit(0);
|
|
1756
|
+
return;
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
// Self-verifying intent: run the `test` blocks in a .intent file (decisions + lifecycles).
|
|
1760
|
+
if (cmd === 'test') {
|
|
1761
|
+
// Change-impact selection: run the tests for what a diff actually affects, using the Intent
|
|
1762
|
+
// Graph (not just the modified files). Selects changed intents plus any intent that shares an
|
|
1763
|
+
// event / service / api symbol with a changed one. `thunder test --changed [<range>]`.
|
|
1764
|
+
if (args.changed) {
|
|
1765
|
+
const gitc = (c) => { try { return execSync(`git ${c}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }); } catch { return null; } };
|
|
1766
|
+
const top = gitc('rev-parse --show-toplevel');
|
|
1767
|
+
if (top === null) { console.error('thunder test --changed: not a git repository'); process.exit(2); return; }
|
|
1768
|
+
const root = top.trim();
|
|
1769
|
+
const range = file || '';
|
|
1770
|
+
let base, head;
|
|
1771
|
+
if (range.includes('..')) { [base, head] = range.split('..'); head = head || 'HEAD'; }
|
|
1772
|
+
else if (range) { base = range; head = null; }
|
|
1773
|
+
else { base = 'HEAD'; head = null; }
|
|
1774
|
+
const diffSpec = head ? `${base} ${head}` : base;
|
|
1775
|
+
const changed = (gitc(`diff --name-only ${diffSpec} -- "*.thunder" "*.tl" "*.intent"`) || '').split('\n').map((s) => s.trim()).filter(Boolean);
|
|
1776
|
+
const label = range || `${base}..working-tree`;
|
|
1777
|
+
if (!changed.length) { console.log(`thunder test --changed ${label}: no source files changed`); return; }
|
|
1778
|
+
|
|
1779
|
+
const symbolsOf = (ast) => {
|
|
1780
|
+
const s = new Set();
|
|
1781
|
+
if (!ast) return s;
|
|
1782
|
+
if (ast.mission) s.add(`system:${ast.mission}`);
|
|
1783
|
+
for (const e of ast.events || []) s.add(`event:${e.name}`);
|
|
1784
|
+
for (const sv of ast.services || []) { s.add(`service:${sv.name}`); (sv.publishes || []).forEach((p) => s.add(`event:${p}`)); (sv.consumes || []).forEach((p) => s.add(`event:${p}`)); }
|
|
1785
|
+
for (const ap of ast.apis || []) s.add(`api:${ap.name}`);
|
|
1786
|
+
return s;
|
|
1787
|
+
};
|
|
1788
|
+
const rel = (p) => relative(root, p);
|
|
1789
|
+
const astAt = (relpath) => { const abs = join(root, relpath); if (!existsSync(abs)) return null; try { return parseIntent(readFileSync(abs, 'utf8')); } catch { return null; } };
|
|
1790
|
+
|
|
1791
|
+
// Seed symbols from the changed intents, then find every repo intent that shares one.
|
|
1792
|
+
const changedAsts = new Map(changed.map((p) => [p, astAt(p)]));
|
|
1793
|
+
const seed = new Set();
|
|
1794
|
+
for (const ast of changedAsts.values()) for (const sym of symbolsOf(ast)) seed.add(sym);
|
|
1795
|
+
const selected = new Map();
|
|
1796
|
+
for (const p of changed) selected.set(p, 'changed');
|
|
1797
|
+
for (const abs of collectIntents(root)) {
|
|
1798
|
+
const p = rel(abs);
|
|
1799
|
+
if (selected.has(p)) continue;
|
|
1800
|
+
const shared = [...symbolsOf(parseIntent(readFileSync(abs, 'utf8')))].filter((x) => seed.has(x));
|
|
1801
|
+
if (shared.length) selected.set(p, `impacted via ${shared[0].replace(':', ' ')}`);
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
let anyFail = false;
|
|
1805
|
+
const results = [];
|
|
1806
|
+
for (const [p, reason] of selected) {
|
|
1807
|
+
const ast = changedAsts.get(p) || astAt(p);
|
|
1808
|
+
if (!ast) { results.push({ file: p, reason, deleted: true }); continue; }
|
|
1809
|
+
const r = runTests(ast);
|
|
1810
|
+
const res = resolveObligations(ast);
|
|
1811
|
+
const testsOk = r.total === 0 || r.ok;
|
|
1812
|
+
if (!testsOk || res.failed > 0) anyFail = true;
|
|
1813
|
+
results.push({ file: p, reason, tests: { passed: r.passed, total: r.total, ok: testsOk }, unverified: res.unverified, failedClaims: res.failed });
|
|
1814
|
+
}
|
|
1815
|
+
if (args.json) { console.log(JSON.stringify({ schema: 'thunder-changed-v1', range: label, changed, selected: results }, null, 2)); process.exit(anyFail ? 1 : 0); return; }
|
|
1816
|
+
console.log(`thunder test --changed ${label}: ${changed.length} changed, ${selected.size} intent(s) selected`);
|
|
1817
|
+
for (const r of results) {
|
|
1818
|
+
if (r.deleted) { console.log(` , ${r.file} [${r.reason}, deleted]`); continue; }
|
|
1819
|
+
const mark = r.tests.ok && !r.failedClaims ? 'PASS' : 'FAIL';
|
|
1820
|
+
console.log(` ${mark.padEnd(6)} ${r.file} [${r.reason}] tests ${r.tests.passed}/${r.tests.total}${r.unverified ? `, ${r.unverified} unverified` : ''}`);
|
|
1821
|
+
}
|
|
1822
|
+
process.exit(anyFail ? 1 : 0);
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
1827
|
+
|
|
1828
|
+
// Property-based testing: generate many cases for each `property`, evaluate the decision,
|
|
1829
|
+
// assert the `expect` clauses, and shrink failures. `thunder test <file> --properties`.
|
|
1830
|
+
if (args.properties) {
|
|
1831
|
+
const cases = Number.isFinite(Number(args.cases)) && Number(args.cases) > 0 ? Math.min(Math.floor(Number(args.cases)), 100000) : 100;
|
|
1832
|
+
const seed = Number.isFinite(Number(args.seed)) ? Math.floor(Number(args.seed)) : 424242;
|
|
1833
|
+
const rep = runProperties(ast, { cases, seed });
|
|
1834
|
+
const bad = rep.passed !== rep.total;
|
|
1835
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
|
|
1836
|
+
if (!rep.total) { console.log(`thunder test ${basename(file)} --properties: no property blocks found.`); return; }
|
|
1837
|
+
console.log(`thunder test ${basename(file)} --properties: ${rep.total} propert${rep.total === 1 ? 'y' : 'ies'}, ${rep.passed} passed`);
|
|
1838
|
+
for (const r of rep.results) {
|
|
1839
|
+
if (r.error) { console.log(` FAIL ${r.property} , ${r.error}`); continue; }
|
|
1840
|
+
if (r.ok) { console.log(` PASS ${r.property} (${r.cases} cases, seed ${r.seed})`); continue; }
|
|
1841
|
+
const f = r.failure;
|
|
1842
|
+
const inputs = Object.entries(f.inputs).map(([k, v]) => `${k}=${v}`).join(', ');
|
|
1843
|
+
console.log(` FAIL ${r.property} (seed ${r.seed})`);
|
|
1844
|
+
console.log(` smallest failure: ${inputs} -> ${f.expect} (got ${f.actual})`);
|
|
1845
|
+
}
|
|
1846
|
+
process.exit(bad ? 1 : 0);
|
|
1847
|
+
return;
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
// Scenario tests: workflow-level given/when/then/never. Deterministically flags a scenario
|
|
1851
|
+
// that both expects and prohibits the same outcome; otherwise DECLARED (needs runtime evidence).
|
|
1852
|
+
if (args.scenarios) {
|
|
1853
|
+
const scenarios = ast.scenarios || [];
|
|
1854
|
+
const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
1855
|
+
const results = scenarios.map((sc) => {
|
|
1856
|
+
const neverSet = new Set(sc.never.map(norm));
|
|
1857
|
+
const positives = [...sc.then, ...sc.eventually.flatMap((e) => e.clauses)];
|
|
1858
|
+
const contradictions = positives.filter((p) => neverSet.has(norm(p)));
|
|
1859
|
+
return { scenario: sc.name, status: contradictions.length ? 'failed' : 'declared', given: sc.given.length, then: positives.length, never: sc.never.length, contradictions };
|
|
1860
|
+
});
|
|
1861
|
+
const failed = results.filter((r) => r.status === 'failed').length;
|
|
1862
|
+
const rep = { schema: 'thunder-scenarios-v1', mission: ast.mission, file: basename(file), total: results.length, failed, results };
|
|
1863
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(failed ? 1 : 0); return; }
|
|
1864
|
+
if (!rep.total) { console.log(`thunder test ${basename(file)} --scenarios: no scenario blocks found.`); return; }
|
|
1865
|
+
console.log(`thunder test ${basename(file)} --scenarios: ${rep.total} scenario(s), ${rep.total - failed} consistent${failed ? `, ${failed} contradictory` : ''}`);
|
|
1866
|
+
for (const r of results) {
|
|
1867
|
+
if (r.status === 'failed') console.log(` FAIL ${r.scenario} , contradiction: ${r.contradictions.map((c) => `"${c}"`).join(', ')} both expected and prohibited`);
|
|
1868
|
+
else console.log(` DECLARED ${r.scenario} (${r.given} given, ${r.then} then, ${r.never} never) , needs runtime evidence`);
|
|
1869
|
+
}
|
|
1870
|
+
process.exit(failed ? 1 : 0);
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// All-targets mode: run the tests against EVERY target whose toolchain is available, in one
|
|
1875
|
+
// pass, and report each target's pass count side by side. `thunder test <file> --all-targets`.
|
|
1876
|
+
if (args.allTargets) {
|
|
1877
|
+
const report = LIVE_TARGETS.map((t) => {
|
|
1878
|
+
const run = t.available() ? t.run(ast) : runFailure('missing-toolchain', `${t.key} toolchain not available`);
|
|
1879
|
+
if (run.status === 'error' && run.kind === 'missing-toolchain') return { target: t.key, status: 'skipped', reason: run.message, kind: run.kind };
|
|
1880
|
+
// A compile failure, crash, or timeout is an error for the whole target, not a skip and not a pass.
|
|
1881
|
+
if (run.status === 'error') return { target: t.key, status: 'error', kind: run.kind, message: run.message, total: 0, passed: 0, cases: gradeRun(ast, run) };
|
|
1882
|
+
const cases = gradeRun(ast, run);
|
|
1883
|
+
const passed = cases.filter((c) => c.pass).length;
|
|
1884
|
+
const errors = cases.filter((c) => c.status === 'error').length;
|
|
1885
|
+
return { target: t.key, status: passed === cases.length ? 'pass' : 'fail', total: cases.length, passed, errors, cases };
|
|
1886
|
+
});
|
|
1887
|
+
const bad = report.some((r) => r.status === 'fail' || r.status === 'error');
|
|
1888
|
+
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; }
|
|
1889
|
+
const cap = (s) => ({ typescript: 'TypeScript', csharp: 'C#', javascript: 'JavaScript' })[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
|
|
1890
|
+
const ran = report.filter((r) => r.status !== 'skipped');
|
|
1891
|
+
console.log(`thunder test ${basename(file)} --all-targets: ${ran.length}/${report.length} target(s) executed`);
|
|
1892
|
+
for (const r of report) {
|
|
1893
|
+
if (r.status === 'skipped') { console.log(` SKIP ${cap(r.target).padEnd(12)} (toolchain not available)`); continue; }
|
|
1894
|
+
if (r.status === 'error') { console.log(` ERROR ${cap(r.target).padEnd(12)} ${r.kind}: ${r.message}`); continue; }
|
|
1895
|
+
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` : ''}`);
|
|
1896
|
+
for (const c of r.cases) if (!c.pass) console.log(` ${caseLine(c)}`);
|
|
1897
|
+
}
|
|
1898
|
+
process.exit(bad ? 1 : 0);
|
|
1899
|
+
return;
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// Target mode: run the tests against the GENERATED TypeScript (executed for real), not the
|
|
1903
|
+
// semantic engine. Proves the generated implementation is faithful to the intent.
|
|
1904
|
+
// `thunder test <file> --target typescript`.
|
|
1905
|
+
if (args.target && RUNNABLE_TARGETS.has(String(args.target).toLowerCase())) {
|
|
1906
|
+
const targetKey = canonicalTarget(args.target);
|
|
1907
|
+
const run = runLiveTarget(ast, targetKey);
|
|
1908
|
+
// Live target could not run because its toolchain is missing (e.g. python3 not installed) , skip cleanly, don't fail.
|
|
1909
|
+
if (run.status === 'error' && run.kind === 'missing-toolchain') {
|
|
1910
|
+
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; }
|
|
1911
|
+
console.log(`thunder test ${basename(file)} --target ${targetKey}: skipped (the ${targetKey} runtime is not available on this machine).`);
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
// Any other whole-run failure (compile failure, crash, timeout) is an error with its reason, never a null answer.
|
|
1915
|
+
if (run.status === 'error') {
|
|
1916
|
+
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; }
|
|
1917
|
+
console.log(`thunder test ${basename(file)} --target ${targetKey}: ERROR (${run.kind}) , ${run.message}`);
|
|
1918
|
+
process.exit(1);
|
|
1919
|
+
return;
|
|
1920
|
+
}
|
|
1921
|
+
const cases = gradeRun(ast, run);
|
|
1922
|
+
const passed = cases.filter((c) => c.pass).length;
|
|
1923
|
+
const errors = cases.filter((c) => c.status === 'error').length;
|
|
1924
|
+
const bad = passed !== cases.length;
|
|
1925
|
+
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; }
|
|
1926
|
+
if (!cases.length) { console.log(`thunder test ${basename(file)} --target ${targetKey}: no decision test cases to run.`); return; }
|
|
1927
|
+
console.log(`thunder test ${basename(file)} --target ${targetKey}: ${passed}/${cases.length} passed (executed generated code)${errors ? `, ${errors} could not run` : ''}`);
|
|
1928
|
+
for (const c of cases) console.log(` ${c.pass ? `PASS ${c.key}` : caseLine(c).replace(/^(FAIL|ERROR) /, (m) => m.trim().padEnd(6))}`);
|
|
1929
|
+
process.exit(bad ? 1 : 0);
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
// Semantic coverage: which goals, decision rules, guarantees, prohibitions, scenarios, and
|
|
1934
|
+
// targets are actually exercised , meaning-level, not lines. `thunder test <file> --coverage`.
|
|
1935
|
+
if (args.coverage) {
|
|
1936
|
+
const rep = semanticCoverage(ast);
|
|
1937
|
+
const bad = args.strict && rep.unverified.length > 0;
|
|
1938
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
|
|
1939
|
+
console.log(`thunder test ${basename(file)} --coverage: ${rep.overall}% overall`);
|
|
1940
|
+
console.log('');
|
|
1941
|
+
for (const m of rep.metrics) console.log(` ${m.name.padEnd(16)} ${`${m.covered}/${m.total}`.padStart(7)} ${String(m.pct).padStart(3)}%`);
|
|
1942
|
+
if (rep.unverified.length) {
|
|
1943
|
+
console.log('');
|
|
1944
|
+
console.log(' Unverified:');
|
|
1945
|
+
for (const u of rep.unverified) console.log(` - ${u}`);
|
|
1946
|
+
}
|
|
1947
|
+
process.exit(bad ? 1 : 0);
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
// AI evaluations: probabilistic behavior graded against a dataset by metric thresholds.
|
|
1952
|
+
// Declare the bar in ThunderLang; feed measured metrics via --results to gate on them.
|
|
1953
|
+
// `thunder test <file> --evals [--results <json|path>] [--strict]`.
|
|
1954
|
+
if (args.evals) {
|
|
1955
|
+
let results = null;
|
|
1956
|
+
if (args.results) {
|
|
1957
|
+
try { results = existsSync(args.results) ? JSON.parse(readFileSync(args.results, 'utf8')) : JSON.parse(args.results); }
|
|
1958
|
+
catch { console.error('thunder test --evals: --results must be a JSON file path or inline JSON of {metric: value}'); process.exit(2); return; }
|
|
1959
|
+
}
|
|
1960
|
+
const cmp = { '>=': (a, b) => a >= b, '<=': (a, b) => a <= b, '>': (a, b) => a > b, '<': (a, b) => a < b, '==': (a, b) => a === b, '!=': (a, b) => a !== b };
|
|
1961
|
+
const evals = (ast.evaluations || []).map((ev) => {
|
|
1962
|
+
if (!results) return { name: ev.name, dataset: ev.dataset, status: 'declared', requires: ev.requires };
|
|
1963
|
+
const checks = ev.requires.map((r) => {
|
|
1964
|
+
const have = results[r.metric];
|
|
1965
|
+
if (have === undefined) return { ...r, actual: null, pass: false, missing: true };
|
|
1966
|
+
return { ...r, actual: Number(have), pass: cmp[r.op](Number(have), r.threshold) };
|
|
1967
|
+
});
|
|
1968
|
+
return { name: ev.name, dataset: ev.dataset, status: checks.every((c) => c.pass) ? 'passed' : 'failed', checks };
|
|
1969
|
+
});
|
|
1970
|
+
const failed = evals.filter((e) => e.status === 'failed').length;
|
|
1971
|
+
const declared = evals.filter((e) => e.status === 'declared').length;
|
|
1972
|
+
const bad = failed > 0 || (args.strict && declared > 0);
|
|
1973
|
+
const rep = { schema: 'thunder-evals-v1', mission: ast.mission, file: basename(file), total: evals.length, passed: evals.filter((e) => e.status === 'passed').length, declared, failed, results: evals };
|
|
1974
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
|
|
1975
|
+
if (!rep.total) { console.log(`thunder test ${basename(file)} --evals: no evaluation blocks found.`); return; }
|
|
1976
|
+
console.log(`thunder test ${basename(file)} --evals: ${rep.total} evaluation(s)${results ? `, ${rep.passed} passed${failed ? `, ${failed} failed` : ''}` : ' (declared , provide --results to grade)'}`);
|
|
1977
|
+
for (const e of evals) {
|
|
1978
|
+
const label = e.status === 'passed' ? 'PASS' : e.status === 'failed' ? 'FAIL' : 'DECLARED';
|
|
1979
|
+
console.log(` ${label.padEnd(9)} ${e.name}${e.dataset ? ` (dataset ${e.dataset})` : ''}`);
|
|
1980
|
+
for (const r of (e.checks || e.requires)) {
|
|
1981
|
+
const mark = e.checks ? (r.pass ? '✓' : '✗') : '·';
|
|
1982
|
+
const actual = e.checks ? (r.missing ? ' (metric not in results)' : ` (${r.actual})`) : '';
|
|
1983
|
+
console.log(` ${mark} ${r.metric} ${r.op} ${r.threshold}${actual}`);
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
process.exit(bad ? 1 : 0);
|
|
1987
|
+
return;
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
// Mutation testing: inject faults into decisions and check the tests catch them.
|
|
1991
|
+
// A survived mutant is a weak spot. `thunder test <file> --mutate [--strict]`.
|
|
1992
|
+
if (args.mutate) {
|
|
1993
|
+
const rep = runMutations(ast);
|
|
1994
|
+
const bad = args.strict && rep.survived > 0;
|
|
1995
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
|
|
1996
|
+
if (rep.total === 0) { console.log(`thunder test ${basename(file)} --mutate: ${rep.note}`); return; }
|
|
1997
|
+
console.log(`thunder test ${basename(file)} --mutate: mutation score ${rep.score}% (${rep.killed} killed, ${rep.survived} survived of ${rep.total})`);
|
|
1998
|
+
const survivors = rep.results.filter((r) => !r.killed);
|
|
1999
|
+
if (survivors.length) { console.log(' survived , the tests did not catch these (weak spots):'); for (const s of survivors) console.log(` - ${s.describe}`); }
|
|
2000
|
+
process.exit(bad ? 1 : 0);
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
// Contract-test derivation: every `guarantee` and `never` is a test obligation.
|
|
2005
|
+
// Honest resolution: no verification -> UNVERIFIED (never silently PASS); a declared
|
|
2006
|
+
// verification with the file's checks green -> PASS; a failing in-file check -> FAIL.
|
|
2007
|
+
// `--strict` also fails the run on any UNVERIFIED obligation (CI: nothing left unproven).
|
|
2008
|
+
if (args.contracts) {
|
|
2009
|
+
const res = resolveObligations(ast);
|
|
2010
|
+
const obligations = res.obligations;
|
|
2011
|
+
const rep = { schema: 'thunder-contracts-v1', mission: ast.mission, file: basename(file),
|
|
2012
|
+
total: obligations.length, verified: res.verified, declared: res.declared,
|
|
2013
|
+
unverified: res.unverified, failed: res.failed, obligations };
|
|
2014
|
+
const bad = rep.failed > 0 || (args.strict && rep.unverified > 0);
|
|
2015
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
|
|
2016
|
+
if (!rep.total) { console.log(`thunder test ${basename(file)} --contracts: no guarantees or prohibitions declared.`); return; }
|
|
2017
|
+
console.log(`thunder test ${basename(file)} --contracts: ${rep.total} obligation(s), ${rep.verified} verified, ${rep.declared} declared, ${rep.unverified} unverified${rep.failed ? `, ${rep.failed} failed` : ''}`);
|
|
2018
|
+
const LABEL = { verified: 'PASS', failed: 'FAIL', declared: 'DECLARED', unverified: 'UNVERIFIED' };
|
|
2019
|
+
for (const o of obligations) {
|
|
2020
|
+
const by = o.kinds.length ? ` by ${o.kinds.join('+')}` : '';
|
|
2021
|
+
const detail = o.provenBy ? ` proven by test ${o.provenBy}`
|
|
2022
|
+
: o.status === 'declared' ? ' (declared, runs in target mode)'
|
|
2023
|
+
: o.status === 'unverified' ? ' (nothing verifies this)' : '';
|
|
2024
|
+
console.log(` ${LABEL[o.status].padEnd(10)} ${o.kind} ${o.id}: ${o.text}${by}${detail}`);
|
|
2025
|
+
}
|
|
2026
|
+
if (args.strict && rep.unverified) console.log(`\n strict: ${rep.unverified} unverified obligation(s) , run fails until every claim carries a verification.`);
|
|
2027
|
+
process.exit(bad ? 1 : 0);
|
|
2028
|
+
return;
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
const r = runTests(ast);
|
|
2032
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.ok ? 0 : 1); return; }
|
|
2033
|
+
if (r.total === 0) { console.log(`thunder test ${basename(file)}: no test blocks found.`); return; }
|
|
2034
|
+
console.log(`thunder test ${basename(file)}: ${r.passed}/${r.total} passed`);
|
|
2035
|
+
for (const c of r.results) {
|
|
2036
|
+
const detail = c.error ? ` ${c.error}`
|
|
2037
|
+
: c.kind === 'lifecycle' ? `expected ${c.expected ?? '(any)'}, got ${c.actual} (valid=${c.valid})`
|
|
2038
|
+
: `expected ${c.expected}, got ${c.actual}`;
|
|
2039
|
+
console.log(` ${c.pass ? 'PASS' : 'FAIL'} ${c.target} / ${c.case}${c.pass ? '' : ` , ${detail}`}`);
|
|
2040
|
+
}
|
|
2041
|
+
process.exit(r.ok ? 0 : 1);
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
// PROVE: run the tests, evaluate guarantee / prohibition obligations, and emit a durable
|
|
2046
|
+
// intent-proof-v1 artifact with honest statuses. Unverified claims never read as passed.
|
|
2047
|
+
// `thunder prove <file> [--out <dir>] [--json]`.
|
|
2048
|
+
if (cmd === 'prove') {
|
|
2049
|
+
if (!file || !existsSync(file)) { console.error('usage: thunder prove <file> [--out <dir>] [--json]'); process.exit(2); return; }
|
|
2050
|
+
const source = readFileSync(file, 'utf8');
|
|
2051
|
+
const ast = parseIntent(source);
|
|
2052
|
+
const diagnostics = semanticDiagnostics(ast);
|
|
2053
|
+
const resolved = resolveObligations(ast);
|
|
2054
|
+
const tests = resolved.tests;
|
|
2055
|
+
const proof = buildProof(ast, {
|
|
2056
|
+
sourceFile: basename(file),
|
|
2057
|
+
sourceHash: sha256(source),
|
|
2058
|
+
targetsRequested: ast.targets || [],
|
|
2059
|
+
targetsGenerated: [],
|
|
2060
|
+
diagnostics,
|
|
2061
|
+
generatedAt: new Date().toISOString(),
|
|
2062
|
+
});
|
|
2063
|
+
// Fold per-claim verdicts into the proof so it records real status, not just planned/needs_verification.
|
|
2064
|
+
const CLAIM_MAP = { verified: 'verified', failed: 'failed', declared: 'planned', unverified: 'needs_verification' };
|
|
2065
|
+
const byId = new Map(resolved.obligations.map((o) => [o.id, o]));
|
|
2066
|
+
const applyStatus = (claim) => { const o = byId.get(claim.id); return o ? { ...claim, status: CLAIM_MAP[o.status], provenBy: o.provenBy || null } : claim; };
|
|
2067
|
+
proof.guarantees = proof.guarantees.map(applyStatus);
|
|
2068
|
+
proof.neverRules = proof.neverRules.map(applyStatus);
|
|
2069
|
+
// Freshness tuple: what `thunder verify` recomputes to mark this proof STALE later.
|
|
2070
|
+
proof.freshness = freshnessFor(file, proof, args.env);
|
|
2071
|
+
const proofId = `proof-${proof.sourceHash.replace('sha256:', '').slice(0, 6)}`;
|
|
2072
|
+
const fail = !proof.verification.semanticPassed || !tests.ok || resolved.failed > 0;
|
|
2073
|
+
|
|
2074
|
+
if (args.json) {
|
|
2075
|
+
console.log(JSON.stringify({ proofId, ...proof, tests }, null, 2));
|
|
2076
|
+
process.exit(fail ? 1 : 0);
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
console.log(`Proof created: ${proofId}`);
|
|
2081
|
+
console.log('');
|
|
2082
|
+
console.log(` Intent: ${proof.missionName || stripSourceExt(basename(file))}`);
|
|
2083
|
+
console.log(` Intent hash: ${proof.sourceHash}`);
|
|
2084
|
+
console.log(` Compiler: ThunderLang ${proof.compilerVersion}`);
|
|
2085
|
+
console.log(` Generated: ${proof.generatedAt}`);
|
|
2086
|
+
console.log(` Syntax: ${proof.verification.syntaxPassed ? 'PASS' : 'FAIL'}`);
|
|
2087
|
+
console.log(` Semantics: ${proof.verification.semanticPassed ? 'PASS' : 'FAIL'}`);
|
|
2088
|
+
console.log(` Tests: ${tests.total ? `${tests.passed}/${tests.total} passed` : 'none'}`);
|
|
2089
|
+
console.log(` Claims: ${resolved.verified} verified, ${resolved.declared} declared, ${resolved.unverified} UNVERIFIED${resolved.failed ? `, ${resolved.failed} FAILED` : ''} (of ${resolved.obligations.length})`);
|
|
2090
|
+
console.log(` Proof status: ${String(proof.proofStatus).toUpperCase()}${(resolved.unverified || resolved.failed) ? ' (not fully proven)' : ''}`);
|
|
2091
|
+
const fr = proof.freshness;
|
|
2092
|
+
console.log(` Bound to: commit ${fr.implementation ? fr.implementation.slice(0, 7) : 'n/a'}${fr.dependencies ? ` · deps ${fr.dependencies.hash.replace('sha256:', '').slice(0, 7)} (${fr.dependencies.file})` : ''}${fr.environment ? ` · env ${fr.environment}` : ''}`);
|
|
2093
|
+
const problems = resolved.obligations.filter((o) => o.status === 'unverified' || o.status === 'failed');
|
|
2094
|
+
if (problems.length) {
|
|
2095
|
+
console.log('');
|
|
2096
|
+
console.log(' Not proven (this is where drift hides , a claim like this never counts as proven):');
|
|
2097
|
+
for (const o of problems) console.log(` - ${o.status === 'failed' ? 'FAILED ' : 'UNVERIFIED'} ${o.kind} ${o.id}: ${o.text}`);
|
|
2098
|
+
}
|
|
2099
|
+
const outName = `${slug(ast.mission || stripSourceExt(basename(file)))}.thunder-proof.json`;
|
|
2100
|
+
const outDir = args.out && args.out !== '.intent' ? args.out : dirname(file);
|
|
2101
|
+
const outPath = join(outDir, outName);
|
|
2102
|
+
writeFileSync(outPath, JSON.stringify(proof, null, 2));
|
|
2103
|
+
console.log('');
|
|
2104
|
+
console.log(` wrote ${relative(process.cwd(), outPath)}`);
|
|
2105
|
+
process.exit(fail ? 1 : 0);
|
|
2106
|
+
return;
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
// `thunder evidence <file>` , project the intent's proof into evidence-event-v1 events for the
|
|
2110
|
+
// shared SkillsTech evidence graph (STW spine). Deterministic, offline, safe-derived; prints JSON.
|
|
2111
|
+
// The network push to the spine belongs to the org-layer/CI, not this CLI.
|
|
2112
|
+
if (cmd === 'evidence') {
|
|
2113
|
+
if (!file || !existsSync(file)) { console.error('usage: thunder evidence <file> # emit evidence-event-v1 JSON for the shared proof spine'); process.exit(2); return; }
|
|
2114
|
+
const source = readFileSync(file, 'utf8');
|
|
2115
|
+
const ast = parseIntent(source);
|
|
2116
|
+
const diagnostics = semanticDiagnostics(ast);
|
|
2117
|
+
const resolved = resolveObligations(ast);
|
|
2118
|
+
const proof = buildProof(ast, {
|
|
2119
|
+
sourceFile: basename(file),
|
|
2120
|
+
sourceHash: sha256(source),
|
|
2121
|
+
targetsRequested: ast.targets || [],
|
|
2122
|
+
targetsGenerated: [],
|
|
2123
|
+
diagnostics,
|
|
2124
|
+
generatedAt: new Date().toISOString(),
|
|
2125
|
+
});
|
|
2126
|
+
const CLAIM_MAP = { verified: 'verified', failed: 'failed', declared: 'planned', unverified: 'needs_verification' };
|
|
2127
|
+
const byId = new Map(resolved.obligations.map((o) => [o.id, o]));
|
|
2128
|
+
const applyStatus = (claim) => { const o = byId.get(claim.id); return o ? { ...claim, status: CLAIM_MAP[o.status], provenBy: o.provenBy || null } : claim; };
|
|
2129
|
+
proof.guarantees = proof.guarantees.map(applyStatus);
|
|
2130
|
+
proof.neverRules = proof.neverRules.map(applyStatus);
|
|
2131
|
+
proof.freshness = freshnessFor(file, proof, args.env);
|
|
2132
|
+
const events = toEvidenceEvents(proof);
|
|
2133
|
+
console.log(JSON.stringify(events, null, 2));
|
|
2134
|
+
return;
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
// CONFORMANCE: the same test cases run against every target. The engine defines the canonical
|
|
2138
|
+
// result each case must produce; target outputs fed via --results are graded against it.
|
|
2139
|
+
// `thunder conform <file> [--targets ts,py] [--results <json|path>] [--json]`.
|
|
2140
|
+
if (cmd === 'conform') {
|
|
2141
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
2142
|
+
let results = null;
|
|
2143
|
+
if (args.results) {
|
|
2144
|
+
try { results = existsSync(args.results) ? JSON.parse(readFileSync(args.results, 'utf8')) : JSON.parse(args.results); }
|
|
2145
|
+
catch { console.error('thunder conform: --results must be JSON of {target: {"Test / case": result}} (file path or inline)'); process.exit(2); return; }
|
|
2146
|
+
}
|
|
2147
|
+
let targets = (args.targets && args.targets.length ? args.targets : (ast.targets || [])).map((t) => canonicalTarget(t));
|
|
2148
|
+
const skippedTargets = [];
|
|
2149
|
+
// --all-targets: execute EVERY target whose toolchain is available in one pass, and show all
|
|
2150
|
+
// live targets as columns (unavailable ones stay "declared" with a skipped note).
|
|
2151
|
+
if (args.allTargets) {
|
|
2152
|
+
results = results || {};
|
|
2153
|
+
targets = Array.from(new Set([...targets, ...LIVE_TARGETS.map((t) => t.key)]));
|
|
2154
|
+
for (const t of LIVE_TARGETS) {
|
|
2155
|
+
if (!t.available()) { skippedTargets.push(t.key); continue; }
|
|
2156
|
+
const run = t.run(ast);
|
|
2157
|
+
if (run.status === 'error' && run.kind === 'missing-toolchain') skippedTargets.push(t.key);
|
|
2158
|
+
else results[t.key] = caseResultsOf(ast, run);
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
// --run <targets>: execute specific live targets (TypeScript/JS/Python/C#/Java) and grade real
|
|
2162
|
+
// outputs. A missing toolchain is skipped, leaving it "declared"; any other failure (not
|
|
2163
|
+
// translated, compile failure, crash, timeout) is graded as an error with its reason.
|
|
2164
|
+
if (args.run && args.run.length) {
|
|
2165
|
+
results = results || {};
|
|
2166
|
+
for (const rt of args.run) {
|
|
2167
|
+
if (!RUNNABLE_TARGETS.has(rt.toLowerCase())) continue;
|
|
2168
|
+
const key = canonicalTarget(rt);
|
|
2169
|
+
if (!targets.includes(key)) targets = [...targets, key]; // a target you ran is always shown
|
|
2170
|
+
const run = runLiveTarget(ast, key);
|
|
2171
|
+
if (run.status === 'error' && run.kind === 'missing-toolchain') skippedTargets.push(key);
|
|
2172
|
+
else results[key] = caseResultsOf(ast, run);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
const rep = buildConformance(ast, { targets, results });
|
|
2176
|
+
if (skippedTargets.length) rep.skipped = Array.from(new Set(skippedTargets));
|
|
2177
|
+
const bad = rep.semanticFailures > 0 || rep.failures.length > 0;
|
|
2178
|
+
if (args.evidence) {
|
|
2179
|
+
const ctx = { compilerVersion: COMPILER_VERSION, occurredAt: new Date().toISOString(), missionName: ast.mission || null, intentHash: sha256(readFileSync(file, 'utf8')) };
|
|
2180
|
+
console.log(JSON.stringify(conformToEvidence(rep, ctx), null, 2));
|
|
2181
|
+
process.exit(bad ? 1 : 0); return;
|
|
2182
|
+
}
|
|
2183
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
|
|
2184
|
+
if (!rep.total) { console.log(`thunder conform ${basename(file)}: no test cases to conform.`); return; }
|
|
2185
|
+
|
|
2186
|
+
const cap = (s) => ({ typescript: 'TypeScript', csharp: 'C#', javascript: 'JavaScript' })[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
|
|
2187
|
+
const cols = ['Semantic', ...rep.columns.map(cap)];
|
|
2188
|
+
const labelW = Math.max(12, ...rep.cases.map((c) => c.key.length));
|
|
2189
|
+
const cw = (h) => Math.max(h.length, 8);
|
|
2190
|
+
const cell = (v, w) => String(v).padEnd(w);
|
|
2191
|
+
console.log(`thunder conform ${basename(file)}: ${rep.total} case(s) · semantic + ${rep.columns.length} target(s)${rep.graded ? '' : ' (declared , provide --results to grade targets)'}`);
|
|
2192
|
+
console.log(` ${cell('', labelW)} ${cols.map((h) => cell(h, cw(h))).join(' ')}`);
|
|
2193
|
+
for (const c of rep.cases) {
|
|
2194
|
+
const sem = c.semanticPass ? 'PASS' : 'FAIL';
|
|
2195
|
+
const tcells = rep.columns.map((col) => {
|
|
2196
|
+
const s = c.targets[col].status;
|
|
2197
|
+
return cell(s === 'pass' ? 'PASS' : s === 'fail' ? 'FAIL' : s === 'error' ? 'ERROR' : '—', cw(cap(col)));
|
|
2198
|
+
});
|
|
2199
|
+
console.log(` ${cell(c.key, labelW)} ${cell(sem, cw('Semantic'))} ${tcells.join(' ')}`);
|
|
2200
|
+
}
|
|
2201
|
+
for (const f of rep.failures) {
|
|
2202
|
+
console.log('');
|
|
2203
|
+
console.log(' CONFORMANCE FAILURE');
|
|
2204
|
+
console.log(` Target: ${cap(f.target)}`);
|
|
2205
|
+
console.log(` Case: ${f.case}`);
|
|
2206
|
+
console.log(` Expected: ${f.expected}`);
|
|
2207
|
+
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}`);
|
|
2208
|
+
else console.log(` Actual: ${f.actual === null ? 'null' : f.actual}`);
|
|
2209
|
+
}
|
|
2210
|
+
if (rep.skipped && rep.skipped.length) {
|
|
2211
|
+
console.log('');
|
|
2212
|
+
console.log(` Skipped (toolchain not available, left declared): ${rep.skipped.map(cap).join(', ')}`);
|
|
2213
|
+
}
|
|
2214
|
+
process.exit(bad ? 1 : 0);
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
// Intent Runtime: SIMULATE a lifecycle against a sequence of events.
|
|
2219
|
+
if (cmd === 'simulate') {
|
|
2220
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
2221
|
+
const lcs = ast.lifecycles || [];
|
|
2222
|
+
if (!lcs.length) { console.error('intent simulate: no lifecycle in this mission'); process.exit(2); return; }
|
|
2223
|
+
const events = args.events || [];
|
|
2224
|
+
const sims = lcs.map((lc) => simulateLifecycle(lc, events));
|
|
2225
|
+
if (args.json) { console.log(JSON.stringify(sims.length === 1 ? sims[0] : sims, null, 2)); return; }
|
|
2226
|
+
for (const s of sims) {
|
|
2227
|
+
console.log(`lifecycle ${s.lifecycle}: ${s.path.join(' -> ')} (${s.valid ? 'valid' : 'INVALID'}${s.endedTerminal ? ', terminal' : ''})`);
|
|
2228
|
+
for (const st of s.steps) console.log(` ${st.ok ? 'ok ' : 'X '} ${st.from} --${st.event}--> ${st.to}${st.reason ? ` (${st.reason})` : ''}`);
|
|
2229
|
+
}
|
|
2230
|
+
process.exit(sims.some((s) => !s.valid) ? 1 : 0);
|
|
2231
|
+
return;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
// Schema migration: upgrade a persisted Intent Graph JSON to the current (or a target)
|
|
2235
|
+
// schema version, then validate the result against the canonical vocabulary.
|
|
2236
|
+
// Validate an Intent Graph against the canonical vocabulary (consumer anti-fork self-check).
|
|
2237
|
+
if (cmd === 'validate') {
|
|
2238
|
+
const raw = readFileSync(file, 'utf8');
|
|
2239
|
+
let graph;
|
|
2240
|
+
try { graph = JSON.parse(raw); } catch { console.error('intent validate: input is not valid JSON'); process.exit(2); return; }
|
|
2241
|
+
if (!graph || !Array.isArray(graph.nodes)) { console.error('intent validate: not an Intent Graph (no nodes[])'); process.exit(2); return; }
|
|
2242
|
+
const v = validateGraph(graph);
|
|
2243
|
+
if (args.json) { console.log(JSON.stringify(v, null, 2)); process.exit(v.valid ? 0 : 1); return; }
|
|
2244
|
+
console.log(`thunder validate ${basename(file)}: ${v.valid ? 'VALID' : `${v.issues.length} issue(s)`} (${v.version})`);
|
|
2245
|
+
for (const i of v.issues) console.log(` [${i.code}] ${i.message}${i.id ? ` (${i.id})` : ''}`);
|
|
2246
|
+
process.exit(v.valid ? 0 : 1);
|
|
2247
|
+
return;
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
if (cmd === 'migrate') {
|
|
2251
|
+
const raw = readFileSync(file, 'utf8');
|
|
2252
|
+
let graph;
|
|
2253
|
+
try { graph = JSON.parse(raw); } catch { console.error('thunder migrate: input is not valid JSON'); process.exit(2); return; }
|
|
2254
|
+
if (!graph || !Array.isArray(graph.nodes)) { console.error('thunder migrate: not an Intent Graph (no nodes[])'); process.exit(2); return; }
|
|
2255
|
+
let result;
|
|
2256
|
+
try { result = migrateGraph(graph, args.to ? { to: args.to } : {}); }
|
|
2257
|
+
catch (e) { console.error(`thunder migrate: ${e instanceof Error ? e.message : e}`); process.exit(2); return; }
|
|
2258
|
+
const v = validateGraph(result.graph);
|
|
2259
|
+
if (args.json) { console.log(JSON.stringify({ ...result, validation: v }, null, 2)); process.exit(v.valid ? 0 : 1); return; }
|
|
2260
|
+
console.log(`thunder migrate: ${result.from} -> ${result.to} (${result.migrated ? result.applied.length + ' step(s)' : 'already current'})`);
|
|
2261
|
+
for (const a of result.applied) console.log(` applied ${a.from} -> ${a.to}: ${a.description}`);
|
|
2262
|
+
console.log(` validation: ${v.valid ? 'OK' : `${v.issues.length} issue(s)`}`);
|
|
2263
|
+
for (const i of v.issues.slice(0, 10)) console.log(` [${i.code}] ${i.message}`);
|
|
2264
|
+
if (args.out && args.out !== '.intent') console.log(` wrote ${writeText(args.out, `${slug((graph.nodes.find((n) => n.type === 'Mission')?.title) || 'graph')}.graph.json`, JSON.stringify(result.graph, null, 2))}`);
|
|
2265
|
+
process.exit(v.valid ? 0 : 1);
|
|
2266
|
+
return;
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
// Graph -> source: regenerate .intent from an Intent Graph (a graph JSON, or an .intent
|
|
2270
|
+
// file which is parsed + built first , a normalizing round-trip).
|
|
2271
|
+
if (cmd === 'source') {
|
|
2272
|
+
const raw = readFileSync(file, 'utf8');
|
|
2273
|
+
let graph;
|
|
2274
|
+
if (file.endsWith('.json')) {
|
|
2275
|
+
try { graph = JSON.parse(raw); } catch { console.error('intent source: input .json is not valid JSON'); process.exit(2); return; }
|
|
2276
|
+
if (!graph || !Array.isArray(graph.nodes)) { console.error('intent source: JSON is not an Intent Graph (no nodes[])'); process.exit(2); return; }
|
|
2277
|
+
} else {
|
|
2278
|
+
graph = buildIntentGraph(parseIntent(raw));
|
|
2279
|
+
}
|
|
2280
|
+
const src = graphToSource(graph);
|
|
2281
|
+
if (args.out && args.out !== '.intent') {
|
|
2282
|
+
const base = (graph.nodes.find((n) => n.type === 'Mission')?.title) || basename(file).replace(/\.[^.]+$/, '');
|
|
2283
|
+
console.log(`thunder source: wrote ${writeText(args.out, `${slug(base)}.intent`, src)}`);
|
|
2284
|
+
} else {
|
|
2285
|
+
process.stdout.write(src);
|
|
2286
|
+
}
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
// Import adapters: lift an external DMN / BPMN document back into ThunderLang source.
|
|
2291
|
+
if (cmd === 'import') {
|
|
2292
|
+
const xml = readFileSync(file, 'utf8');
|
|
2293
|
+
const fmt = args.format || detectFormat(xml);
|
|
2294
|
+
if (!fmt || !IMPORT_FORMATS.includes(fmt)) {
|
|
2295
|
+
console.error(`thunder import: could not detect format; pass --format <${IMPORT_FORMATS.join('|')}>`);
|
|
2296
|
+
process.exit(2); return;
|
|
2297
|
+
}
|
|
2298
|
+
const report = importReport(xml, fmt);
|
|
2299
|
+
if (report == null) { console.error(`thunder import: unsupported format "${fmt}"`); process.exit(2); return; }
|
|
2300
|
+
if (args.json) { console.log(JSON.stringify(report, null, 2)); return; }
|
|
2301
|
+
const src = report.source;
|
|
2302
|
+
if (args.out && args.out !== '.intent') {
|
|
2303
|
+
const base = basename(file).replace(/\.[^.]+$/, '');
|
|
2304
|
+
const p = writeText(args.out, `${slug(base)}.intent`, src);
|
|
2305
|
+
console.log(`thunder import: wrote ${p}`);
|
|
2306
|
+
} else {
|
|
2307
|
+
process.stdout.write(src.endsWith('\n') ? src : src + '\n');
|
|
2308
|
+
}
|
|
2309
|
+
// Fidelity warnings go to stderr, so stdout stays clean for piping the source.
|
|
2310
|
+
for (const w of report.warnings) console.error(`thunder import: [${w.code}] ${w.message}`);
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
// Export adapters: render decisions/lifecycles to DMN / BPMN / NuSMV (interop).
|
|
2315
|
+
if (cmd === 'export') {
|
|
2316
|
+
const fmt = args.format;
|
|
2317
|
+
if (!fmt || !EXPORT_FORMATS.includes(fmt)) {
|
|
2318
|
+
console.error(`usage: intent export <file> --format <${EXPORT_FORMATS.join('|')}> [--out <dir>]`);
|
|
2319
|
+
process.exit(2); return;
|
|
2320
|
+
}
|
|
2321
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
2322
|
+
const res = exportIntent(ast, fmt);
|
|
2323
|
+
if (args.out && args.out !== '.intent') {
|
|
2324
|
+
const name = `${slug(ast.mission || stripSourceExt(basename(file)))}.${res.ext}`;
|
|
2325
|
+
const p = writeText(args.out, name, res.content);
|
|
2326
|
+
console.log(`thunder export: wrote ${p}`);
|
|
2327
|
+
} else {
|
|
2328
|
+
process.stdout.write(res.content);
|
|
2329
|
+
}
|
|
2330
|
+
return;
|
|
2331
|
+
}
|
|
2332
|
+
|
|
2333
|
+
// Intent Atlas: the navigable/searchable whole-system map over the Intent Graph.
|
|
2334
|
+
if (cmd === 'atlas') {
|
|
2335
|
+
const root = file || '.';
|
|
2336
|
+
if (args.review || args.agentBrief || args.openthunder) {
|
|
2337
|
+
if (args.search || args.expand) throw new Error('Review mode cannot be combined with graph search or expansion.');
|
|
2338
|
+
const files = collectIntents(root).map((f) => ({ path: relative(root, f) || basename(f), source: readFileSync(f, 'utf8') }));
|
|
2339
|
+
const evidence = args.openthunder ? JSON.parse(readFileSync(args.openthunder, 'utf8')) : undefined;
|
|
2340
|
+
const review = buildReviewAtlas(files, { product: args.product, evidence });
|
|
2341
|
+
console.log(args.json ? JSON.stringify(review, null, 2) : renderReviewBrief(review));
|
|
2342
|
+
process.exitCode = reviewAtlasExitCode(review, { strict: args.strict });
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
const graphs = collectIntents(root).map((f) => buildIntentGraph(parseIntent(readFileSync(f, 'utf8'))));
|
|
2346
|
+
const atlas = buildAtlas(graphs, { product: args.product });
|
|
2347
|
+
if (args.search) {
|
|
2348
|
+
const hits = searchAtlas(atlas, args.search, { type: args.from });
|
|
2349
|
+
if (args.json) { console.log(JSON.stringify(hits, null, 2)); return; }
|
|
2350
|
+
console.log(`thunder atlas search "${args.search}": ${hits.length} hit(s)`);
|
|
2351
|
+
for (const h of hits) console.log(` ${h.type.padEnd(18)} ${h.id}${h.title ? ` , ${h.title}` : ''}`);
|
|
2352
|
+
return;
|
|
2353
|
+
}
|
|
2354
|
+
if (args.expand) {
|
|
2355
|
+
const ex = expandNode(atlas, args.expand);
|
|
2356
|
+
if (!ex) { console.error(`thunder atlas: no node "${args.expand}".`); process.exit(2); return; }
|
|
2357
|
+
if (args.json) { console.log(JSON.stringify(ex, null, 2)); return; }
|
|
2358
|
+
console.log(`${ex.node.type} ${ex.node.id}${ex.node.title ? ` , ${ex.node.title}` : ''}`);
|
|
2359
|
+
for (const e of ex.out) console.log(` -> ${e.rel.padEnd(16)} ${e.node.id}`);
|
|
2360
|
+
for (const e of ex.inbound) console.log(` <- ${e.rel.padEnd(16)} ${e.node.id}`);
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
if (args.json) { console.log(JSON.stringify(atlas, null, 2)); return; }
|
|
2364
|
+
console.log(`thunder atlas ${root}: ${atlas.overview.missions} mission(s), ${atlas.overview.nodes} node(s), ${atlas.overview.relationships} edge(s)`);
|
|
2365
|
+
console.log(` ${JSON.stringify(atlas.overview.byType)}`);
|
|
2366
|
+
for (const m of atlas.missions) console.log(` mission ${m.id}${m.title ? ` , ${m.title}` : ''}`);
|
|
2367
|
+
console.log(' expand a node: thunder atlas . --expand <id> | search: --search <query>');
|
|
2368
|
+
return;
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
// Mission Atlas index: aggregate every .intent under a directory into one inventory.
|
|
2372
|
+
if (cmd === 'index') {
|
|
2373
|
+
const root = file;
|
|
2374
|
+
let intentFiles;
|
|
2375
|
+
try {
|
|
2376
|
+
intentFiles = collectIntents(root).map((f) => ({ path: relative(root, f), source: readFileSync(f, 'utf8') }));
|
|
2377
|
+
} catch (e) {
|
|
2378
|
+
console.error(`thunder index: cannot read "${root}": ${e instanceof Error ? e.message : e}`);
|
|
2379
|
+
process.exit(2);
|
|
2380
|
+
return;
|
|
2381
|
+
}
|
|
2382
|
+
const index = buildMissionIndex(intentFiles, { product: args.product });
|
|
2383
|
+
if (args.json) { console.log(JSON.stringify(index, null, 2)); return; }
|
|
2384
|
+
console.log(`thunder index ${root}: ${index.summary.missions} mission(s)`);
|
|
2385
|
+
console.log(` ${JSON.stringify(index.summary.byArea)}`);
|
|
2386
|
+
for (const m of index.missions) {
|
|
2387
|
+
console.log(` ${m.mission.padEnd(24)} ${String(m.risk).padEnd(7)} G:${m.guarantees} N:${m.neverRules} verify:${m.verification}${m.reviewed ? ' reviewed' : ''}`);
|
|
2388
|
+
}
|
|
2389
|
+
console.log(` ${index.summary.declaredFull} declared-full, ${index.summary.declaredPartial} partial, ${index.summary.unverified} unverified, ${index.summary.highRisk} high-risk`);
|
|
2390
|
+
console.log(' note: verification is DECLARED, not proven. Test/drift status needs OpenThunder.');
|
|
2391
|
+
return;
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
// `thunder verify-diff <intent> --after <code> [--before <code>]` , the AI-loop gate: prove
|
|
2395
|
+
// deterministically which of the intent's guarantees/never-rules a code change upholds or breaks.
|
|
2396
|
+
if (cmd === 'verify-diff') {
|
|
2397
|
+
const intentText = readFileSync(file, 'utf8');
|
|
2398
|
+
if (!args.after) { console.error('usage: thunder verify-diff <intent> --after <codeFile> [--before <codeFile>] [--from <lang>]'); process.exit(2); return; }
|
|
2399
|
+
const after = readFileSync(args.after, 'utf8');
|
|
2400
|
+
const before = args.before ? readFileSync(args.before, 'utf8') : null;
|
|
2401
|
+
const language = args.from || languageForFile(args.after);
|
|
2402
|
+
const r = verifyDiff(intentText, { before, after, language });
|
|
2403
|
+
if (args.evidence) {
|
|
2404
|
+
const ctx = { compilerVersion: COMPILER_VERSION, occurredAt: new Date().toISOString(), missionName: parseIntent(intentText).mission || null, intentHash: sha256(intentText), changeHash: sha256(after) };
|
|
2405
|
+
console.log(JSON.stringify(verifyDiffToEvidence(r, ctx), null, 2));
|
|
2406
|
+
process.exit(r.ok ? 0 : 1); return;
|
|
2407
|
+
}
|
|
2408
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.ok ? 0 : 1); return; }
|
|
2409
|
+
console.log(`thunder verify-diff ${basename(file)} vs ${basename(args.after)}: ${r.verdict} (${r.blocking} blocking, ${r.summary.regressions} regression(s))`);
|
|
2410
|
+
for (const f of r.findings) {
|
|
2411
|
+
const tag = f.code === 'INTENT_VERIFY_NEVER_VIOLATED' ? 'VIOLATION' : f.regression ? 'REGRESSION' : f.level.toUpperCase();
|
|
2412
|
+
console.log(` [${tag}] ${f.message}${f.line ? ` (line ${f.line})` : ''}`);
|
|
2413
|
+
}
|
|
2414
|
+
if (r.ok) console.log(' ok the change upholds the declared contract (deterministic checks; tests + humans still own correctness).');
|
|
2415
|
+
process.exit(r.ok ? 0 : 1);
|
|
2416
|
+
return;
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
// `thunder draft --brief <json|->` , scaffold a rigorous intent draft from a structured brief,
|
|
2420
|
+
// plus a review checklist of what a human must still fill in. Prints the draft; --write saves it.
|
|
2421
|
+
if (cmd === 'draft') {
|
|
2422
|
+
const briefPath = args.brief || (cmd === 'draft' && file && file.endsWith('.json') ? file : null);
|
|
2423
|
+
if (!briefPath) { console.error('usage: intent draft --brief <brief.json|-> [--write <out.intent>]'); process.exit(2); return; }
|
|
2424
|
+
const raw = briefPath === '-' ? readFileSync(0, 'utf8') : readFileSync(briefPath, 'utf8');
|
|
2425
|
+
let brief;
|
|
2426
|
+
try { brief = JSON.parse(raw); } catch { console.error('intent draft: --brief is not valid JSON'); process.exit(2); return; }
|
|
2427
|
+
const r = draftIntent(brief);
|
|
2428
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
|
|
2429
|
+
if (args.write) { writeFileSync(args.write, r.source); console.error(`thunder draft: wrote ${args.write}`); }
|
|
2430
|
+
else process.stdout.write(r.source);
|
|
2431
|
+
if (r.review.length) { console.error('\nreview (fill these in , the draft is a proposal, not verified):'); for (const x of r.review) console.error(` - ${x.message}`); }
|
|
2432
|
+
return;
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
// `thunder guard <file>` , preview what a runtime guard compiled from this intent enforces:
|
|
2436
|
+
// which fields it redacts (secrets/PII) and which decisions it can gate at runtime.
|
|
2437
|
+
if (cmd === 'guard') {
|
|
2438
|
+
const ast = parseIntent(readFileSync(file, 'utf8'));
|
|
2439
|
+
const g = guardSummary(ast);
|
|
2440
|
+
if (args.json) { console.log(JSON.stringify(g, null, 2)); return; }
|
|
2441
|
+
console.log(`thunder guard ${basename(file)}:`);
|
|
2442
|
+
console.log(` redacts fields ${g.redactsFields.length ? g.redactsFields.join(', ') : '(none declared secret/PII)'}`);
|
|
2443
|
+
console.log(` enforces decisions ${g.enforcesDecisions.length ? g.enforcesDecisions.join(', ') : '(none)'}`);
|
|
2444
|
+
if (g.neverRules.length) { console.log(' never rules:'); for (const n of g.neverRules) console.log(` - ${n}`); }
|
|
2445
|
+
console.log(' use: import { compileGuard } from "@skillstech/thunderlang/core"');
|
|
2446
|
+
return;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// `thunder ledger <file.json>` , verify the tamper-evident chain, and explain a subject's history
|
|
2450
|
+
// (why it was built, who approved it, what was assumed/corrected/verified, which risks accepted).
|
|
2451
|
+
if (cmd === 'ledger') {
|
|
2452
|
+
if (!file) { console.error('usage: intent ledger <ledger.json> [--subject <id>] [--json]'); process.exit(2); return; }
|
|
2453
|
+
let ledger;
|
|
2454
|
+
try { ledger = JSON.parse(readFileSync(file, 'utf8')); } catch { console.error('intent ledger: not valid JSON'); process.exit(2); return; }
|
|
2455
|
+
const chain = verifyLedger(ledger);
|
|
2456
|
+
if (args.subject) {
|
|
2457
|
+
const ex = ledgerExplain(ledger, args.subject);
|
|
2458
|
+
if (args.json) { console.log(JSON.stringify({ chain, ...ex }, null, 2)); process.exit(chain.valid ? 0 : 1); return; }
|
|
2459
|
+
console.log(`thunder ledger ${basename(file)} , ${args.subject} (chain ${chain.valid ? 'VALID' : 'BROKEN'})`);
|
|
2460
|
+
if (ex.why.length) { console.log(' why built:'); for (const w of ex.why) console.log(` - ${w}`); }
|
|
2461
|
+
if (ex.approvedBy.length) console.log(` approved by: ${ex.approvedBy.join(', ')}`);
|
|
2462
|
+
if (ex.assumptions.length) console.log(` assumptions: ${ex.assumptions.length}`);
|
|
2463
|
+
if (ex.corrections.length) console.log(` corrections (inferred intent fixed): ${ex.corrections.length}`);
|
|
2464
|
+
if (ex.acceptedRisks.length) console.log(` accepted risks: ${ex.acceptedRisks.length}`);
|
|
2465
|
+
if (ex.verifications.length) console.log(` verifications: ${ex.verifications.length}`);
|
|
2466
|
+
console.log(` change history: ${ex.changeCount} entries`);
|
|
2467
|
+
process.exit(chain.valid ? 0 : 1);
|
|
2468
|
+
return;
|
|
2469
|
+
}
|
|
2470
|
+
if (args.json) { console.log(JSON.stringify(chain, null, 2)); process.exit(chain.valid ? 0 : 1); return; }
|
|
2471
|
+
const n = (ledger.entries || []).length;
|
|
2472
|
+
console.log(`thunder ledger ${basename(file)}: ${n} entr${n === 1 ? 'y' : 'ies'}, chain ${chain.valid ? 'VALID (tamper-evident)' : `BROKEN at #${chain.brokenAt} , ${chain.reason}`}`);
|
|
2473
|
+
process.exit(chain.valid ? 0 : 1);
|
|
2474
|
+
return;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
// `thunder impact <base> <proposed>` , the Simulator: estimate a change's impact BEFORE building it
|
|
2478
|
+
// , the deterministic blast radius, the risk it would introduce, contradictions, release risk.
|
|
2479
|
+
if (cmd === 'impact') {
|
|
2480
|
+
const baseArg = args._[0]; const propArg = args._[1];
|
|
2481
|
+
if (!baseArg || !propArg) { console.error('usage: intent impact <base.intent|dir> <proposed.intent|dir> [--json]'); process.exit(2); return; }
|
|
2482
|
+
const collect = (p) => (existsSync(p) && statSync(p).isDirectory() ? collectIntents(p) : [p]).map((f) => ({ file: relative(process.cwd(), f) || f, source: readFileSync(f, 'utf8') }));
|
|
2483
|
+
const r = simulateChange(collect(baseArg), collect(propArg));
|
|
2484
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.summary.safe ? 0 : 1); return; }
|
|
2485
|
+
console.log(`thunder impact: ${r.summary.safe ? 'SAFE' : 'REVIEW'} (${baseArg} -> ${propArg})`);
|
|
2486
|
+
console.log(` change touches ${r.changedNodes} node(s); ripples to ${r.deterministicImpact.total} dependent(s)`);
|
|
2487
|
+
const bt = Object.entries(r.deterministicImpact.byType);
|
|
2488
|
+
if (bt.length) console.log(' deterministic impact by type: ' + bt.map(([t, ns]) => `${ns.length} ${t}`).join(', '));
|
|
2489
|
+
if (r.ruleDerivedRisk.length) { console.log(` risk it would introduce (${r.ruleDerivedRisk.length}):`); for (const f of r.ruleDerivedRisk.slice(0, 6)) console.log(` [${f.severity}] ${f.ruleId} , ${f.detected}`); }
|
|
2490
|
+
if (r.contradictions.length) console.log(` contradictions: ${r.contradictions.length}`);
|
|
2491
|
+
if (r.releaseRisks.length) console.log(` release risk: ${r.releaseRisks.length} blocking finding(s)`);
|
|
2492
|
+
if (r.unknownImpact.length) console.log(` unknown impact: ${r.unknownImpact.length} node(s) where the ripple can't be traced deterministically`);
|
|
2493
|
+
process.exit(r.summary.safe ? 0 : 1);
|
|
2494
|
+
return;
|
|
2495
|
+
}
|
|
2496
|
+
|
|
2497
|
+
// `thunder guardian <before> <after>` , drift detection: what a change did to the intent , which
|
|
2498
|
+
// intent it affects, what risk it introduced, what must be reverified, what learning is stale.
|
|
2499
|
+
if (cmd === 'guardian') {
|
|
2500
|
+
const beforeArg = args._[0]; const afterArg = args._[1];
|
|
2501
|
+
if (!beforeArg || !afterArg) { console.error('usage: intent guardian <before.intent|dir> <after.intent|dir> [--json]'); process.exit(2); return; }
|
|
2502
|
+
const collect = (p) => (existsSync(p) && statSync(p).isDirectory() ? collectIntents(p) : [p]).map((f) => ({ file: relative(process.cwd(), f) || f, source: readFileSync(f, 'utf8') }));
|
|
2503
|
+
const r = guardianReport(collect(beforeArg), collect(afterArg));
|
|
2504
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.verdict === 'needs-attention' ? 1 : 0); return; }
|
|
2505
|
+
const c = r.changed;
|
|
2506
|
+
console.log(`thunder guardian: ${r.verdict.toUpperCase()} (${beforeArg} -> ${afterArg})`);
|
|
2507
|
+
console.log(` changed +${c.nodesAdded} / -${c.nodesRemoved} / ~${c.nodesChanged} nodes, +${c.relationshipsAdded} / -${c.relationshipsRemoved} relationships`);
|
|
2508
|
+
if (r.affectedIntent.length) console.log(` affected ${r.affectedIntent.map((n) => n.title || n.id).join(', ')}`);
|
|
2509
|
+
if (r.introducedRisk.length) { console.log(` introduced risk (${r.introducedRisk.length}):`); for (const f of r.introducedRisk.slice(0, 6)) console.log(` [${f.severity}] ${f.ruleId} , ${f.detected}`); }
|
|
2510
|
+
if (r.resolvedRisk.length) console.log(` resolved risk: ${r.resolvedRisk.length}`);
|
|
2511
|
+
if (r.mustReverify.length) { console.log(` must reverify (${r.mustReverify.length}):`); for (const m of r.mustReverify.slice(0, 6)) console.log(` ${m.type} ${m.title || m.id} , ${m.reason}`); }
|
|
2512
|
+
if (r.staleLearning.length) { console.log(' learning to refresh:'); for (const l of r.staleLearning.slice(0, 6)) console.log(` ${l.scope} , ${l.reason}`); }
|
|
2513
|
+
process.exit(r.verdict === 'needs-attention' ? 1 : 0);
|
|
2514
|
+
return;
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
// `thunder scan [dir]` , the Scanner spine: intent -> Intent IR -> explainable Fable findings ->
|
|
2518
|
+
// risk themes. Deterministic, no AI. --json for the machine report; --ir writes the merged IR.
|
|
2519
|
+
// Part 3 focused scan queries , one question each over the Intent IR + Fable findings:
|
|
2520
|
+
// `thunder risks | gaps | unverified | coverage | unknowns | contradictions [dir] [--json]`.
|
|
2521
|
+
if (VIEWS[cmd]) {
|
|
2522
|
+
const root = file || '.';
|
|
2523
|
+
const targets = existsSync(root) && statSync(root).isDirectory() ? collectIntents(root) : [root];
|
|
2524
|
+
if (!targets.length || !existsSync(targets[0])) { console.error(`thunder ${cmd}: no .intent files under ${root}`); process.exit(2); return; }
|
|
2525
|
+
const scan = scanProject(targets.map((f) => ({ file: relative(process.cwd(), f) || f, source: readFileSync(f, 'utf8') })));
|
|
2526
|
+
const v = VIEWS[cmd](scan);
|
|
2527
|
+
if (args.json) { console.log(JSON.stringify(v, null, 2)); return; }
|
|
2528
|
+
if (cmd === 'coverage') {
|
|
2529
|
+
console.log(`thunder coverage ${root}: ${v.verified}/${v.total} claims verified (${v.coverage}%)`);
|
|
2530
|
+
for (const c of v.unverified) console.log(` unverified [${c.type}] ${c.title}`);
|
|
2531
|
+
process.exit(v.coverage === 100 ? 0 : 1); return;
|
|
2532
|
+
}
|
|
2533
|
+
if (cmd === 'risks') {
|
|
2534
|
+
const s = v.bySeverity;
|
|
2535
|
+
console.log(`thunder risks ${root}: ${v.count} risk theme(s) , ${s.blocker || 0} blocker, ${s.error || 0} error, ${s.warning || 0} warning, ${s.info || 0} info`);
|
|
2536
|
+
for (const t of v.themes) console.log(` ${String(t.count).padStart(3)} ${t.category}${t.blocker ? ` (${t.blocker} blocker)` : ''}`);
|
|
2537
|
+
for (const r of v.remediationSequence.slice(0, 5)) console.log(` fix [${r.severity}] ${r.ruleId} (${r.count}x) , ${r.remediation}`);
|
|
2538
|
+
process.exit((s.blocker || 0) + (s.error || 0) === 0 ? 0 : 1); return;
|
|
2539
|
+
}
|
|
2540
|
+
// gaps / unverified / unknowns / contradictions , a uniform list
|
|
2541
|
+
console.log(`thunder ${cmd} ${root}: ${v.count}`);
|
|
2542
|
+
for (const g of v.gaps || []) console.log(` [${g.severity}] ${g.ruleId} , ${g.detected}`);
|
|
2543
|
+
for (const c of v.claims || []) console.log(` [${c.type}] ${c.title}`);
|
|
2544
|
+
for (const u of v.unknowns || []) console.log(` [${u.type}] ${u.title}${u.confidence ? ` (${u.confidence})` : ''}`);
|
|
2545
|
+
for (const c of v.conflicts || []) console.log(` [Conflict] ${c.title}`);
|
|
2546
|
+
for (const l of v.links || []) console.log(` ${l.from} ${l.type} ${l.to}`);
|
|
2547
|
+
for (const f of v.findings || []) console.log(` ${f.ruleId} , ${f.detected}`);
|
|
2548
|
+
process.exit(v.count === 0 ? 0 : 1);
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
if (cmd === 'scan') {
|
|
2553
|
+
const root = file || '.';
|
|
2554
|
+
const targets = existsSync(root) && statSync(root).isDirectory() ? collectIntents(root) : [root];
|
|
2555
|
+
const result = scanProject(targets.map((f) => ({ file: relative(process.cwd(), f) || f, source: readFileSync(f, 'utf8') })));
|
|
2556
|
+
if (args.ir) { writeFileSync(args.ir, JSON.stringify(result.ir, null, 2)); console.error(`thunder scan: wrote Intent IR (${result.ir.nodes.length} nodes) to ${args.ir}`); }
|
|
2557
|
+
if (args.json) { console.log(JSON.stringify(result, null, 2)); process.exit(result.ok ? 0 : 1); return; }
|
|
2558
|
+
const s = result.bySeverity;
|
|
2559
|
+
console.log(`thunder scan ${root}: ${result.totals.findings} finding(s) across ${result.totals.missions} mission(s) in ${result.totals.files} file(s)`);
|
|
2560
|
+
console.log(` severity ${s.blocker} blocker, ${s.error} error, ${s.warning} warning, ${s.info} info , Intent IR: ${result.ir.nodes.length} nodes`);
|
|
2561
|
+
if (result.risks.length) {
|
|
2562
|
+
console.log(' risk themes:');
|
|
2563
|
+
for (const r of result.risks) console.log(` ${String(r.count).padStart(3)} ${r.category}${r.blocker ? ` (${r.blocker} blocker)` : ''}`);
|
|
2564
|
+
}
|
|
2565
|
+
if (result.remediationSequence.length) {
|
|
2566
|
+
console.log(' highest-impact remediation first:');
|
|
2567
|
+
for (const r of result.remediationSequence.slice(0, 5)) console.log(` [${r.severity}] ${r.ruleId} (${r.count}x) , ${r.remediation}`);
|
|
2568
|
+
}
|
|
2569
|
+
process.exit(result.ok ? 0 : 1);
|
|
2570
|
+
return;
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
// `thunder report [dir]` , a repo-wide intent health summary (aggregates every .intent file).
|
|
2574
|
+
// Distinct from `check` (pass/fail gate): counts by severity + area, top codes, and coverage.
|
|
2575
|
+
if (cmd === 'report') {
|
|
2576
|
+
const root = file || '.';
|
|
2577
|
+
const targets = existsSync(root) && statSync(root).isDirectory() ? collectIntents(root) : [root];
|
|
2578
|
+
const rep = buildReport(targets.map((f) => ({ file: relative(process.cwd(), f) || f, source: readFileSync(f, 'utf8') })));
|
|
2579
|
+
if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(0); return; }
|
|
2580
|
+
const c = rep.coverage;
|
|
2581
|
+
console.log(`thunder report ${root}: ${rep.totals.missions} mission(s) in ${rep.totals.files} file(s), ${rep.totals.diagnostics} diagnostic(s)`);
|
|
2582
|
+
console.log(` severity ${rep.bySeverity.blocker} blocker, ${rep.bySeverity.error} error, ${rep.bySeverity.warning} warning, ${rep.bySeverity.info} info`);
|
|
2583
|
+
console.log(' coverage '
|
|
2584
|
+
+ `guarantees verified ${c.guaranteesVerified}/${c.guarantees}${c.guaranteeVerifyRate != null ? ` (${c.guaranteeVerifyRate}%)` : ''}, `
|
|
2585
|
+
+ `missions with tests ${c.missionsWithTests}/${rep.totals.missions}${c.testCoverageRate != null ? ` (${c.testCoverageRate}%)` : ''}, `
|
|
2586
|
+
+ `outcomes contracted ${c.outcomeContracts}/${c.outcomes}${c.outcomeContractRate != null ? ` (${c.outcomeContractRate}%)` : ''}`);
|
|
2587
|
+
if (rep.topCodes.length) {
|
|
2588
|
+
console.log(' top codes ' + rep.topCodes.slice(0, 5).map((t) => `${t.code} (${t.count})`).join(', '));
|
|
2589
|
+
}
|
|
2590
|
+
const worst = rep.files.filter((f) => f.error > 0 || f.warning > 0).slice(0, 8);
|
|
2591
|
+
if (worst.length) {
|
|
2592
|
+
console.log(' files needing attention:');
|
|
2593
|
+
for (const f of worst) console.log(` ${f.error ? 'ERR' : 'warn'} ${f.file} , ${f.error} error(s), ${f.warning} warning(s)`);
|
|
2594
|
+
}
|
|
2595
|
+
process.exit(0);
|
|
2596
|
+
return;
|
|
2597
|
+
}
|
|
2598
|
+
|
|
2599
|
+
// `thunder check <file|dir> --format sarif` emits a SARIF 2.1.0 log so ThunderLang
|
|
2600
|
+
// diagnostics show up natively in GitHub/GitLab code scanning and SARIF-aware IDEs.
|
|
2601
|
+
// This is a REPORT (exit 0); gate the build with a plain `thunder check .` step.
|
|
2602
|
+
if (cmd === 'check' && args.format === 'sarif') {
|
|
2603
|
+
const targets = existsSync(file) && statSync(file).isDirectory() ? collectIntents(file) : [file];
|
|
2604
|
+
const reports = targets.map((f) => {
|
|
2605
|
+
const a = parseIntent(readFileSync(f, 'utf8'));
|
|
2606
|
+
let diags = semanticDiagnostics(a);
|
|
2607
|
+
if (a.waivers && a.waivers.length) {
|
|
2608
|
+
const now = args.now || null;
|
|
2609
|
+
diags = [...applyWaivers(diags, a.waivers, { now }).diagnostics, ...governanceDiagnostics(a.waivers, diags, { now })];
|
|
2610
|
+
}
|
|
2611
|
+
return { file: relative(process.cwd(), f) || f, diagnostics: diags.filter((d) => !d.waived) };
|
|
2612
|
+
});
|
|
2613
|
+
console.log(JSON.stringify(toSarif(reports, { version: COMPILER_VERSION }), null, 2));
|
|
2614
|
+
return;
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
// `thunder check <dir>` recurses and gates every .intent file (self-contained CI, no
|
|
2618
|
+
// wrapper script needed). Errors fail the run; warnings do not.
|
|
2619
|
+
if (cmd === 'check' && existsSync(file) && statSync(file).isDirectory()) {
|
|
2620
|
+
const files = collectIntents(file);
|
|
2621
|
+
const reports = files.map((f) => {
|
|
2622
|
+
const a = parseIntent(readFileSync(f, 'utf8'));
|
|
2623
|
+
let diags = semanticDiagnostics(a);
|
|
2624
|
+
if (a.waivers && a.waivers.length) {
|
|
2625
|
+
const now = args.now || null;
|
|
2626
|
+
diags = [...applyWaivers(diags, a.waivers, { now }).diagnostics, ...governanceDiagnostics(a.waivers, diags, { now })];
|
|
2627
|
+
}
|
|
2628
|
+
const errors = diags.filter((d) => d.level === 'error' && !d.waived).length;
|
|
2629
|
+
return { file: relative(file, f) || f, mission: a.mission || null, errors, warnings: diags.filter((d) => d.level === 'warning' && !d.waived).length, ok: errors === 0 };
|
|
2630
|
+
});
|
|
2631
|
+
const failed = reports.filter((r) => !r.ok);
|
|
2632
|
+
if (args.json) {
|
|
2633
|
+
console.log(JSON.stringify({ schema: 'intent-check-batch-v1', root: file, total: reports.length, failed: failed.length, ok: failed.length === 0, files: reports }, null, 2));
|
|
2634
|
+
process.exit(failed.length ? 1 : 0);
|
|
2635
|
+
}
|
|
2636
|
+
console.log(`thunder check ${file}: ${reports.length - failed.length}/${reports.length} passed`);
|
|
2637
|
+
for (const r of reports) console.log(` ${r.ok ? 'ok ' : 'ERR'} ${r.file}${r.errors ? ` , ${r.errors} error(s)` : ''}${r.warnings ? ` (${r.warnings} warning(s))` : ''}`);
|
|
2638
|
+
process.exit(failed.length ? 1 : 0);
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
// `thunder edit <file>` , apply structural field edits (intent-patch-v1) to the source,
|
|
2642
|
+
// preserving comments + formatting. Edits come from --edits <json|-> and/or convenience
|
|
2643
|
+
// flags. Prints the result to stdout, or --write applies it in place.
|
|
2644
|
+
if (cmd === 'edit') {
|
|
2645
|
+
const src = readFileSync(file, 'utf8');
|
|
2646
|
+
const edits = [];
|
|
2647
|
+
if (args.edits) {
|
|
2648
|
+
const raw = args.edits === '-' ? readFileSync(0, 'utf8') : readFileSync(args.edits, 'utf8');
|
|
2649
|
+
let parsed;
|
|
2650
|
+
try { parsed = JSON.parse(raw); } catch { console.error('intent edit: --edits is not valid JSON'); process.exit(2); return; }
|
|
2651
|
+
if (!Array.isArray(parsed)) { console.error('intent edit: --edits must be a JSON array of edit ops'); process.exit(2); return; }
|
|
2652
|
+
edits.push(...parsed);
|
|
2653
|
+
}
|
|
2654
|
+
if (args.setGoal) edits.push({ op: 'setField', field: 'goal', value: args.setGoal });
|
|
2655
|
+
for (const s of args.addGuarantee || []) edits.push({ op: 'addGuarantee', statement: s });
|
|
2656
|
+
for (const s of args.addNever || []) edits.push({ op: 'addNever', statement: s });
|
|
2657
|
+
for (const m of args.removeGuarantee || []) edits.push({ op: 'removeGuarantee', match: m });
|
|
2658
|
+
for (const m of args.removeNever || []) edits.push({ op: 'removeNever', match: m });
|
|
2659
|
+
if (!edits.length) { console.error('intent edit: no edits given. Use --edits <file|-> or --set-goal/--add-guarantee/...'); process.exit(2); return; }
|
|
2660
|
+
|
|
2661
|
+
const result = applyEdits(src, edits);
|
|
2662
|
+
if (args.json) { console.log(JSON.stringify({ ...result, source: undefined, applied: result.applied.length, skipped: result.skipped }, null, 2)); }
|
|
2663
|
+
for (const s of result.skipped) console.error(` skipped: ${s.reason}`);
|
|
2664
|
+
if (args.write) {
|
|
2665
|
+
if (result.source !== src.replace(/\r\n?/g, '\n')) writeFileSync(file, result.source);
|
|
2666
|
+
console.error(`thunder edit ${basename(file)}: applied ${result.applied.length}, skipped ${result.skipped.length}.`);
|
|
2667
|
+
} else if (!args.json) {
|
|
2668
|
+
process.stdout.write(result.source);
|
|
2669
|
+
}
|
|
2670
|
+
process.exit(0);
|
|
2671
|
+
return;
|
|
2672
|
+
}
|
|
2673
|
+
|
|
2674
|
+
// `thunder fmt <file|dir>` , canonical formatting (whitespace only; content + comments
|
|
2675
|
+
// preserved). Prints to stdout, or --write in place, or --check for CI (exit 1 if any
|
|
2676
|
+
// file is not already formatted).
|
|
2677
|
+
if (cmd === 'fmt') {
|
|
2678
|
+
const targets = statSync(file).isDirectory() ? collectIntents(file) : [file];
|
|
2679
|
+
const unformatted = [];
|
|
2680
|
+
let changed = 0;
|
|
2681
|
+
for (const f of targets) {
|
|
2682
|
+
const src = readFileSync(f, 'utf8');
|
|
2683
|
+
const formatted = formatSource(src);
|
|
2684
|
+
const same = src.replace(/\r\n?/g, '\n') === formatted;
|
|
2685
|
+
if (args.check) { if (!same) unformatted.push(relative('.', f) || f); continue; }
|
|
2686
|
+
if (args.write) { if (!same) { writeFileSync(f, formatted); changed++; } continue; }
|
|
2687
|
+
process.stdout.write(formatted);
|
|
2688
|
+
}
|
|
2689
|
+
if (args.check) {
|
|
2690
|
+
if (unformatted.length) { console.error(`thunder fmt --check: ${unformatted.length} file(s) not formatted:`); for (const u of unformatted) console.error(` ${u}`); process.exit(1); }
|
|
2691
|
+
console.log('thunder fmt --check: all formatted.');
|
|
2692
|
+
process.exit(0);
|
|
2693
|
+
}
|
|
2694
|
+
if (args.write) console.log(`thunder fmt: formatted ${changed} file(s), ${targets.length - changed} already clean.`);
|
|
2695
|
+
return;
|
|
2696
|
+
}
|
|
2697
|
+
|
|
2698
|
+
const { source, ast, sourceHash, sourceFile } = load(file);
|
|
2699
|
+
const generatedAt = new Date().toISOString();
|
|
2700
|
+
const diagnostics = semanticDiagnostics(ast);
|
|
2701
|
+
const outDir = join(args.out, slug(ast.mission || stripSourceExt(basename(file))));
|
|
2702
|
+
|
|
2703
|
+
// Production gate: a build --mode production refuses to proceed while an AI
|
|
2704
|
+
// implementation is not shippable. --allow-pending is for dev builds only.
|
|
2705
|
+
if (cmd === 'build' && args.mode === 'production' && ast.implementation) {
|
|
2706
|
+
const id = ast.implementation.id || slug(ast.mission || '');
|
|
2707
|
+
const pf = join(args.out, 'proofs', `${id}.json`);
|
|
2708
|
+
const proof = existsSync(pf) ? JSON.parse(readFileSync(pf, 'utf8')) : null;
|
|
2709
|
+
const st = resolveState({ ast, region: null, proof });
|
|
2710
|
+
const approvalRequired = !!ast.implementation.approval && ast.implementation.approval !== 'none';
|
|
2711
|
+
const gate = productionGate([{ ...st, id, approvalRequired }], { allowPending: args.allowPending });
|
|
2712
|
+
if (!gate.ok) {
|
|
2713
|
+
const r = gate.blocking[0];
|
|
2714
|
+
console.error(`INTENT-AI-501: production build blocked , implementation "${id}" is ${r.status}${r.reasons?.[0] ? ` (${r.reasons[0].code})` : ''}. Verify + approve, or use --allow-pending for a dev build.`);
|
|
2715
|
+
process.exit(1);
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2719
|
+
if (cmd === 'completions' || cmd === 'hover') {
|
|
2720
|
+
const [ln, coln] = (args.position || '1:1').split(':').map(Number);
|
|
2721
|
+
const out = cmd === 'completions'
|
|
2722
|
+
? getCompletions(source, { line: ln, column: coln })
|
|
2723
|
+
: getHover(source, { line: ln, column: coln });
|
|
2724
|
+
console.log(JSON.stringify(out, null, 2));
|
|
2725
|
+
return;
|
|
2726
|
+
}
|
|
2727
|
+
|
|
2728
|
+
if (cmd === 'check') {
|
|
2729
|
+
// Governance (Gap 5): waivers downgrade matching blockers to on-the-record exceptions.
|
|
2730
|
+
let diags = diagnostics;
|
|
2731
|
+
if (ast.waivers && ast.waivers.length) {
|
|
2732
|
+
const now = args.now || null;
|
|
2733
|
+
const applied = applyWaivers(diagnostics, ast.waivers, { now });
|
|
2734
|
+
const gov = governanceDiagnostics(ast.waivers, diagnostics, { now });
|
|
2735
|
+
diags = [...applied.diagnostics, ...gov];
|
|
2736
|
+
}
|
|
2737
|
+
const errors = diags.filter((d) => d.level === 'error' && !d.waived).length;
|
|
2738
|
+
if (args.json) {
|
|
2739
|
+
// Machine-readable diagnostics for editors, CI, and OpenThunder.
|
|
2740
|
+
const out = {
|
|
2741
|
+
schema: 'intent-check-v1',
|
|
2742
|
+
file: sourceFile,
|
|
2743
|
+
mission: ast.mission || null,
|
|
2744
|
+
ok: errors === 0,
|
|
2745
|
+
summary: {
|
|
2746
|
+
errors,
|
|
2747
|
+
warnings: diags.filter((d) => d.level === 'warning' && !d.waived).length,
|
|
2748
|
+
info: diags.filter((d) => d.level === 'info').length,
|
|
2749
|
+
waived: diags.filter((d) => d.waived).length,
|
|
2750
|
+
},
|
|
2751
|
+
diagnostics: diags.map((d) => ({
|
|
2752
|
+
level: d.level, code: d.code, message: d.message,
|
|
2753
|
+
...(d.why ? { why: d.why } : {}),
|
|
2754
|
+
...(d.severity ? { severity: d.severity } : {}),
|
|
2755
|
+
...(Array.isArray(d.blocks) && d.blocks.length ? { blocks: d.blocks } : {}),
|
|
2756
|
+
...(d.waived ? { waived: true, waiver: d.waiver } : {}),
|
|
2757
|
+
})),
|
|
2758
|
+
};
|
|
2759
|
+
console.log(JSON.stringify(out, null, 2));
|
|
2760
|
+
process.exit(errors > 0 ? 1 : 0);
|
|
2761
|
+
}
|
|
2762
|
+
console.log(`thunder check ${sourceFile} (mission: ${ast.mission})`);
|
|
2763
|
+
process.exit(printDiagnostics(diags) > 0 ? 1 : 0);
|
|
2764
|
+
}
|
|
2765
|
+
|
|
2766
|
+
const generated = [];
|
|
2767
|
+
// `thunder graph <file> --safe` , a display-safe intent-graph on stdout, for external viewers
|
|
2768
|
+
// (e.g. STT rendering the Intent Atlas). Strips owner/source provenance and redacts sensitive
|
|
2769
|
+
// classifications; carries no source code.
|
|
2770
|
+
if (cmd === 'graph' && args.safe) {
|
|
2771
|
+
console.log(JSON.stringify(safeGraph(buildIntentGraph(ast)), null, 2));
|
|
2772
|
+
return;
|
|
2773
|
+
}
|
|
2774
|
+
if (cmd === 'graph' || cmd === 'build') {
|
|
2775
|
+
generated.push(writeJson(outDir, 'contract-graph.json', buildContractGraph(ast, generatedAt)));
|
|
2776
|
+
generated.push(writeJson(outDir, 'architecture-graph.json', buildArchitectureGraph(ast, generatedAt)));
|
|
2777
|
+
generated.push(writeJson(outDir, 'implementation-plan.json', buildImplementationPlan(ast, generatedAt)));
|
|
2778
|
+
generated.push(writeJson(outDir, 'intent-graph.json', buildIntentGraph(ast)));
|
|
2779
|
+
}
|
|
2780
|
+
if (cmd === 'build') {
|
|
2781
|
+
generated.push(writeText(outDir, `${slug(ast.mission)}.md`, renderMarkdown(ast)));
|
|
2782
|
+
generated.push(writeText(outDir, `${slug(ast.mission)}.mmd`, renderMermaid(ast)));
|
|
2783
|
+
generated.push(writeText(outDir, `${slug(ast.mission)}.testplan.md`, renderTestplan(ast)));
|
|
2784
|
+
}
|
|
2785
|
+
if (cmd === 'proof' || cmd === 'build' || cmd === 'graph') {
|
|
2786
|
+
const proof = buildProof(ast, {
|
|
2787
|
+
sourceFile, sourceHash, generatedAt,
|
|
2788
|
+
targetsRequested: args.targets || ast.targets,
|
|
2789
|
+
targetsGenerated: generated.map((p) => p.replace(process.cwd() + '/', '')),
|
|
2790
|
+
diagnostics,
|
|
2791
|
+
});
|
|
2792
|
+
generated.push(writeJson(outDir, '.thunder-proof.json', proof));
|
|
2793
|
+
}
|
|
2794
|
+
if (!['graph', 'proof', 'build'].includes(cmd)) {
|
|
2795
|
+
console.error(`unknown command: ${cmd}`);
|
|
2796
|
+
process.exit(2);
|
|
2797
|
+
}
|
|
2798
|
+
console.log(`thunder ${cmd} ${sourceFile} -> ${outDir}`);
|
|
2799
|
+
for (const p of generated) console.log(` wrote ${p.replace(process.cwd() + '/', '')}`);
|
|
2800
|
+
printDiagnostics(diagnostics);
|
|
2801
|
+
}
|
|
2802
|
+
|
|
2803
|
+
/** A file that is not there is said in words, never as a crash: what was looked for, where, and what to type. */
|
|
2804
|
+
function missingFile(e) {
|
|
2805
|
+
if (!e || e.code !== 'ENOENT' || !e.path) return false;
|
|
2806
|
+
const cmd = process.argv[2] ?? 'thunder';
|
|
2807
|
+
const name = relative(process.cwd(), e.path) || e.path;
|
|
2808
|
+
const lines = [`thunder ${cmd}: there is no file or folder called "${name}" here.`, `You're in: ${process.cwd()}`];
|
|
2809
|
+
let root = null;
|
|
2810
|
+
try { root = findProjectRoot(process.cwd()); } catch { /* none */ }
|
|
2811
|
+
if (root && ['run', 'test', 'build', 'check'].includes(cmd)) lines.push(`You're inside the Thunder project "${basename(root)}". Run it with: thunder ${cmd}`);
|
|
2812
|
+
else lines.push('See the main commands with: thunder help');
|
|
2813
|
+
console.error(paint(lines.join('\n'), useColor(process.stderr)));
|
|
2814
|
+
process.exitCode = 2;
|
|
2815
|
+
return true;
|
|
2816
|
+
}
|
|
2817
|
+
process.on('uncaughtException', (e) => { if (!missingFile(e)) { console.error(e); process.exitCode = 1; } });
|
|
2818
|
+
try { main(); } catch (e) { if (!missingFile(e)) throw e; }
|