@skillstech/thunderlang 0.4.2 → 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.2",
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",
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.
@@ -123,6 +145,40 @@ function collectFiles(root, acc = []) {
123
145
  return acc;
124
146
  }
125
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
+
126
182
  // Walk a directory for authored source files (skips the .intent/ output dir).
127
183
  function collectIntents(root, acc = []) {
128
184
  const st = statSync(root);
@@ -226,6 +282,14 @@ function parseArgs(argv) {
226
282
  else if (a === '--role') args.role = argv[++i];
227
283
  else if (a === '--note') args.note = argv[++i];
228
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]);
229
293
  else if (a === '--expand') args.expand = argv[++i];
230
294
  else if (a === '--now') args.now = argv[++i];
231
295
  else if (a === '--format') args.format = argv[++i];
@@ -359,7 +423,7 @@ Inspect
359
423
  Run & test
360
424
  run <file> --inputs '<json>' execute the decision(s) deterministically
361
425
  test <file> [--contracts | --properties | --scenarios | --mutate | --evals | --changed | --coverage] [--strict]
362
- 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
363
427
  test <file> --all-targets run the tests against every AVAILABLE target in one pass
364
428
  simulate <file> --events a,b,c walk the lifecycle(s) over events
365
429
  outcomes <file> evaluate outcome contracts vs delivery results
@@ -374,7 +438,7 @@ Prove & verify intent
374
438
  verify <proof.json> [src] re-check a proof; reports STALE when impl/deps/compiler moved
375
439
  evidence <file> emit evidence-event-v1 JSON (tool_verified) for the shared proof spine
376
440
  (also: prove/verify-diff/conform/drift accept --evidence to emit their own event)
377
- conform <file> [--targets a,b] [--run typescript,python,csharp,java | --all-targets] [--results <json>] conformance matrix across targets
441
+ conform <file> [--targets a,b] [--run typescript,python,csharp,java,go,rust,kotlin,scala,elixir | --all-targets] [--results <json>] conformance matrix across targets
378
442
 
379
443
  Real code vs intent (drift)
380
444
  lift <file> [--from <lang>] lift source code into inferred intent
@@ -391,6 +455,12 @@ Real code vs intent (drift)
391
455
  guard <file> [--json] preview the runtime guard (redacted fields, enforced decisions)
392
456
 
393
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)
394
464
  graph <file> [--safe] the canonical Intent Graph (intent-graph-v1); --safe = display-safe on stdout
395
465
  migrate <graph.json> [--to <version>] upgrade a persisted graph
396
466
  validate <graph.json> [--json] check a graph is canonical (anti-fork)
@@ -419,6 +489,62 @@ function main() {
419
489
  console.log(HELP);
420
490
  process.exit(cmd ? 0 : 2);
421
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
+ }
422
548
  // `schema` takes no file (it emits the canonical Intent Graph schema).
