@skillstech/thunderlang 0.4.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/dist/core.cjs +8389 -4510
  3. package/dist/index.cjs +7218 -3842
  4. package/package.json +1 -1
  5. package/src/anchor.d.mts +12 -0
  6. package/src/anchor.mjs +127 -0
  7. package/src/cli.mjs +234 -42
  8. package/src/codegen.mjs +27 -9
  9. package/src/core.d.ts +19 -0
  10. package/src/core.mjs +16 -0
  11. package/src/emit.mjs +1 -1
  12. package/src/expr.mjs +42 -1
  13. package/src/human-contract.d.mts +20 -0
  14. package/src/human-contract.mjs +213 -0
  15. package/src/index.d.ts +23 -0
  16. package/src/index.mjs +11 -0
  17. package/src/lift.mjs +7 -0
  18. package/src/mcp.mjs +139 -54
  19. package/src/obligations.d.mts +9 -0
  20. package/src/obligations.mjs +35 -0
  21. package/src/plain-contract.d.mts +30 -0
  22. package/src/plain-contract.mjs +339 -0
  23. package/src/promote.d.mts +6 -0
  24. package/src/promote.mjs +179 -0
  25. package/src/read-repo-fs.mjs +29 -0
  26. package/src/read-repo.d.mts +21 -0
  27. package/src/read-repo.mjs +139 -0
  28. package/src/read.d.mts +29 -0
  29. package/src/read.mjs +1620 -0
  30. package/src/review-atlas.d.mts +19 -0
  31. package/src/review-atlas.mjs +136 -0
  32. package/src/steps.d.mts +2 -0
  33. package/src/steps.mjs +297 -0
  34. package/src/target-elixir.mjs +79 -0
  35. package/src/target-go.mjs +95 -0
  36. package/src/target-kotlin.mjs +91 -0
  37. package/src/target-rust.mjs +99 -0
  38. package/src/target-scala.mjs +93 -0
  39. package/src/target-types.mjs +97 -0
  40. package/src/target-util.mjs +1 -59
  41. package/src/testing.mjs +12 -9
  42. package/src/thunder-repo.mjs +96 -0
  43. package/src/translate.d.mts +5 -0
  44. package/src/translate.mjs +126 -0
  45. package/src/write.d.mts +24 -0
  46. package/src/write.mjs +263 -0
package/src/core.d.ts CHANGED
@@ -6,6 +6,12 @@
6
6
 
7
7
  // The canonical hash (byte-identical to node:crypto).
8
8
  export { sha256, sha256hex } from './index';
9
+ export { runTests, TEST_SCHEMA, TestReport, resolveObligations, ObligationResolution } from './index';
10
+ export { HumanContractPreview, compileHumanContract, previewHumanContract, renderHumanContract, renderExampleTable } from './human-contract.mjs';
11
+ export { ANCHOR_SCHEMA, spanRange, spanText, replaceSpan, editStep, anchorReport } from './anchor.mjs';
12
+ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
13
+ export { STEPS_SCHEMA, classifyStatement } from './steps.mjs';
14
+ export { PLAIN_SCHEMA, PlainModel, PlainPreview, PlainExplanation, parsePlainContract, renderPlainContract, plainToThunder, compilePlainContract, previewPlainContract, explainPlain } from './plain-contract.mjs';
9
15
 
10
16
  // Parser + graph + in-memory compile.
