@skillstech/thunderlang 0.4.1 → 0.5.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillstech/thunderlang",
3
- "version": "0.4.1",
3
+ "version": "0.5.2",
4
4
  "description": "Deterministic ThunderLang compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -70,11 +70,11 @@
70
70
  "homepage": "https://thunderlang.dev",
71
71
  "repository": {
72
72
  "type": "git",
73
- "url": "git+https://github.com/SkillsTechTalk/intent-language.git",
73
+ "url": "git+https://github.com/SkillsTechTalk/thunderlang.git",
74
74
  "directory": "compiler"
75
75
  },
76
76
  "bugs": {
77
- "url": "https://github.com/SkillsTechTalk/intent-language/issues"
77
+ "url": "https://github.com/SkillsTechTalk/thunderlang/issues"
78
78
  },
79
79
  "author": "Skills Tech Talk, LLC",
80
80
  "license": "Apache-2.0",
package/src/cli.mjs CHANGED
@@ -15,6 +15,12 @@
15
15
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync } from 'node:fs';
16
16
  import { basename, join, relative, dirname } from 'node:path';
17
17
  import { parseIntent, slug, subjectName, KNOWN_LENSES } from './parse.mjs';
18
+ import { previewHumanContract, renderHumanContract } from './human-contract.mjs';
19
+ import { readCode, searchReading } from './read.mjs';
20
+ import { readRepo, searchRepo, groupByFile } from './read-repo.mjs';
21
+ import { promoteDecision } from './promote.mjs';
22
+ import { collectReadableFiles } from './read-repo-fs.mjs';
23
+ import { translateDecisions } from './translate.mjs';
18
24
  import {
19
25
  buildContractGraph, buildArchitectureGraph, buildImplementationPlan,
20
26
  semanticDiagnostics, buildProof, sha256, COMPILER_VERSION,
@@ -59,6 +65,11 @@ import { runTypescriptTarget } from './target-ts.mjs';
59
65
  import { runPythonTarget, pythonAvailable } from './target-py.mjs';
60
66
  import { runCSharpTarget, csharpAvailable } from './target-cs.mjs';
61
67
  import { runJavaTarget, javaAvailable } from './target-java.mjs';
68
+ import { runGoTarget, goAvailable } from './target-go.mjs';
69
+ import { runRustTarget, rustAvailable } from './target-rust.mjs';
70
+ import { runKotlinTarget, kotlinAvailable } from './target-kotlin.mjs';
71
+ import { runScalaTarget, scalaAvailable } from './target-scala.mjs';
72
+ import { runElixirTarget, elixirAvailable } from './target-elixir.mjs';
62
73
 
63
74
  // The live-target registry: one entry per canonical target that can be compiled + executed.
64
75
  // `available()` is a (cached) toolchain probe; TypeScript/JS runs in-process so it is always live.
@@ -67,14 +78,25 @@ const LIVE_TARGETS = [
67
78
  { key: 'python', run: runPythonTarget, available: pythonAvailable },
68
79
  { key: 'csharp', run: runCSharpTarget, available: csharpAvailable },
69
80
  { key: 'java', run: runJavaTarget, available: javaAvailable },
81
+ { key: 'go', run: runGoTarget, available: goAvailable },
82
+ { key: 'rust', run: runRustTarget, available: rustAvailable },
83
+ { key: 'kotlin', run: runKotlinTarget, available: kotlinAvailable },
84
+ { key: 'scala', run: runScalaTarget, available: scalaAvailable },
85
+ { key: 'elixir', run: runElixirTarget, available: elixirAvailable },
70
86
  ];
71
87
  const LIVE_BY_KEY = new Map(LIVE_TARGETS.map((t) => [t.key, t]));
72
88
  LIVE_BY_KEY.set('javascript', LIVE_BY_KEY.get('typescript')); // js is the same in-process runner
73
89
  // All canonical targets available to run right now (used by --all-targets).
74
90
  const availableLiveTargets = () => LIVE_TARGETS.filter((t) => t.available());
75
- const RUNNABLE_TARGETS = new Set(['typescript', 'ts', 'javascript', 'js', 'python', 'py', 'csharp', 'cs', 'c#', 'java']);
91
+ const RUNNABLE_TARGETS = new Set([
92
+ 'typescript', 'ts', 'javascript', 'js', 'python', 'py', 'csharp', 'cs', 'c#', 'java',
93
+ 'go', 'golang', 'rust', 'rs', 'kotlin', 'kt', 'scala', 'sc', 'elixir', 'ex',
94
+ ]);
76
95
  // Map an alias to its canonical target key + the adapter that executes it.
77
- const TARGET_ALIASES = { ts: 'typescript', js: 'javascript', py: 'python', cs: 'csharp', 'c#': 'csharp' };
96
+ const TARGET_ALIASES = {
97
+ ts: 'typescript', js: 'javascript', py: 'python', cs: 'csharp', 'c#': 'csharp',
98
+ golang: 'go', rs: 'rust', kt: 'kotlin', sc: 'scala', ex: 'elixir',
99
+ };
78
100
  const canonicalTarget = (t) => TARGET_ALIASES[String(t).toLowerCase()] || String(t).toLowerCase();
79
101
  // Execute a live target. Returns { "Test / case": actual } or null if the target can't run
80
102
  // (e.g. the runtime/SDK is not installed). Unknown targets return null.
@@ -84,6 +106,7 @@ function runLiveTarget(ast, target) {
84
106
  }
85
107
  import { importIntent, importReport, detectFormat, IMPORT_FORMATS } from './importers.mjs';
86
108
  import { runTests } from './testing.mjs';
109
+ import { toEvidenceEvents, verifyDiffToEvidence, conformToEvidence, driftToEvidence } from './evidence.mjs';
87
110
  import { evaluateOutcomes } from './outcome.mjs';
88
111
  import { analyzeStyle } from './style.mjs';
89
112
  import { intentProofJsonSchema, validateProof } from './proof-schema.mjs';
@@ -122,6 +145,40 @@ function collectFiles(root, acc = []) {
122
145
  return acc;
123
146
  }
124
147
 
148
+ // `thunder read <dir>`: one searchable reading of a whole repository, grouped by file.
149
+ function readFolder(dir, args) {
150
+ const index = readRepo(collectReadableFiles(dir));
151
+ const items = searchRepo(index, {
152
+ query: args.search || '', kinds: args.kind || [], languages: args.langs || [],
153
+ path: args.pathPrefix || '', answer: args.answer || '', input: args.input || '',
154
+ });
155
+ if (args.json) { console.log(JSON.stringify({ ...index, items }, null, 2)); return; }
156
+ const c = index.counts;
157
+ const langs = Object.entries(index.languages).map(([l, n]) => `${l} ${n}`).join(', ') || 'none';
158
+ 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.`);
159
+ 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 ? '; ...' : ''}`);
160
+ const filtered = items.length !== index.items.length;
161
+ if (!filtered && index.answers.length) {
162
+ console.log(`\nAnswers the code gives: ${index.answers.slice(0, 12).map((a) => `${a.name} (${a.decisions.length})`).join(', ')}`);
163
+ console.log('Narrow with --answer <Outcome>, --input <name>, --search <words>, --kind, --lang, or --path.');
164
+ }
165
+ if (!items.length) { console.log('\nNothing matches. Try fewer words or fewer filters.'); return; }
166
+ const limit = Number.isFinite(args.limit) && args.limit > 0 ? args.limit : (filtered ? Infinity : 40);
167
+ let shown = 0;
168
+ for (const g of groupByFile(items)) {
169
+ if (shown >= limit) break;
170
+ console.log(`\n${g.file} (${g.language})`);
171
+ for (const it of g.items) {
172
+ if (shown++ >= limit) break;
173
+ console.log(` [${it.kind}${it.status === 'partial' ? ', partly read' : ''}] ${it.name} line ${it.line}: ${it.says}`);
174
+ if (args.inLang && it.thunder) {
175
+ for (const l of translateDecisions(parseIntent(it.thunder), args.inLang).split('\n').slice(2)) console.log(` ${l}`);
176
+ }
177
+ }
178
+ }
179
+ if (items.length > shown) console.log(`\n${items.length - Math.min(shown, items.length)} more. Narrow the search, or pass --limit ${items.length}.`);
180
+ }
181
+
125
182
  // Walk a directory for authored source files (skips the .intent/ output dir).