423
549
  if (cmd === 'schema') {
424
550
  const out = {
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.2';
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.
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;
@@ -0,0 +1,213 @@
1
+ // Experimental authoring shorthand and a deterministic reading view. Both lower
2
+ // to the existing parser/runtime. This is not a second execution language.
3
+ import { parseIntent } from './parse.mjs';
4
+ import { compileExpr, tokenize } from './expr.mjs';
5
+ import { runTests } from './testing.mjs';
6
+
7
+ const ID = '[A-Za-z_][A-Za-z0-9_]*';
8
+ const id = new RegExp(`^${ID}$`);
9
+ const literal = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?|true|false|"[A-Za-z0-9 _-]*")$/;
10
+ const fail = (line, text) => { throw new Error(`Line ${line}: ${text}`); };
11
+
12
+ function namedCase(text, line, decision) {
13
+ const match = text.match(new RegExp(`^case "([^"\\\\]+)":\\s*\\((.*)\\)\\s*->\\s*(${ID})$`));
14
+ if (!match) fail(line, 'Use case "name": (input: value, otherInput: value) -> Outcome. Use -> for both rules and examples.');
15
+ const values = new Map();
16
+ const entries = match[2].trim().replace(/,\s*$/, '').split(',');
17
+ for (const entry of entries) {
18
+ const arg = entry.trim().match(new RegExp(`^(${ID})\\s*:\\s*(.+)$`));
19
+ if (!arg) fail(line, 'Name every example input, such as amount: 100.');
20
+ if (!decision.inputs.includes(arg[1])) fail(line, `Unknown input ${arg[1]}. Expected: ${decision.inputs.join(', ')}.`);
21
+ if (values.has(arg[1])) fail(line, `Duplicate input ${arg[1]}. Provide each input once.`);
22
+ values.set(arg[1], arg[2].trim());
23
+ }
24
+ const missing = decision.inputs.filter(input => !values.has(input));
25
+ if (missing.length) fail(line, `Missing input ${missing.join(', ')}. Missing is not the same as false.`);
26
+ return { cells: [match[1].trim(), ...decision.inputs.map(input => values.get(input)), match[3]], line };
27
+ }
28
+
29
+ /** Compile the small, explicit human-v1 subset into ordinary .thunder source. */
30
+ export function compileHumanContract(source) {
31
+ if (typeof source !== 'string' || source.length > 200000) throw new Error('A human contract must be text of at most 200 KB.');
32
+ const rows = source.split(/\r?\n/).map((text, i) => ({ text: text.trim(), indented: /^\s/.test(text), line: i + 1 }))
33
+ .filter(r => r.text && !r.text.startsWith('#'));
34
+ let mission = null, purpose = null, active = null;
35
+ const decisions = [], tables = new Map();
36
+ for (let index = 0; index < rows.length; index++) {
37
+ const row = rows[index];
38
+ const { text, line } = row;
39
+ if (!row.indented) {
40
+ active = null;
41
+ let match;
42
+ if ((match = text.match(new RegExp(`^contract (${ID})$`)))) {
43
+ if (mission || decisions.length) fail(line, 'Declare one contract before its decisions.');
44
+ mission = match[1];
45
+ } else if (text.startsWith('purpose ')) {
46
+ if (!mission || purpose) fail(line, 'Declare one purpose after the contract name.');
47
+ purpose = text.slice(8).trim();
48
+ } else if ((match = text.match(new RegExp(`^decision (${ID})\\(([^)]*)\\)$`)))) {
49
+ const signature = match[2].split(',').map(x => x.trim().match(new RegExp(`^(${ID})(?:\\s*:\\s*(number|boolean|string))?$`)));
50
+ if (signature.some(input => !input)) fail(line, 'Use input names, optionally typed as number, boolean, or string.');
51
+ const inputs = signature.map(input => input[1]);
52
+ const inputTypes = Object.fromEntries(signature.filter(input => input[2]).map(input => [input[1], input[2]]));
53
+ if (!mission || !purpose) fail(line, 'Start with contract and purpose before a decision.');
54
+ if (!inputs.length || inputs.some(x => !id.test(x) || ['case', 'expect', 'true', 'false', 'and', 'or', 'not', 'in'].includes(x)) || new Set(inputs).size !== inputs.length) fail(line, 'Use unique input names, such as decision RefundPolicy(amount, withinWindow).');
55
+ if (decisions.some(d => d.name === match[1])) fail(line, 'Decision names must be unique.');
56
+ active = { kind: 'decision', name: match[1], inputs, inputTypes, rules: [], otherwise: null, line };
57
+ decisions.push(active);
58
+ } else if ((match = text.match(new RegExp(`^examples (${ID})$`)))) {
59
+ if (tables.has(match[1]) || !decisions.some(d => d.name === match[1])) fail(line, 'Examples must name one preceding decision exactly, with one examples block per decision.');
60
+ active = { kind: 'examples', name: match[1], rows: [], format: null, line };
61
+ tables.set(match[1], active);
62
+ } else fail(line, 'Expected contract, purpose, decision Name(inputs), or examples Name. This preview does not guess unknown syntax.');
63
+ } else if (active?.kind === 'decision') {
64
+ let match;
65
+ if ((match = text.match(new RegExp(`^when (.+) -> (${ID})$`)))) {
66
+ if (active.otherwise) fail(line, 'Put conditional rules before otherwise.');
67
+ try {
68
+ compileExpr(match[1]);
69
+ for (const token of tokenize(match[1])) {
70
+ if (token.t === 'id' && !active.inputs.includes(token.v)) fail(line, `Unknown input ${token.v}. Declare it, or quote it if it is a text value.`);
71
+ if (token.t === 'num' && !Number.isFinite(token.v)) fail(line, 'Use a finite number in the condition.');
72
+ }
73
+ } catch (e) { fail(line, e.message); }
74
+ active.rules.push({ condition: match[1], result: match[2], line });
75
+ } else if ((match = text.match(new RegExp(`^otherwise -> (${ID})$`)))) {
76
+ if (active.otherwise) fail(line, 'Use one otherwise result.');
77
+ active.otherwise = match[1];
78
+ } else fail(line, 'Use when <condition> -> Outcome or otherwise -> Outcome.');
79
+ } else if (active?.kind === 'examples') {
80
+ const format = text.startsWith('|') ? 'table' : 'named';
81
+ if (active.format && active.format !== format) fail(line, 'Use named cases or a table within one examples block, not both.');
82
+ active.format = format;
83
+ if (format === 'table') {
84
+ if (!text.endsWith('|')) fail(line, 'Write an examples table row with | around every cell.');
85
+ active.rows.push({ cells: text.slice(1, -1).split('|').map(s => s.trim()), line });
86
+ } else {
87
+ let statement = text;
88
+ while (!/\)\s*(?:->|=>)/.test(statement) && index + 1 < rows.length && rows[index + 1].indented && !/^(case |\|)/.test(rows[index + 1].text)) {
89
+ statement += ` ${rows[++index].text}`;
90
+ }
91
+ active.rows.push(namedCase(statement, line, decisions.find(d => d.name === active.name)));
92
+ }
93
+ } else fail(line, 'This indented line has no decision or examples block.');
94
+ }
95
+ if (!mission || !purpose || !decisions.length) throw new Error('Include a contract, purpose, and at least one decision with examples.');
96
+ const out = [`mission ${mission}`, '', 'goal', ` ${purpose}`];
97
+ for (const d of decisions) {
98
+ if (!d.rules.length || !d.otherwise) fail(d.line, 'Each decision needs at least one when rule and an otherwise result.');
99
+ out.push('', `decision ${d.name}`, ' inputs', ...d.inputs.map(i => ` ${i}`));
100
+ d.rules.forEach((r, i) => out.push(` rule condition_${i + 1}`, ` when ${r.condition}`, ` return ${r.result}`));
101
+ out.push(' default', ` return ${d.otherwise}`);
102
+ const table = tables.get(d.name);
103
+ if (!table || !table.rows.length) fail(d.line, `Add examples ${d.name} with at least one case.`);
104
+ const expectedHeader = ['case', ...d.inputs, 'expect'];
105
+ const header = table.format === 'table' ? table.rows[0].cells : expectedHeader;
106
+ if (JSON.stringify(header) !== JSON.stringify(expectedHeader)) fail(table.rows[0].line, `Use this header: | ${expectedHeader.join(' | ')} |`);
107
+ const names = new Set();
108
+ out.push('', `test ${d.name}`);
109
+ for (const row of table.rows.slice(table.format === 'table' ? 1 : 0)) {
110
+ if (row.cells.every(c => /^:?-+:?$/.test(c))) continue; // optional Markdown separator
111
+ const [name, ...values] = row.cells;
112
+ if (row.cells.length !== header.length || !name || names.has(name)) fail(row.line, 'Use a unique case name and fill every column.');
113
+ names.add(name);
114
+ const expected = values.pop();
115
+ if (!id.test(expected)) fail(row.line, 'The expected outcome must be a named result, such as Approve or Review.');
116
+ const outcomes = [...d.rules.map(r => r.result), d.otherwise];
117
+ if (!outcomes.includes(expected)) fail(row.line, `Unknown outcome ${expected}. Use one of: ${[...new Set(outcomes)].join(', ')}.`);
118
+ values.forEach((v, i) => {
119
+ if (!literal.test(v) || (!v.startsWith('"') && !['true', 'false'].includes(v) && !Number.isFinite(Number(v)))) fail(row.line, 'Inputs must be finite numbers, true/false, or quoted simple text. Complex values need ordinary ThunderLang.');
120
+ const type = v.startsWith('"') ? 'string' : ['true', 'false'].includes(v) ? 'boolean' : 'number';
121
+ if (d.inputTypes[d.inputs[i]] && type !== d.inputTypes[d.inputs[i]]) fail(row.line, `${d.inputs[i]} expects ${d.inputTypes[d.inputs[i]]}, received ${type}. Values are not coerced.`);
122
+ });
123
+ out.push(` case ${name}`, ` given ${d.inputs.map((input, i) => `${input} ${values[i]}`).join(', ')}`, ` expect ${expected}`);
124
+ }
125
+ if (!names.size) fail(table.line, 'The table has no examples; add a row with inputs and an expected outcome.');
126
+ }
127
+ return out.join('\n') + '\n';
128
+ }
129
+
130
+ const words = s => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, ' ');
131
+ const operators = { '>=': 'is at least', '<=': 'is at most', '>': 'is greater than', '<': 'is less than', '==': 'equals', '=': 'equals', '!=': 'does not equal', '&&': 'and', '||': 'or', '!': 'not' };
132
+ function readCondition(expression) {
133
+ try { return tokenize(expression).map(t => t.t === 'str' ? JSON.stringify(t.v) : t.t === 'id' ? words(t.v) : operators[t.v] ?? String(t.v)).join(' '); }
134
+ catch { return expression; } // keep unsupported text visible, never fabricate a translation
135
+ }
136
+
137
+ // Older lifted drafts have a free-text `unknown` block; their AST only retains
138
+ // named unknowns. Preserve the source's words in this view instead of dropping
139
+ // them or rendering an empty internal record to a reader.
140
+ function readUnknowns(ast, source) {
141
+ const notes = (ast.unknowns ?? []).filter(u => u.name).map(u => u.name);
142
+ let block = false;
143
+ for (const line of source.split(/\r?\n/)) {
144
+ if (/^unknown\s*$/.test(line)) { block = true; continue; }
145
+ if (/^\S/.test(line)) block = false;
146
+ if (block && /^\s+\S/.test(line)) notes.push(line.trim());
147
+ }
148
+ return notes;
149
+ }
150
+
151
+ /** Read authored decisions. Existing files retain all content in canonicalSource;
152
+ * this view deliberately makes no claim to summarize other language constructs. */
153
+ export function previewHumanContract(source) {
154
+ const first = source.split(/\r?\n/).find(l => l.trim() && !l.trim().startsWith('#'))?.trim() ?? '';
155
+ const compact = first.startsWith('contract ');
156
+ const canonicalSource = compact ? compileHumanContract(source) : source;
157
+ const ast = parseIntent(canonicalSource);
158
+ const tests = runTests(ast);
159
+ const declared = (ast.tests ?? []).flatMap(t => t.cases);
160
+ const results = tests.results.map((r, i) => ({ ...r, given: declared[i]?.given ?? {}, pass: !!r.pass && !r.error && !r.note && declared[i]?.expect != null }));
161
+ const passed = results.filter(r => r.pass).length;
162
+ const report = {
163
+ schema: 'thunder-human-preview-v1', experimental: true, origin: ast.lift?.inferred ? 'inferred-code' : compact ? 'human-v1' : 'thunderlang',
164
+ mission: ast.mission, purpose: ast.goal, canonicalSource,
165
+ signatureInputs: ast.inputs ?? [], sourceReferences: ast.lift?.maps_to ?? [],
166
+ needsReview: ast.lift?.needs_review ?? [], unknowns: readUnknowns(ast, canonicalSource),
167
+ decisions: (ast.decisions ?? []).map(d => ({ name: d.name, inputs: d.inputs, order: 'first matching rule wins',
168
+ rules: d.rules.map(r => ({ condition: r.when, readAs: readCondition(r.when ?? ''), outcome: r.result })), otherwise: d.default })),
169
+ tests: { total: results.length, passed, failed: results.length - passed, results },
170
+ application: 'not_checked',
171
+ limitations: ['This reading view covers authored decisions and examples. Other constructs remain in the full source.',
172
+ 'Purpose is author-stated intent, not inferred from code or established by tests.',
173
+ 'Passing examples check those contract inputs only. Use OpenThunder intent test-app to exercise the application.'],
174
+ };
175
+ return report;
176
+ }
177
+
178
+ export function renderHumanContract(report) {
179
+ const inferred = report.origin === 'inferred-code';
180
+ const out = [`${report.mission || 'Untitled contract'} (experimental reading view)`, '',
181
+ inferred ? 'Recovered from code: inferred draft, needs human review. Business purpose is not established.' : `Purpose: ${report.purpose || 'Not stated'}`];
182
+ if (inferred) {
183
+ out.push(`Candidate description: ${report.purpose || 'Not inferred'}`);
184
+ for (const ref of report.sourceReferences) out.push(`Source: ${ref}`);
185
+ if (report.signatureInputs.length) out.push(`Signature inputs: ${report.signatureInputs.map(i => `${i.name}${i.type ? ` (${i.type})` : ''}`).join(', ')}`);
186
+ if (!report.decisions.length) out.push('Behavior rules: not recovered. Inspect the original code before approving a contract.');
187
+ for (const note of report.needsReview) out.push(`Needs review: ${note}`);
188
+ for (const note of report.unknowns) out.push(`Unknown: ${note}`);
189
+ }
190
+ for (const d of report.decisions) {
191
+ out.push('', `Decision: ${words(d.name)}`, `Inputs: ${d.inputs.map(words).join(', ')}`, 'Read rules in order; the first match wins.');
192
+ d.rules.forEach((r, i) => out.push(`${i + 1}. If ${r.readAs}, choose ${r.outcome}.`));
193
+ out.push(`Otherwise choose ${d.otherwise ?? '(not stated)'}.`);
194
+ }
195
+ out.push('', `Contract examples: ${report.tests.passed}/${report.tests.total} passed. Application: not checked.`);
196
+ for (const target of new Set(report.tests.results.map(r => r.target))) {
197
+ const rows = report.tests.results.filter(r => r.target === target);
198
+ const inputs = report.decisions.find(d => d.name === target)?.inputs ?? [...new Set(rows.flatMap(r => Object.keys(r.given)))];
199
+ out.push('', `Examples: ${target}`, renderExampleTable(inputs, rows.map(r => ({ ...r, status: r.pass ? 'Passed' : 'Failed' }))));
200
+ for (const row of rows) if (row.error || row.note) out.push(`${row.case}: ${row.error || row.note}`);
201
+ }
202
+ out.push('', ...report.limitations);
203
+ return out.join('\n');
204
+ }
205
+
206
+ /** Generated presentation only. Input order comes from the decision signature. */
207
+ export function renderExampleTable(inputs, rows) {
208
+ const cell = value => String(value ?? 'Not available').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\|/g, '\\|');
209
+ const header = ['Case', ...inputs, 'Expected', 'Actual', 'Result'];
210
+ const values = rows.map(row => [row.case, ...inputs.map(input => row.given?.[input]), row.expected,
211
+ Object.prototype.hasOwnProperty.call(row, 'actual') ? row.actual : 'Not checked', row.status]);
212
+ return [header, header.map(() => '---'), ...values].map(row => `| ${row.map(cell).join(' | ')} |`).join('\n');
213
+ }
package/src/lift.mjs CHANGED
@@ -477,6 +477,13 @@ const ADAPTERS = {
477
477
  scala: extractFactsScala, sc: extractFactsScala,
478
478
  elixir: extractFactsElixir, ex: extractFactsElixir, exs: extractFactsElixir,
479
479
  };
480
+ /** Signature-level code facts (functions, errors, tests) for one source, in a supported language. */
481
+ export function extractFacts(source, language, file) {
482
+ const key = String(language).toLowerCase();
483
+ const adapter = ADAPTERS[key];
484
+ return adapter ? adapter(String(source), file || `input.${LANG_EXT[key] || 'txt'}`) : null;
485
+ }
486
+
480
487
  export const SUPPORTED_LANGUAGES = ['typescript', 'javascript', 'python', 'java', 'csharp', 'go', 'rust', 'cpp', 'php', 'ruby', 'perl', 'kotlin', 'scala', 'elixir'];
481
488
  const DYNAMIC_LANGUAGES = new Set(['perl', 'javascript', 'python', 'ruby', 'php', 'elixir']);
482
489