11
17
  export {
@@ -33,6 +39,7 @@ export {
33
39
  } from './index';
34
40
 
35
41
  // Intent Atlas + navigation.
42
+ export { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode, REVIEW_ATLAS_SCHEMA, ReviewFile, ReviewStatus, ReviewAtlasRow, ReviewAtlas } from './review-atlas.mjs';
36
43
  export {
37
44
  ATLAS_SCHEMA, IntentAtlas, buildAtlas, atlasNode, expandNode, searchAtlas,
38
45
  } from './index';
@@ -97,3 +104,15 @@ export {
97
104
  export {
98
105
  analyzeStyle, styleDiagnostics, toDesignTokens, toCss, STYLE_SCHEMA, DESIGN_TOKENS_SCHEMA,
99
106
  } from './index';
107
+
108
+ // Decisions -> readable typed source in six languages.
109
+ export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
110
+ export type { TranslateLanguage } from './translate.mjs';
111
+
112
+ // Read code you don't know.
113
+ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from './read.mjs';
114
+ export type { Reading, ReadItem, ReadKind } from './read.mjs';
115
+ export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
116
+ export type { RepoItem, RepoFacet, RepoReading, RepoFilter } from './read-repo.mjs';
117
+ export { promoteDecision, PROMOTE_SCHEMA } from './promote.mjs';
118
+ export type { Promotion } from './promote.mjs';
package/src/core.mjs CHANGED
@@ -6,6 +6,11 @@
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';
10
+ export { ANCHOR_SCHEMA, spanRange, spanText, replaceSpan, editStep, anchorReport } from './anchor.mjs';
11
+ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
12
+ export { STEPS_SCHEMA, classifyStatement } from './steps.mjs';
13
+ export { PLAIN_SCHEMA, parsePlainContract, renderPlainContract, plainToThunder, compilePlainContract, previewPlainContract, explainPlain } from './plain-contract.mjs';
9
14
 
10
15
  // Classification model (observed/inferred/proposed/... + isFactual). Node-free.
11
16
  export { CLASSIFICATIONS, CONFIDENCE, UNSETTLED, classify, isFactual, BLOCKABLE_PHASES } from './classification.mjs';
@@ -75,6 +80,7 @@ export { toFinding, universalPack, RISK_CATEGORIES, FABLE_SCHEMA } from './fable
75
80
  export { VIEW_SCHEMA, VIEWS, coverageView, unverifiedView, gapsView, risksView, unknownsView, contradictionsView } from './scan-queries.mjs';
76
81
  // Intent Atlas (whole-system map) + navigation primitives.
77
82
  export { buildAtlas, atlasNode, expandNode, searchAtlas, ATLAS_SCHEMA } from './intent-atlas.mjs';
83
+ export { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode, REVIEW_ATLAS_SCHEMA } from './review-atlas.mjs';
78
84
  // Intent Lens: Intent Scope + Focus Graph + Intent Brief (a focused subgraph of the Atlas).
79
85
  export { FOCUS_SCHEMA, SCOPE_TYPES, FOCUS_REASONS, makeScope, buildFocusGraph, intentBrief } from './focus.mjs';
80
86
  // Comprehension Contract: the C0..C7 understanding level (browser-safe; every product reads it).
@@ -90,3 +96,13 @@ export { TWELVE_FACTOR_SCHEMA, twelveFactorReport, twelveFactorSummary } from '.
90
96
  export { diffGraphs, mergeGraphs } from './semantic-diff.mjs';
91
97
  // Graph -> source (native round-trip) so a browser editor can regenerate .intent.
92
98
  export { graphToSource, GRAPH_SOURCE_SCHEMA } from './graph-source.mjs';
99
+
100
+ export { resolveObligations } from './obligations.mjs';
101
+ export { runTests, TEST_SCHEMA } from './testing.mjs';
102
+ // Decisions -> readable typed source in six languages (browser-safe; same translators as the targets).
103
+ export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
104
+ // Read code you don't know: decisions recovered from six languages as ThunderLang + plain English.
105
+ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from './read.mjs';
106
+ // Read a whole repository (pure: the caller passes file contents) and turn a recovered decision into a contract.
107
+ export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
108
+ export { promoteDecision, PROMOTE_SCHEMA } from './promote.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.4';
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/index.d.ts CHANGED
@@ -204,6 +204,7 @@ export interface IntentGraph {
204
204
  export function buildIntentGraph(ast: IntentAst): IntentGraph;
205
205
 
206
206
  // Intent Atlas (whole-system navigable map over the graph)
207
+ export { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode, REVIEW_ATLAS_SCHEMA, ReviewFile, ReviewStatus, ReviewAtlasRow, ReviewAtlas } from './review-atlas.mjs';
207
208
  export const ATLAS_SCHEMA: string;
208
209
  export interface IntentAtlas {
209
210
  schema: string; product: string | null;
@@ -460,6 +461,17 @@ export interface TestReport {
460
461
  results: Array<{ target: string | null; case: string; kind: string; expected?: unknown; actual?: unknown; valid?: boolean; expectValid?: boolean | null; pass: boolean; error?: string; note?: string }>;
461
462
  }
462
463
  export function runTests(ast: IntentAst): TestReport;
464
+ export interface ObligationResolution {
465
+ kind: 'guarantee' | 'prohibition'; id?: string; text: string;
466
+ status: 'verified' | 'failed' | 'declared' | 'unverified';
467
+ verify: string[]; kinds: string[]; provenBy: string | null;
468
+ evidence: Array<{ name: string; pass: boolean | null; cases: number }>;
469
+ unresolved: string[];
470
+ }
471
+ export function resolveObligations(ast: IntentAst): {
472
+ obligations: ObligationResolution[]; tests: TestReport;
473
+ verified: number; failed: number; declared: number; unverified: number;
474
+ };
463
475
 
464
476
  // Outcome contracts (executable commitments)
465
477
  export const OUTCOME_SCHEMA: string;
@@ -724,3 +736,14 @@ export interface ChangeReport {
724
736
  touchedNodeIds: string[];
725
737
  }
726
738
  export function changeReport(pairs: Array<{ path: string; before: IntentGraph | null; after: IntentGraph | null }>): ChangeReport;
739
+
740
+ // Read code you don't know.
741
+ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from './read.mjs';
742
+ export type { Reading, ReadItem, ReadKind } from './read.mjs';
743
+ export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
744
+ export type { RepoItem, RepoFacet, RepoReading, RepoFilter } from './read-repo.mjs';
745
+ export function collectReadableFiles(root: string, options?: { maxFiles?: number; maxFileBytes?: number }): Array<{ path: string; source: string; size?: number }>;
746
+ export { promoteDecision, PROMOTE_SCHEMA } from './promote.mjs';
747
+ export type { Promotion } from './promote.mjs';
748
+ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
749
+ export type { ChangedCase, ChangedCases, WriteChange, RulePart } from './write.mjs';
package/src/index.mjs CHANGED
@@ -64,6 +64,7 @@ export { parseSelection, regionMetrics, selectCandidate } from './select.mjs';
64
64
  export { buildIntentGraph, INTENT_GRAPH_SCHEMA } from './intent-graph.mjs';
65
65
  // Intent Atlas , the navigable/searchable whole-system map over the graph (directive #4)
66
66
  export { buildAtlas, atlasNode, expandNode, searchAtlas, ATLAS_SCHEMA } from './intent-atlas.mjs';
67
+ export { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode, REVIEW_ATLAS_SCHEMA } from './review-atlas.mjs';
67
68
  export { diffGraphs, mergeGraphs } from './semantic-diff.mjs';
68
69
  export { CLASSIFICATIONS, CONFIDENCE, UNSETTLED, classify, isFactual, BLOCKABLE_PHASES } from './classification.mjs';
69
70
  export { composeConstraints, detectConflicts } from './conflict.mjs';
@@ -184,3 +185,13 @@ export { startLspServer } from "./lsp.mjs";
184
185
 
185
186
  // Formatter , canonical .intent formatting (whitespace only)
186
187
  export { formatSource, isFormatted } from "./format.mjs";
188
+
189
+ export { resolveObligations } from './obligations.mjs';
190
+ // Read code you don't know: one file, a whole repository, files from disk, and promotion of a recovered decision
191
+ // into a contract with edge-case examples.
192
+ export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from "./read.mjs";
193
+ export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from "./read-repo.mjs";
194
+ export { collectReadableFiles } from "./read-repo-fs.mjs";
195
+ export { promoteDecision, PROMOTE_SCHEMA } from "./promote.mjs";
196
+ // Thunder write: change a recovered rule and write exactly those characters back, verified by re-reading.
197
+ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from "./write.mjs";
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