126
183
  function collectIntents(root, acc = []) {
127
184
  const st = statSync(root);
@@ -225,6 +282,14 @@ function parseArgs(argv) {
225
282
  else if (a === '--role') args.role = argv[++i];
226
283
  else if (a === '--note') args.note = argv[++i];
227
284
  else if (a === '--search') args.search = argv[++i];
285
+ else if (a === '--kind') args.kind = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
286
+ else if (a === '--in') args.inLang = argv[++i];
287
+ else if (a === '--answer') args.answer = argv[++i];
288
+ else if (a === '--promote') args.promote = argv[++i];
289
+ else if (a === '--input') args.input = argv[++i];
290
+ else if (a === '--lang') args.langs = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
291
+ else if (a === '--path') args.pathPrefix = argv[++i];
292
+ else if (a === '--limit') args.limit = Number(argv[++i]);
228
293
  else if (a === '--expand') args.expand = argv[++i];
229
294
  else if (a === '--now') args.now = argv[++i];
230
295
  else if (a === '--format') args.format = argv[++i];
@@ -261,6 +326,7 @@ function parseArgs(argv) {
261
326
  else if (a === '--governed') args.governed = true;
262
327
  else if (a === '--target') args.target = argv[++i];
263
328
  else if (a === '--all-targets') args.allTargets = true;
329
+ else if (a === '--evidence') args.evidence = true;
264
330
  else if (a === '--env') args.env = argv[++i];
265
331
  else if (a === '--brief') args.brief = argv[++i];
266
332
  else if (a === '--after') args.after = argv[++i];
@@ -357,7 +423,7 @@ Inspect
357
423
  Run & test
358
424
  run <file> --inputs '<json>' execute the decision(s) deterministically
359
425
  test <file> [--contracts | --properties | --scenarios | --mutate | --evals | --changed | --coverage] [--strict]
360
- test <file> --target typescript|python|csharp|java run the tests against the EXECUTED generated code
426
+ test <file> --target typescript|python|csharp|java|go|rust|kotlin|scala|elixir run the tests against the EXECUTED generated code
361
427
  test <file> --all-targets run the tests against every AVAILABLE target in one pass
362
428
  simulate <file> --events a,b,c walk the lifecycle(s) over events
363
429
  outcomes <file> evaluate outcome contracts vs delivery results
@@ -370,7 +436,9 @@ Prove & verify intent
370
436
  proof <file> the .thunder-proof.json artifact (see also: prove, which emits verdicts)
371
437
  proof --schema emit the canonical proof envelope JSON Schema (intent-proof-v1)
372
438
  verify <proof.json> [src] re-check a proof; reports STALE when impl/deps/compiler moved
373
- conform <file> [--targets a,b] [--run typescript,python,csharp,java | --all-targets] [--results <json>] conformance matrix across targets
439
+ evidence <file> emit evidence-event-v1 JSON (tool_verified) for the shared proof spine
440
+ (also: prove/verify-diff/conform/drift accept --evidence to emit their own event)
441
+ conform <file> [--targets a,b] [--run typescript,python,csharp,java,go,rust,kotlin,scala,elixir | --all-targets] [--results <json>] conformance matrix across targets
374
442
 
375
443
  Real code vs intent (drift)
376
444
  lift <file> [--from <lang>] lift source code into inferred intent
@@ -387,6 +455,12 @@ Real code vs intent (drift)
387
455
  guard <file> [--json] preview the runtime guard (redacted fields, enforced decisions)
388
456
 
389
457
  Graph & IR
458
+ human <file> [--json | --format source] experimental compact authoring and a decision reading view
459
+ read <file|dir> [--search q] [--kind decision,function,error,test] [--in <lang>] [--from <lang>] [--json]
460
+ for a folder also: [--answer <Outcome>] [--input <name>] [--lang go,rust] [--path <prefix>] [--limit n]
461
+ --promote <decision> [--out <file>] turn a recovered decision into a contract with starter examples
462
+ read code you don't know: its decision rules as ThunderLang + plain English,
463
+ optionally rewritten in a language you know (--in typescript|python|go|rust|csharp|java)
390
464
  graph <file> [--safe] the canonical Intent Graph (intent-graph-v1); --safe = display-safe on stdout
391
465
  migrate <graph.json> [--to <version>] upgrade a persisted graph
392
466
  validate <graph.json> [--json] check a graph is canonical (anti-fork)
@@ -415,6 +489,62 @@ function main() {
415
489
  console.log(HELP);
416
490
  process.exit(cmd ? 0 : 2);
417
491
  }
492
+ if (cmd === 'read') {
493
+ try {
494
+ if (!file) throw new Error('Use thunder read <file> [--search q] [--kind decision,function,error,test] [--in <lang>] [--json].');
495
+ if (statSync(file).isDirectory()) { readFolder(file, args); return; }
496
+ if (args.promote) {
497
+ const items = statSync(file).isDirectory()
498
+ ? searchRepo(readRepo(collectReadableFiles(file)), { path: args.pathPrefix || '' })
499
+ : readCode(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) }).items.map((it) => ({ ...it, file: basename(file) }));
500
+ const matches = items.filter((it) => it.kind === 'decision' && it.name === args.promote);
501
+ if (!matches.length) throw new Error(`No decision named ${args.promote}. Run thunder read ${file} --kind decision to list them.`);
502
+ if (matches.length > 1) throw new Error(`${matches.length} decisions are named ${args.promote} (${matches.map((m) => m.file).join(', ')}). Narrow with --path.`);
503
+ const p = promoteDecision(matches[0]);
504
+ if (!p.ok) throw new Error(p.reason);
505
+ const report = previewHumanContract(p.source);
506
+ if (args.out) {
507
+ writeFileSync(args.out, p.source);
508
+ console.error(`Wrote ${args.out}: ${report.tests.total} examples recording what the code does today (${report.tests.passed} pass).`);
509
+ console.error(`Next: confirm each answer with a person, then: thunder human ${args.out} --format source > ${p.name}.thunder`);
510
+ } else process.stdout.write(p.source);
511
+ return;
512
+ }
513
+ const reading = readCode(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) });
514
+ const items = searchReading(reading, { query: args.search || '', kinds: args.kind || [] });
515
+ if (args.json) { console.log(JSON.stringify({ ...reading, items }, null, 2)); return; }
516
+ const c = reading.counts;
517
+ 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.`);
518
+ if (!items.length) console.log('\nNothing matches. Try fewer words or remove --kind.');
519
+ for (const it of items) {
520
+ console.log(`\n[${it.kind}${it.status === 'partial' ? ', partly read' : ''}] ${it.name} (line ${it.line})`);
521
+ console.log(` ${it.says}`);
522
+ if (it.thunder) {
523
+ console.log('');
524
+ for (const l of it.thunder.split('\n')) console.log(` ${l}`);
525
+ if (args.inLang) {
526
+ const code = translateDecisions(parseIntent(it.thunder), args.inLang).split('\n').slice(2);
527
+ console.log(`\n In ${args.inLang}:`);
528
+ for (const l of code) console.log(` ${l}`);
529
+ }
530
+ }
531
+ for (const u of it.unread || []) console.log(` not read (line ${u.line}): ${u.text} ${u.reason}`);
532
+ }
533
+ } catch (e) { console.error(`thunder read: ${e.message}`); process.exitCode = 2; }
534
+ return;
535
+ }
536
+ if (cmd === 'human') {
537
+ try {
538
+ if (!file) throw new Error('Use thunder human <file> [--json | --format source].');
539
+ if (args.format && args.format !== 'source') throw new Error('The supported format is source; omit --format for the reading view.');
540
+ const report = previewHumanContract(readFileSync(file, 'utf8'));
541
+ if (args.json) console.log(JSON.stringify(report, null, 2));
542
+ else if (args.format === 'source') process.stdout.write(report.canonicalSource);
543
+ else console.log(renderHumanContract(report));
544
+ process.exitCode = report.tests.failed ? 1 : report.tests.total ? 0 : 2;
545
+ } catch (e) { console.error(`thunder human: ${e.message}`); process.exitCode = 2; }
546
+ return;
547
+ }
418
548
  // `schema` takes no file (it emits the canonical Intent Graph schema).
419
549
  if (cmd === 'schema') {
420
550
  const out = {
@@ -860,7 +990,7 @@ test Example
860
990
  if (!res.ok) { console.error(res.error); process.exit(1); }
861
991
  if (args.json) { console.log(JSON.stringify(res.summary, null, 2)); return; }
862
992
  if (args.out) {
863
- const p = writeText(args.out, `${slug(res.lifted.mission)}.intent`, res.intentText);
993
+ const p = writeText(args.out, `${slug(res.lifted.mission)}.thunder`, res.intentText);
864
994
  console.log(`thunder lift ${basename(file)} -> ${p.replace(process.cwd() + '/', '')}`);
865
995
  } else {
866
996
  console.log(res.intentText);
@@ -901,6 +1031,11 @@ test Example
901
1031
  const codeText = readFileSync(file, 'utf8');
902
1032
  const language = args.from && args.from !== 'repo' ? args.from : languageForFile(file);
903
1033
  const res = checkDrift(intentText, codeText, { language });
1034
+ if (args.evidence) {
1035
+ const ctx = { compilerVersion: COMPILER_VERSION, occurredAt: new Date().toISOString(), missionName: parseIntent(intentText).mission || null, intentHash: sha256(intentText), codeHash: sha256(codeText) };
1036
+ console.log(JSON.stringify(driftToEvidence(res, ctx), null, 2));
1037
+ process.exit(res.status === 'drift' ? 1 : 0); return;
1038
+ }
904
1039
  if (args.json) { console.log(JSON.stringify(res, null, 2)); }
905
1040
  else {
906
1041
  console.log(`thunder drift: ${res.status.toUpperCase()} (${res.summary.blocking} blocking)`);
@@ -1505,6 +1640,34 @@ test Example
1505
1640
  return;
1506
1641
  }
1507
1642
 
1643
+ // `thunder evidence <file>` , project the intent's proof into evidence-event-v1 events for the
1644
+ // shared SkillsTech evidence graph (STW spine). Deterministic, offline, safe-derived; prints JSON.
1645
+ // The network push to the spine belongs to the org-layer/CI, not this CLI.
1646
+ if (cmd === 'evidence') {
1647
+ if (!file || !existsSync(file)) { console.error('usage: thunder evidence <file> # emit evidence-event-v1 JSON for the shared proof spine'); process.exit(2); return; }
1648
+ const source = readFileSync(file, 'utf8');
1649
+ const ast = parseIntent(source);
1650
+ const diagnostics = semanticDiagnostics(ast);
1651
+ const resolved = resolveObligations(ast);
1652
+ const proof = buildProof(ast, {
1653
+ sourceFile: basename(file),
1654
+ sourceHash: sha256(source),
1655
+ targetsRequested: ast.targets || [],
1656
+ targetsGenerated: [],
1657
+ diagnostics,
1658
+ generatedAt: new Date().toISOString(),
1659
+ });
1660
+ const CLAIM_MAP = { verified: 'verified', failed: 'failed', declared: 'planned', unverified: 'needs_verification' };
1661
+ const byId = new Map(resolved.obligations.map((o) => [o.id, o]));
1662
+ const applyStatus = (claim) => { const o = byId.get(claim.id); return o ? { ...claim, status: CLAIM_MAP[o.status], provenBy: o.provenBy || null } : claim; };
1663
+ proof.guarantees = proof.guarantees.map(applyStatus);
1664
+ proof.neverRules = proof.neverRules.map(applyStatus);
1665
+ proof.freshness = freshnessFor(file, proof, args.env);
1666
+ const events = toEvidenceEvents(proof);
1667
+ console.log(JSON.stringify(events, null, 2));
1668
+ return;
1669
+ }
1670
+
1508
1671
  // CONFORMANCE: the same test cases run against every target. The engine defines the canonical
1509
1672
  // result each case must produce; target outputs fed via --results are graded against it.
1510
1673
  // `thunder conform <file> [--targets ts,py] [--results <json|path>] [--json]`.
@@ -1542,6 +1705,11 @@ test Example
1542
1705
  const rep = buildConformance(ast, { targets, results });
1543
1706
  if (skippedTargets.length) rep.skipped = Array.from(new Set(skippedTargets));
1544
1707
  const bad = rep.semanticFailures > 0 || rep.failures.length > 0;
1708
+ if (args.evidence) {
1709
+ const ctx = { compilerVersion: COMPILER_VERSION, occurredAt: new Date().toISOString(), missionName: ast.mission || null, intentHash: sha256(readFileSync(file, 'utf8')) };
1710
+ console.log(JSON.stringify(conformToEvidence(rep, ctx), null, 2));
1711
+ process.exit(bad ? 1 : 0); return;
1712
+ }
1545
1713
  if (args.json) { console.log(JSON.stringify(rep, null, 2)); process.exit(bad ? 1 : 0); return; }
1546
1714
  if (!rep.total) { console.log(`thunder conform ${basename(file)}: no test cases to conform.`); return; }
1547
1715
 
@@ -1752,6 +1920,11 @@ test Example
1752
1920
  const before = args.before ? readFileSync(args.before, 'utf8') : null;
1753
1921
  const language = args.from || languageForFile(args.after);
1754
1922
  const r = verifyDiff(intentText, { before, after, language });
1923
+ if (args.evidence) {
1924
+ const ctx = { compilerVersion: COMPILER_VERSION, occurredAt: new Date().toISOString(), missionName: parseIntent(intentText).mission || null, intentHash: sha256(intentText), changeHash: sha256(after) };
1925
+ console.log(JSON.stringify(verifyDiffToEvidence(r, ctx), null, 2));
1926
+ process.exit(r.ok ? 0 : 1); return;
1927
+ }
1755
1928
  if (args.json) { console.log(JSON.stringify(r, null, 2)); process.exit(r.ok ? 0 : 1); return; }
1756
1929
  console.log(`thunder verify-diff ${basename(file)} vs ${basename(args.after)}: ${r.verdict} (${r.blocking} blocking, ${r.summary.regressions} regression(s))`);
1757
1930
  for (const f of r.findings) {
package/src/core.d.ts CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  // The canonical hash (byte-identical to node:crypto).
8
8
  export { sha256, sha256hex } from './index';
9
+ export { HumanContractPreview, compileHumanContract, previewHumanContract, renderHumanContract, renderExampleTable } from './human-contract.mjs';
9
10
 
10
11
  // Parser + graph + in-memory compile.
11
12
  export {
@@ -97,3 +98,11 @@ export {
97
98
  export {
98
99
  analyzeStyle, styleDiagnostics, toDesignTokens, toCss, STYLE_SCHEMA, DESIGN_TOKENS_SCHEMA,
99
100
  } from './index';
101
+
102
+ // Decisions -> readable typed source in six languages.
103
+ export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
104
+ export type { TranslateLanguage } from './translate.mjs';
105
+
106
+ // Read code you don't know.
107
+ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from './read.mjs';
108
+ export type { Reading, ReadItem, ReadKind } from './read.mjs';
package/src/core.mjs CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  // AI-implementation helpers (unchanged , keeps existing /core consumers working).
8
8
  export * from './ai-core.mjs';
9
+ export { compileHumanContract, previewHumanContract, renderHumanContract, renderExampleTable } from './human-contract.mjs';
9
10
 
10
11
  // Classification model (observed/inferred/proposed/... + isFactual). Node-free.
11
12
  export { CLASSIFICATIONS, CONFIDENCE, UNSETTLED, classify, isFactual, BLOCKABLE_PHASES } from './classification.mjs';
@@ -90,3 +91,7 @@ export { TWELVE_FACTOR_SCHEMA, twelveFactorReport, twelveFactorSummary } from '.
90
91
  export { diffGraphs, mergeGraphs } from './semantic-diff.mjs';
91
92
  // Graph -> source (native round-trip) so a browser editor can regenerate .intent.
92
93
  export { graphToSource, GRAPH_SOURCE_SCHEMA } from './graph-source.mjs';
94
+ // Decisions -> readable typed source in six languages (browser-safe; same translators as the targets).
95
+ export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
96
+ // Read code you don't know: decisions recovered from six languages as ThunderLang + plain English.
97
+ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from './read.mjs';
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '0.4.1';
33
+ export const COMPILER_VERSION = '0.5.2';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
@@ -0,0 +1,116 @@
1
+ // ThunderLang -> shared evidence graph projection.
2
+ //
3
+ // Maps ThunderLang's verification artifacts into evidence-event-v1 events for the SkillsTech proof
4
+ // spine (owned by STW: siblings emit evidence-event-v1, STW composes proof-bundle-v1). ThunderLang is
5
+ // the deterministic, machine-checked layer, so its evidence is evidenceType `tool_verified`.
6
+ //
7
+ // These projections are PURE and OFFLINE. They perform no network I/O: the transport (POST to the
8
+ // spine) belongs to the hosted org-layer / CI, never the end-user CLI, so the compiler stays
9
+ // deterministic and phone-home-free. They are also SAFE-DERIVED: events carry only ids, hashes,
10
+ // verdicts, diagnostic codes, and counts , never source code, never secret values, never claim
11
+ // statement text, never data-element contents (no finding `message`, no expected/actual values).
12
+ //
13
+ // NOTE: the evidence-event-v1 envelope below is ThunderLang's PROPOSED shape, pending STW's canonical
14
+ // schema (see the TL->STW proposal on the comms bus). Field names may adjust once STW confirms.
15
+
16
+ const COUNTED_STATUSES = ['verified', 'failed', 'planned', 'needs_verification'];
17
+ const stripHash = (h) => String(h || '').replace(/^sha256:/, '');
18
+ const short = (h, n = 16) => stripHash(h).slice(0, n);
19
+
20
+ // The shared evidence-event-v1 envelope. `ctx` carries the cross-artifact context the individual
21
+ // artifacts do not all include (missionName, intentHash, compilerVersion, occurredAt).
22
+ function envelope(eventType, evidenceId, ctx = {}, payload = {}) {
23
+ return {
24
+ schema: 'evidence-event-v1',
25
+ sourceProduct: 'thunderlang',
26
+ producer: { name: 'thunderlang', version: ctx.compilerVersion || null },
27
+ eventType,
28
+ evidenceType: 'tool_verified',
29
+ evidenceId,
30
+ occurredAt: ctx.occurredAt || null,
31
+ visibility: ctx.visibility || 'private',
32
+ subject: { missionName: ctx.missionName || null, intentHash: ctx.intentHash || null },
33
+ payload,
34
+ };
35
+ }
36
+
37
+ const safeClaim = (kind, c) => ({ id: c.id, kind, status: c.status, provenBy: c.provenBy || null });
38
+ function countByStatus(claims) {
39
+ const counts = Object.fromEntries(COUNTED_STATUSES.map((s) => [s, 0]));
40
+ for (const c of claims) if (c && Object.prototype.hasOwnProperty.call(counts, c.status)) counts[c.status]++;
41
+ return counts;
42
+ }
43
+ // Safe-derived finding: diagnostic code + level (+ flags), never the human message (which can quote code).
44
+ const safeFinding = (f) => ({ code: f.code, level: f.level, ...(f.regression !== undefined ? { regression: !!f.regression } : {}), ...(f.line !== undefined ? { line: f.line } : {}) });
45
+
46
+ // intent.proven , from an intent-proof-v1 artifact.
47
+ export function toEvidenceEvents(proof) {
48
+ if (!proof || typeof proof !== 'object') return [];
49
+ const guarantees = Array.isArray(proof.guarantees) ? proof.guarantees : [];
50
+ const neverRules = Array.isArray(proof.neverRules) ? proof.neverRules : [];
51
+ const claims = [
52
+ ...guarantees.map((c) => safeClaim('guarantee', c)),
53
+ ...neverRules.map((c) => safeClaim('prohibition', c)),
54
+ ];
55
+ const fr = proof.freshness || {};
56
+ const intentHash = proof.freshness?.intentHash || proof.sourceHash || null;
57
+ return [envelope('intent.proven', `tl-proof-${short(intentHash)}`, {
58
+ compilerVersion: proof.compilerVersion, occurredAt: proof.generatedAt, missionName: proof.missionName, intentHash,
59
+ }, {
60
+ proofStatus: proof.proofStatus || null,
61
+ total: claims.length,
62
+ counts: countByStatus(claims),
63
+ freshness: { implementation: fr.implementation || null, dependencies: fr.dependencies ? fr.dependencies.hash || null : null, environment: fr.environment || null },
64
+ claims,
65
+ })];
66
+ }
67
+
68
+ // change.gated , from a verify-diff verdict ({ verdict, ok, findings, blocking, summary }).
69
+ export function verifyDiffToEvidence(verdict, ctx = {}) {
70
+ if (!verdict || typeof verdict !== 'object') return [];
71
+ const findings = Array.isArray(verdict.findings) ? verdict.findings : [];
72
+ const id = `tl-verifydiff-${short(ctx.intentHash)}${ctx.changeHash ? `-${short(ctx.changeHash, 8)}` : ''}`;
73
+ return [envelope('change.gated', id, ctx, {
74
+ verdict: verdict.verdict || null,
75
+ ok: !!verdict.ok,
76
+ blocking: verdict.blocking || 0,
77
+ regressions: verdict.summary?.regressions ?? findings.filter((f) => f.regression).length,
78
+ findings: findings.map(safeFinding),
79
+ })];
80
+ }
81
+
82
+ // conformance.verified , from a thunder-conformance-v1 report.
83
+ export function conformToEvidence(report, ctx = {}) {
84
+ if (!report || typeof report !== 'object') return [];
85
+ const cases = Array.isArray(report.cases) ? report.cases : [];
86
+ const columns = Array.isArray(report.columns) ? report.columns : [];
87
+ // Per-target pass/fail/declared counts, derived without leaking any expected/actual values.
88
+ const targets = {};
89
+ for (const col of columns) {
90
+ const t = { pass: 0, fail: 0, declared: 0 };
91
+ for (const c of cases) { const s = c.targets?.[col]?.status; if (s === 'pass') t.pass++; else if (s === 'fail') t.fail++; else t.declared++; }
92
+ targets[col] = t;
93
+ }
94
+ return [envelope('conformance.verified', `tl-conform-${short(ctx.intentHash)}`, ctx, {
95
+ total: report.total || cases.length,
96
+ columns,
97
+ semanticFailures: report.semanticFailures || 0,
98
+ graded: !!report.graded,
99
+ targets,
100
+ // failure locations by name only (case + target), never expected/actual values.
101
+ failures: (Array.isArray(report.failures) ? report.failures : []).map((f) => ({ target: f.target, case: f.case })),
102
+ })];
103
+ }
104
+
105
+ // intent.drift , from a checkDrift report ({ status, findings, summary }).
106
+ export function driftToEvidence(report, ctx = {}) {
107
+ if (!report || typeof report !== 'object') return [];
108
+ const findings = Array.isArray(report.findings) ? report.findings : [];
109
+ const id = `tl-drift-${short(ctx.intentHash)}${ctx.codeHash ? `-${short(ctx.codeHash, 8)}` : ''}`;
110
+ return [envelope('intent.drift', id, ctx, {
111
+ status: report.status || null,
112
+ total: findings.length,
113
+ blocking: report.summary?.blocking ?? 0,
114
+ findings: findings.map(safeFinding),
115
+ })];
116
+ }
package/src/expr.mjs CHANGED
@@ -210,6 +210,13 @@ const DIALECTS = {
210
210
  csharp: { ...C_LOGIC, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `new[]{${list.join(', ')}}.Contains(${x})`, nil: 'null' },
211
211
  java: { ...C_LOGIC, eq: (a, b) => `java.util.Objects.equals(${a}, ${b})`, neq: (a, b) => `!java.util.Objects.equals(${a}, ${b})`, inList: (list, x) => `java.util.List.of(${list.join(', ')}).contains(${x})`, nil: 'null' },
212
212
  python: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => (v ? 'True' : 'False'), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(', ')}]`, nil: 'None' },
213
+ // Go has no built-in membership operator, so `in` becomes a parenthesized chain of equalities
214
+ // (an empty list is an impossible match -> false). Booleans and logic are C-family.
215
+ go: { ...C_LOGIC, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => (list.length ? `(${list.map((e) => `${x} == ${e}`).join(' || ')})` : 'false'), nil: 'nil' },
216
+ rust: { ...C_LOGIC, num: (v) => `${v}f64`, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `[${list.join(', ')}].contains(&${x})`, nil: 'Default::default()' },
217
+ kotlin: { ...C_LOGIC, num: (v) => (Number.isInteger(v) ? `${v}.0` : String(v)), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in listOf(${list.join(', ')})`, nil: 'null' },
218
+ scala: { ...C_LOGIC, eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `List(${list.join(', ')}).contains(${x})`, nil: 'null' },
219
+ elixir: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => String(v), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(', ')}]`, nil: 'nil' },
213
220
  };
214
221
 
215
222
  function renderExpr(src, inputs, D) {
@@ -227,7 +234,7 @@ function renderExpr(src, inputs, D) {
227
234
  return `(${r(n.a)} ${n.op} ${r(n.b)})`;
228
235
  case 'in': return D.inList(n.list.map(r), r(n.a));
229
236
  case 'list': return `[${n.items.map(r).join(', ')}]`;
230
- case 'lit': return typeof n.v === 'string' ? JSON.stringify(n.v) : typeof n.v === 'boolean' ? D.bool(n.v) : String(n.v);
237
+ case 'lit': return typeof n.v === 'string' ? JSON.stringify(n.v) : typeof n.v === 'boolean' ? D.bool(n.v) : (D.num ? D.num(n.v) : String(n.v));
231
238
  case 'ref': return (known.has(n.path) || known.has(n.path.split('.')[0])) ? n.path : JSON.stringify(n.path);
232
239
  default: return D.nil;
233
240
  }
@@ -235,6 +242,35 @@ function renderExpr(src, inputs, D) {
235
242
  return r(parse(tokenize(src)));
236
243
  }
237
244
 
245
+ /**
246
+ * Reprint a ThunderLang condition with only the parentheses its meaning needs, so a reading of
247
+ * generated or heavily bracketed code stays easy to read. Returns the input unchanged when it
248
+ * uses a construct this printer does not cover (lists, `in`).
249
+ */
250
+ export function simplifyExpr(src) {
251
+ const PREC = { or: 1, and: 2, not: 3, cmp: 4, arith: 5, neg: 6, lit: 7, ref: 7 };
252
+ let unsupported = false;
253
+ const p = (n, parent = 0) => {
254
+ const me = PREC[n.k];
255
+ if (me == null) { unsupported = true; return ''; }
256
+ let out;
257
+ switch (n.k) {
258
+ // `and` inside `or` keeps its parentheses: correct without them, but easy to misread.
259
+ case 'or': out = `${p(n.a, n.a.k === 'and' ? 9 : me)} or ${p(n.b, n.b.k === 'and' ? 9 : me + 0.5)}`; break;
260
+ case 'and': out = `${p(n.a, me)} and ${p(n.b, me + 0.5)}`; break;
261
+ case 'not': out = `not ${p(n.a, me)}`; break;
262
+ case 'cmp': out = `${p(n.a, me + 0.5)} ${n.op} ${p(n.b, me + 0.5)}`; break;
263
+ case 'arith': out = `${p(n.a, me)} ${n.op} ${p(n.b, me + 0.5)}`; break;
264
+ case 'neg': out = `-${p(n.a, me)}`; break;
265
+ case 'lit': out = typeof n.v === 'string' ? JSON.stringify(n.v) : String(n.v); break;
266
+ case 'ref': out = n.path; break;
267
+ }
268
+ return me < parent ? `(${out})` : out;
269
+ };
270
+ const text = p(parse(tokenize(src)));
271
+ return unsupported ? src : text;
272
+ }
273
+
238
274
  /**
239
275
  * Render a `when` condition as an equivalent expression in a target language, for code generation.
240
276
  * Input names render as identifiers; any other bare token is an enum literal (a string). Reuses
@@ -247,3 +283,8 @@ export const exprToJs = (src, opts = {}) => exprToCode(src, { ...opts, dialect:
247
283
  export const exprToCSharp = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'csharp' });
248
284
  export const exprToJava = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'java' });
249
285
  export const exprToPython = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'python' });
286
+ export const exprToGo = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'go' });
287
+ export const exprToRust = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'rust' });
288
+ export const exprToKotlin = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'kotlin' });
289
+ export const exprToScala = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'scala' });
290
+ export const exprToElixir = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'elixir' });
@@ -0,0 +1,20 @@
1
+ export interface HumanContractPreview {
2
+ schema: 'thunder-human-preview-v1';
3
+ experimental: true;
4
+ origin: 'inferred-code' | 'human-v1' | 'thunderlang';
5
+ mission?: string;
6
+ purpose?: string;
7
+ canonicalSource: string;
8
+ signatureInputs: Array<{ name: string; type?: string }>;
9
+ sourceReferences: string[];
10
+ needsReview: string[];
11
+ unknowns: string[];
12
+ decisions: Array<{ name: string; inputs: string[]; order: string; rules: Array<{ condition: string; readAs: string; outcome: unknown }>; otherwise: unknown }>;
13
+ tests: { total: number; passed: number; failed: number; results: Array<{ target: string; case: string; given: Record<string, string>; pass: boolean; expected: unknown; actual: unknown; error?: string; note?: string }> };
14
+ application: 'not_checked';
15
+ limitations: string[];
16
+ }
17
+ export function compileHumanContract(source: string): string;
18
+ export function previewHumanContract(source: string): HumanContractPreview;
19
+ export function renderHumanContract(report: HumanContractPreview): string;
20
+ export function renderExampleTable(inputs: string[], rows: Array<{ case: string; given: Record<string, string>; expected: unknown; actual?: unknown; status: string }>): string;