@skillstech/thunderlang 0.5.2 → 0.5.5

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/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,17 @@ 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 { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText } from './visual.mjs';
743
+ export { thunderizeFiles, THUNDER_TEXT_EXT } from './thunderize.mjs';
744
+ export { sameMeaning, renderSame } from './same.mjs';
745
+ export type { Reading, ReadItem, ReadKind } from './read.mjs';
746
+ export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from './read-repo.mjs';
747
+ export type { RepoItem, RepoFacet, RepoReading, RepoFilter } from './read-repo.mjs';
748
+ export function collectReadableFiles(root: string, options?: { maxFiles?: number; maxFileBytes?: number }): Array<{ path: string; source: string; size?: number }>;
749
+ export { promoteDecision, PROMOTE_SCHEMA } from './promote.mjs';
750
+ export type { Promotion } from './promote.mjs';
751
+ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
752
+ 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,16 @@ 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 { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText } from "./visual.mjs";
194
+ export { thunderizeFiles, THUNDER_TEXT_EXT } from "./thunderize.mjs";
195
+ export { sameMeaning, renderSame } from "./same.mjs";
196
+ export { readRepo, searchRepo, groupByFile, readableLanguage, READ_REPO_SCHEMA, READ_SKIP_DIRS } from "./read-repo.mjs";
197
+ export { collectReadableFiles } from "./read-repo-fs.mjs";
198
+ export { promoteDecision, PROMOTE_SCHEMA } from "./promote.mjs";
199
+ // Thunder write: change a recovered rule and write exactly those characters back, verified by re-reading.
200
+ export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from "./write.mjs";
package/src/mcp.mjs CHANGED
@@ -15,6 +15,8 @@ import { sha256 } from './hash.mjs';
15
15
  import { verifyDiff } from './verify-diff.mjs';
16
16
  import { liftSource, SUPPORTED_LANGUAGES } from './lift.mjs';
17
17
  import { runTests } from './testing.mjs';
18
+ import { resolveObligations } from './obligations.mjs';
19
+ import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
18
20
  import { evaluateDecision } from './runtime.mjs';
19
21
  import { buildIntentGraph } from './intent-graph.mjs';
20
22
  import { buildConformance } from './conformance.mjs';
@@ -34,38 +36,6 @@ const PROTOCOL_VERSION = '2024-11-05';
34
36
  const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
35
37
  const str = { type: 'string' };
36
38
 
37
- // ── prove helpers ────────────────────────────────────────────────────────────
38
- // Per-claim resolution , mirrors resolveObligations in cli.mjs (shared there by `thunder test
39
- // --contracts` and `thunder prove`) so the MCP proof and the CLI proof agree claim for claim.
40
- // States: verified (proven by a passing named test), failed (its test fails), declared (a
41
- // verification is named but not runnable in-file), unverified (nothing).
42
- function resolveObligations(ast) {
43
- const t = runTests(ast);
44
- const testPass = new Map();
45
- for (const res of (t.results || [])) {
46
- const cur = testPass.get(res.target);
47
- testPass.set(res.target, cur === undefined ? !!res.pass : cur && !!res.pass);
48
- }
49
- const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
50
- const matchTest = (verifyText) => {
51
- const v = norm(verifyText); if (!v) return null;
52
- for (const [name, pass] of testPass) { const n = norm(name); if (n && (n === v || n.includes(v) || v.includes(n))) return { name, pass }; }
53
- return null;
54
- };
55
- const build = (kind, o) => {
56
- const verify = o.verify || [];
57
- let status = 'unverified', provenBy = null;
58
- if (verify.length) {
59
- let m = null;
60
- for (const vt of verify) { const x = matchTest(vt); if (x) { m = x; if (!x.pass) break; } }
61
- if (m) { status = m.pass ? 'verified' : 'failed'; provenBy = m.name; } else status = 'declared';
62
- }
63
- return { kind, id: o.id, status, provenBy };
64
- };
65
- const obligations = [...ast.guarantees.map((g) => build('guarantee', g)), ...ast.neverRules.map((n) => build('prohibition', n))];
66
- return { obligations, tests: t, failed: obligations.filter((o) => o.status === 'failed').length };
67
- }
68
-
69
39
  // Freshness tuple , the (intent, implementation, dependencies, compiler, environment) binding
70
40
  // `thunder verify` recomputes later to mark a proof STALE. Mirrors freshnessFor in cli.mjs;
71
41
  // implementation/dependencies are read from the server's working directory when available.
@@ -90,6 +60,23 @@ function proofFreshness(proof, environment) {
90
60
 
91
61
  // Each tool is a pure function of its arguments. `run` returns a JSON-able value or a string.
92
62
  const TOOLS = [
63
+ {
64
+ name: 'intent_atlas',
65
+ description: 'Review multiple ThunderLang contracts before an AI change. Runs declared cases, ranks failed and unresolved claims, and returns source hashes plus a bounded agent brief. Optional OpenThunder intent prove JSON snapshots are compared by source hash and compiler; imported status never promotes a claim. Does not test application code.',
66
+ inputSchema: {
67
+ type: 'object', required: ['files'], properties: {
68
+ files: { type: 'array', maxItems: 100, items: { type: 'object', required: ['path', 'source'], properties: { path: str, source: str } } },
69
+ evidence: { type: 'object', description: 'Optional OpenThunder intent prove --json report' },
70
+ strict: { type: 'boolean', description: 'Require cases in every file and no unresolved evidence' },
71
+ },
72
+ },
73
+ run: ({ files, evidence, strict = false }) => {
74
+ if (!Array.isArray(files) || files.length > 100 || files.reduce((n, f) => n + (typeof f?.source === 'string' ? f.source.length : 0), 0) > 1000000) throw new Error('Provide up to 100 files and 1 MB of source.');
75
+ const atlas = buildReviewAtlas(files, { evidence });
76
+ const exitCode = reviewAtlasExitCode(atlas, { strict });
77
+ return { ok: exitCode === 0, exitCode, atlas, brief: renderReviewBrief(atlas) };
78
+ },
79
+ },
93
80
  {
94
81
  name: 'intent_check',
95
82
  description: 'Run ThunderLang semantic diagnostics on .intent source. Returns the diagnostics (codes, severity, messages) , the deterministic checks that catch missing verification, secrets on the bus, contradictions, and more.',
@@ -0,0 +1,18 @@
1
+ // thunder-model-v1: the one meaning every Thunder view is drawn from (see src/model.mjs).
2
+ import type { Does } from './visual.mjs';
3
+ export const MODEL_SCHEMA: 'thunder-model-v1';
4
+ export const THING_LANGUAGES: string[];
5
+ export interface FlowNode { id: string; kind: 'start' | 'decision' | 'step' | 'loop' | 'stop' | 'end' | 'code'; text: string; line?: number; lane: number; row: number; does: Does; uses?: string; answer?: boolean; otherwise?: boolean; value?: string; code?: boolean }
6
+ export interface FlowEdge { from: string; to: string; label?: 'yes' | 'no' | 'each' | 'next' | 'done' | 'error' }
7
+ export interface FlowBlock { id: string; yes?: FlowBlock[]; no?: FlowBlock[]; each?: FlowBlock[]; body?: FlowBlock[]; handlers?: { id: string; blocks: FlowBlock[] }[]; always?: { id: string; blocks: FlowBlock[] } }
8
+ /** nodes/edges: the flow as a graph. blocks: the same nodes as a tree, which views draw from. */
9
+ export interface Flow { nodes: FlowNode[]; edges: FlowEdge[]; blocks: FlowBlock[] }
10
+ export interface Thing { id: string; kind: 'thing' | 'record' | 'choices'; name: string; label: string; doc?: string; file: string; lines: [number, number]; knows: { name: string; label: string; kind: string | null; start: string | null; line: number | null }[]; choices: string[]; can: string[] }
11
+ export interface Member { id: string; kind: 'action' | 'rule' | 'steps' | 'setup' | 'not-read'; name: string; label: string; owner?: string; file: string; language: string; lines: [number, number]; doc?: string; route?: string; youGive: string[]; youGetBack?: string; rule?: unknown; question?: string; yesNo?: boolean; flow: Flow }
12
+ export interface ThunderModel { schema: 'thunder-model-v1'; name: string; files: { path: string; language: string; purpose?: string }[]; things: Thing[]; members: Member[]; links: { from: string; to: string; kind: 'uses'; node: string }[]; unknowns: { id?: string; file: string; line: number; why: string }[] }
13
+ export function thunderModel(files: { path: string; source: string }[], options?: { name?: string }): ThunderModel;
14
+ export function flowOf(steps: unknown[], options?: { start?: string; memberIndex?: Map<string, string>; memberLabel?: Map<string, string> }): Flow;
15
+ export function ruleFlow(item: unknown, start: string): Flow;
16
+ export function askAsQuestion(step: { says: string; code?: string }, ruleLabel?: string): { text: string; flip: boolean };
17
+ export function stepDoes(step: unknown): Does;
18
+ export function modelText(model: ThunderModel, id: string): string;
package/src/model.mjs ADDED
@@ -0,0 +1,456 @@
1
+ // thunder-model-v1: the one meaning that every Thunder view is drawn from. Things (classes), Data (records and
2
+ // choices), and members (actions, rules, steps, setup) with their flow as a graph, links between them, source lines,
3
+ // and everything Thunder could not read. Thunder pictures and Thunder Text are projections of this model; nothing in
4
+ // them may say more than the model does. Browser-safe: takes [{ path, source }].
5
+ import { readCode } from './read.mjs';
6
+ import { readableLanguage } from './read-repo.mjs';
7
+ import { plainFromReading } from './plain-contract.mjs';
8
+ import { visualFor } from './visual.mjs';
9
+
10
+ export const MODEL_SCHEMA = 'thunder-model-v1';
11
+ /** Languages whose classes, records, and choices are read today. Others still get every function. */
12
+ export const THING_LANGUAGES = ['python', 'typescript', 'javascript'];
13
+
14
+ const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
15
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
16
+ const stripQuotes = (v) => v.replace(/^[rbuf]*(["'`])(.*)\1$/s, '$2');
17
+
18
+ /** How a starting value reads: "3 unless told otherwise", "empty at first", "on shelf at first". */
19
+ function startValue(expr, params = {}) {
20
+ const e = String(expr ?? '').trim();
21
+ if (!e) return null;
22
+ if (e in params) return params[e] != null ? `${startValue(params[e])?.replace(/ at first$/, '')} unless told otherwise` : 'given when it starts';
23
+ if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+)$/.test(e)) return 'empty at first';
24
+ if (/^(None|null|undefined)$/.test(e)) return 'nothing at first';
25
+ if (/^(True|true)$/.test(e)) return 'yes at first';
26
+ if (/^(False|false)$/.test(e)) return 'no at first';
27
+ if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
28
+ if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes(e)}" at first`;
29
+ const en = e.match(/^[A-Z]\w*\.([A-Z][A-Z0-9_]+)$/);
30
+ if (en) return `${words(en[1])} at first`;
31
+ return 'worked out when it starts';
32
+ }
33
+
34
+ const KIND_WORDS = [
35
+ [/^(int|float|number|double|long|decimal|Decimal|bigint)$/i, 'a number'],
36
+ [/^(str|string|String|text)$/i, 'words'],
37
+ [/^(bool|boolean)$/i, 'yes or no'],
38
+ [/^(date|datetime|Date|LocalDate|Instant)$/i, 'a date'],
39
+ ];
40
+ function kindWords(type) {
41
+ const t = String(type ?? '').trim();
42
+ if (!t) return null;
43
+ for (const [re, w] of KIND_WORDS) if (re.test(t)) return w;
44
+ const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^Array<(.+)>$|^(.+)\[\]$/);
45
+ if (list) return `a list of ${(list[1] || list[2] || list[3]).trim()}s`;
46
+ const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$/);
47
+ if (opt) return `${kindWords(opt[1] || opt[2] || opt[3]) ?? `a ${opt[1] || opt[2] || opt[3]}`}, or nothing`;
48
+ return /^[A-Z]/.test(t) ? `a ${t}` : null;
49
+ }
50
+
51
+ // ── Things: classes, records, and choices ───────────────────────────────────────────────────────────────
52
+
53
+ function pythonThings(src, file) {
54
+ const lines = src.split('\n');
55
+ const out = [];
56
+ for (let i = 0; i < lines.length; i++) {
57
+ const m = lines[i].match(/^(\s*)class\s+(\w+)\s*(?:\(([^)]*)\))?\s*:/);
58
+ if (!m) continue;
59
+ const indent = m[1].length;
60
+ const decorators = [];
61
+ for (let k = i - 1; k >= 0 && /^\s*@/.test(lines[k]); k--) decorators.unshift(lines[k].trim());
62
+ let end = i;
63
+ for (let j = i + 1; j < lines.length; j++) {
64
+ if (!lines[j].trim() || /^\s*#/.test(lines[j])) continue;
65
+ if (lines[j].match(/^\s*/)[0].length <= indent) break;
66
+ end = j;
67
+ }
68
+ const body = lines.slice(i + 1, end + 1);
69
+ const bodyIndent = (body.find((l) => l.trim()) || '').match(/^\s*/)[0].length;
70
+ const top = body.map((l, k) => ({ text: l, line: i + 2 + k })).filter((l) => l.text.trim() && l.text.match(/^\s*/)[0].length === bodyIndent);
71
+ const bases = (m[3] || '').split(',').map((b) => b.trim());
72
+ const isEnum = bases.some((b) => /(^|\.)(Enum|IntEnum|StrEnum|Flag)$/.test(b));
73
+ const isRecord = !isEnum && (decorators.some((d) => /@(dataclasses\.)?dataclass\b|@attr\.s\b|@define\b/.test(d)) || bases.some((b) => /(BaseModel|NamedTuple|TypedDict|Schema)$/.test(b)));
74
+ const docLine = top[0] && top[0].text.trim().match(/^[rRuU]?("""|'''|"|')(.*?)(\1)?$/);
75
+ const doc = docLine ? (docLine[3] ? docLine[2].trim() : docLine[2].trim()) || null : null;
76
+ const thing = { kind: isEnum ? 'choices' : isRecord ? 'record' : 'thing', name: m[2], file, lines: [i + 1, end + 1], indent, ...(doc ? { doc } : {}), knows: [], choices: [] };
77
+ for (const l of top) {
78
+ const t = l.text.trim();
79
+ if (/^(def|async def|class|@|"""|'''|#)/.test(t)) continue;
80
+ let f;
81
+ if (isEnum && (f = t.match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.+)$/))) thing.choices.push(/^[rbuf]*["']/.test(f[2]) ? stripQuotes(f[2].trim()) : words(f[1]));
82
+ else if ((f = t.match(/^(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/))) thing.knows.push({ name: f[1], label: words(f[1]), kind: kindWords(f[2]), start: f[3] ? startValue(f[3]) : null, line: l.line });
83
+ }
84
+ // Facts set when a Thing starts: self.x = ... inside __init__.
85
+ const init = body.findIndex((l) => /^\s*def\s+__init__\s*\(/.test(l));
86
+ if (init >= 0) {
87
+ const sig = body.slice(init).join('\n').match(/def\s+__init__\s*\(([^)]*)\)/s);
88
+ const params = {};
89
+ for (const p of (sig?.[1] || '').split(',').map((x) => x.trim()).filter((x) => x && x !== 'self')) {
90
+ const pm = p.match(/^(\w+)(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/);
91
+ if (pm) params[pm[1]] = pm[2] ?? null;
92
+ }
93
+ const initIndent = body[init].match(/^\s*/)[0].length;
94
+ for (let k = init + 1; k < body.length; k++) {
95
+ const ln = body[k];
96
+ if (ln.trim() && ln.match(/^\s*/)[0].length <= initIndent) break;
97
+ const a = ln.trim().match(/^self\.(\w+)\s*(?::\s*([^=]+))?=\s*(.+)$/);
98
+ if (a && !thing.knows.some((x) => x.name === a[1])) {
99
+ // The parameter's declared type, when the value is a plain parameter name (never code in a pattern).
100
+ const pType = /^\w+$/.test(a[3].trim()) ? (sig?.[1] || '').match(new RegExp(`\\b${a[3].trim()}\\s*:\\s*([\\w\\[\\]. |]+)`))?.[1] : undefined;
101
+ thing.knows.push({ name: a[1], label: words(a[1]), kind: kindWords(a[2] || pType) ?? (/^\[/.test(a[3]) ? 'a list' : null), start: startValue(a[3], params), line: i + 2 + k });
102
+ }
103
+ }
104
+ }
105
+ out.push(thing);
106
+ }
107
+ return out;
108
+ }
109
+
110
+ function braceEnd(src, open) {
111
+ let depth = 0;
112
+ for (let i = open; i < src.length; i++) {
113
+ const c = src[i];
114
+ if (c === '"' || c === "'" || c === '`') { const q = c; for (i++; i < src.length && src[i] !== q; i++) if (src[i] === '\\') i++; continue; }
115
+ if (c === '{') depth++;
116
+ else if (c === '}' && --depth === 0) return i;
117
+ }
118
+ return -1;
119
+ }
120
+ const lineOf = (src, idx) => src.slice(0, idx).split('\n').length;
121
+
122
+ function tsThings(src, file) {
123
+ const out = [];
124
+ const re = /(?:^|\n)[ \t]*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|enum)\s+(\w+)[^{]*\{/g;
125
+ let m;
126
+ while ((m = re.exec(src))) {
127
+ const open = m.index + m[0].length - 1;
128
+ const close = braceEnd(src, open);
129
+ if (close < 0) continue;
130
+ const body = src.slice(open + 1, close);
131
+ const startLine = lineOf(src, m.index + (m[0].startsWith('\n') ? 1 : 0));
132
+ const before = src.slice(0, m.index).split('\n').slice(-4).join('\n');
133
+ const docm = before.match(/\/\*\*([\s\S]*?)\*\/\s*$/);
134
+ const doc = docm ? docm[1].split('\n').map((l) => l.replace(/^\s*\*\s?/, '').trim()).filter((l) => l && !l.startsWith('@')).join(' ') || null : null;
135
+ const thing = { kind: m[1] === 'enum' ? 'choices' : m[1] === 'interface' ? 'record' : 'thing', name: m[2], file, lines: [startLine, lineOf(src, close)], ...(doc ? { doc } : {}), knows: [], choices: [] };
136
+ if (m[1] === 'enum') {
137
+ for (const part of body.split(',')) { const e = part.trim().match(/^(\w+)(?:\s*=\s*(.+))?$/s); if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes(e[2].trim()) : words(e[1])); }
138
+ } else {
139
+ // Only the class's own lines, not the bodies of its methods.
140
+ let depth = 0, own = '';
141
+ for (const c of body) { if (c === '{') depth++; if (depth === 0) own += c; if (c === '}') depth--; }
142
+ const ownLines = own.split(/[;\n]/).map((l) => l.trim()).filter(Boolean);
143
+ for (const l of ownLines) {
144
+ const f = l.match(/^(?:(?:public|private|protected|readonly|static|declare)\s+)*(\w+)(\?)?\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/) || l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*(\w+)()\s*=\s*(.+)$/);
145
+ if (!f || /\(/.test(f[1])) continue;
146
+ const hasType = f.length > 4 && f[3] && !l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*\w+\s*=/);
147
+ thing.knows.push({ name: f[1], label: words(f[1]), kind: hasType ? kindWords(f[3]) : null, start: hasType ? (f[4] ? startValue(f[4]) : null) : startValue(f[3]), line: null });
148
+ }
149
+ const ctor = body.match(/constructor\s*\(([^)]*)\)\s*\{/);
150
+ if (ctor) {
151
+ const params = {};
152
+ for (const p of ctor[1].split(',').map((x) => x.trim()).filter(Boolean)) { const pm = p.match(/^(?:(?:public|private|protected|readonly)\s+)*(\w+)\??(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/); if (pm) params[pm[1]] = pm[2] ?? null; }
153
+ const cOpen = body.indexOf('{', ctor.index + ctor[0].length - 1);
154
+ const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
155
+ for (const a of cBody.matchAll(/this\.(\w+)\s*=\s*([^;\n]+)/g)) {
156
+ if (!thing.knows.some((x) => x.name === a[1])) thing.knows.push({ name: a[1], label: words(a[1]), kind: null, start: startValue(a[2], params), line: null });
157
+ else { const k = thing.knows.find((x) => x.name === a[1]); if (!k.start) k.start = startValue(a[2], params); }
158
+ }
159
+ }
160
+ }
161
+ out.push(thing);
162
+ }
163
+ return out;
164
+ }
165
+
166
+ // ── Flow: steps as a graph a person can follow ─────────────────────────────────────────────────────────
167
+
168
+ /**
169
+ * What kind of step this is, in a kid's words: find, keep-only, check, calculate, save, send, ask, repeat, answer,
170
+ * stop, or code (Thunder could not explain it). Shapes and colors key off this.
171
+ */
172
+ export function stepDoes(step) {
173
+ const s = step.says || '', c = step.callee || '';
174
+ if (step.restates || step.kind === 'other') return 'code';
175
+ if (step.kind === 'fail') return 'stop';
176
+ if (step.kind === 'loop') return 'repeat';
177
+ if (step.kind === 'return') return 'answer';
178
+ if (step.kind === 'check') return 'check';
179
+ if (step.kind === 'branch') return 'decide';
180
+ if (/^Writes to the database|^(Records|Adds to|Removes)/.test(s)) return 'save';
181
+ if (/^(Sends an email|Announces an event|Writes a log)/.test(s)) return 'send';
182
+ if (/^(Calls another service|Calls Stripe)/.test(s)) return 'ask';
183
+ if (/\b(filter|where|select|query|find|get|fetch|load|read|search|lookup|scalars|all)\b/i.test(c) || /the items in .* where|the first item in|the .* entry in|the .* with /.test(s)) return /\b(filter|where)\b/i.test(c) || / where /.test(s) ? 'keep-only' : 'find';
184
+ if (step.kind === 'set') return 'calculate';
185
+ return 'do';
186
+ }
187
+
188
+ /** "the book's status" for book.status; plain words for everything else. */
189
+ const possessive = (text) => String(text)
190
+ .replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => (/^(self|this)$/.test(a) ? `the ${words(b)}` : `the ${words(a)}'s ${words(b)}`))
191
+ .replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words(m)); // days_late, daysLate -> days late
192
+ /** An answer as words: NoFee -> "No fee", true -> "Yes". */
193
+ const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : cap(words(r)));
194
+
195
+ /**
196
+ * A branch as a question a kid can answer with yes or no, asked the positive way round. "If book.status is not on
197
+ * shelf" becomes "Is the book's status on shelf?" with the Stop on the No side (flip). A call to a known rule is
198
+ * asked by the rule's own name: "Can borrow?".
199
+ */
200
+ export function askAsQuestion(step, ruleLabel) {
201
+ let c = String(step.says).replace(/^If /, '').replace(/ \(\d+ steps? inside\)$/, '').trim();
202
+ let flip = false;
203
+ if (/^not: /.test(c)) { c = c.slice(5); flip = true; }
204
+ if (ruleLabel) {
205
+ const negated = /^not\b|^!/.test(String(step.code || '').replace(/^\s*if\s*\(?\s*/, '')) || /\bnot\s+(self|this)\./.test(step.code || '') || /!\s*(this|self)\./.test(step.code || '');
206
+ // The negation is read from the code alone; the step's wording may already say "not" for the same reason.
207
+ return { text: `${ruleLabel.replace(/\?$/, '')}?`, flip: negated };
208
+ }
209
+ let m;
210
+ if ((m = c.match(/^not (.+)$/))) { c = m[1]; flip = !flip; }
211
+ if ((m = c.match(/^(.+?) is not (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip: !flip };
212
+ if ((m = c.match(/^(.+?) has no (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip: !flip };
213
+ if ((m = c.match(/^(.+?) is (.+)$/))) return { text: `Is ${possessive(m[1])} ${possessive(m[2])}?`, flip };
214
+ if ((m = c.match(/^(.+?) has (.+)$/))) return { text: `Does ${possessive(m[1])} have ${m[2]}?`, flip };
215
+ return { text: `${cap(possessive(c))}?`, flip };
216
+ }
217
+
218
+ /** A rule's own picture: each rule asked in order, the first Yes gives its answer, otherwise the fallback. */
219
+ export function ruleFlow(item, start) {
220
+ const nodes = [], edges = [];
221
+ let n = 0;
222
+ const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, row: nodes.length, ...extra }); return id; };
223
+ let prev = node('start', start, { lane: 0, does: 'start' });
224
+ let label;
225
+ for (const r of item.rules || []) {
226
+ const d = node('decision', `${cap(possessive(r.says ?? r.when))}?`, { lane: 0, line: r.line, does: 'decide' });
227
+ edges.push({ from: prev, to: d, ...(label ? { label } : {}) });
228
+ const out = node('end', answerWords(r.result), { lane: 1, line: r.line, does: 'answer', answer: true, value: r.result });
229
+ edges.push({ from: d, to: out, label: 'yes' });
230
+ prev = d; label = 'no';
231
+ }
232
+ if (item.otherwise) {
233
+ const o = node('end', answerWords(item.otherwise.result), { lane: 0, line: item.otherwise.line, does: 'answer', answer: true, otherwise: true, value: item.otherwise.result });
234
+ edges.push({ from: prev, to: o, ...(label ? { label } : {}) });
235
+ }
236
+ // As a tree: each question's Yes gives its answer, its No asks the next question (or gives the fallback).
237
+ const decisions = nodes.filter((x) => x.kind === 'decision');
238
+ const answers = nodes.filter((x) => x.answer && !x.otherwise);
239
+ const fallback = nodes.find((x) => x.otherwise);
240
+ const chain = (i) => (i < decisions.length ? [{ id: decisions[i].id, yes: [{ id: answers[i].id }], no: chain(i + 1) }] : fallback ? [{ id: fallback.id }] : []);
241
+ return { nodes, edges, blocks: chain(0) };
242
+ }
243
+
244
+ /** Turn steps into nodes and edges. Deterministic; nothing is added that the steps do not say. */
245
+ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), memberLabel = new Map() } = {}) {
246
+ const nodes = [], edges = [];
247
+ let n = 0;
248
+ const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, ...extra }); return id; };
249
+ const connect = (open, to) => { for (const o of open) edges.push({ from: o.id, to, ...(o.label ? { label: o.label } : {}) }); };
250
+ // The first call in the step to another member of this file: self.can_borrow(...), delivery_fee(...), this.lateFee(...).
251
+ const usesOf = (st) => {
252
+ for (const c of String(st.code || '').matchAll(/(?:\b(?:self|this)\.)?\b([A-Za-z_]\w*)\s*\(/g)) {
253
+ const id = memberIndex.get(c[1].toLowerCase());
254
+ if (id) return id;
255
+ }
256
+ return null;
257
+ };
258
+ // walk returns { open, blocks }: open = edges still waiting for the next node; blocks = the same nodes as a tree
259
+ // (each question with its yes and no sides, loops with their body, try with its handlers and always), which is
260
+ // what the picture and Thunder Text are drawn from. The edges are the same flow as a graph, for other tools.
261
+ const walk = (list, open, lane) => {
262
+ const blocks = [];
263
+ for (const st of list) {
264
+ const does = stepDoes(st);
265
+ const base = { line: st.line, lane, does, ...(usesOf(st) ? { uses: usesOf(st) } : {}) };
266
+ if (st.kind === 'branch') {
267
+ const { text, flip } = askAsQuestion(st, base.uses && memberLabel.get(base.uses));
268
+ const [into, past] = flip ? ['no', 'yes'] : ['yes', 'no'];
269
+ const d = node('decision', text, base);
270
+ connect(open, d);
271
+ const inside = walk(st.children || [], [{ id: d, label: into }], lane + 1);
272
+ // The other side of the question: its else (or else-if chain) when the code has one.
273
+ const other = st.otherwise?.length ? walk(st.otherwise, [{ id: d, label: past }], lane + 1) : { open: [{ id: d, label: past }], blocks: [] };
274
+ blocks.push({ id: d, [into]: inside.blocks, [past]: other.blocks });
275
+ open = [...other.open, ...inside.open];
276
+ } else if (st.kind === 'loop') {
277
+ const l = node('loop', st.says, base);
278
+ connect(open, l);
279
+ const body = walk(st.children || [], [{ id: l, label: 'each' }], lane + 1);
280
+ for (const b of body.open) edges.push({ from: b.id, to: l, label: 'next' });
281
+ blocks.push({ id: l, each: body.blocks });
282
+ open = [{ id: l, label: 'done' }];
283
+ } else if (st.kind === 'fail') {
284
+ const sn = node('stop', st.says.replace(/^Fails with /, 'Stop: '), base);
285
+ connect(open, sn);
286
+ blocks.push({ id: sn });
287
+ open = [];
288
+ } else if (st.kind === 'return') {
289
+ const e = node('end', st.restates ? st.code : st.says.replace(/^Returns /, 'Gives back '), { ...base, ...(st.restates ? { code: true } : {}) });
290
+ connect(open, e);
291
+ blocks.push({ id: e });
292
+ open = [];
293
+ } else if (st.kind === 'try') {
294
+ // Try: the normal path; each "If X goes wrong" handler beside it; "Always, at the end" after both.
295
+ const t = node('step', st.says, base);
296
+ connect(open, t);
297
+ const body = walk(st.children || [], [{ id: t }], lane);
298
+ let after = body.open;
299
+ const handlers = [];
300
+ for (const h of st.handlers || []) {
301
+ const hn = node('decision', `${h.says}?`, { line: h.line, lane: lane + 1, does: 'decide', handler: true });
302
+ edges.push({ from: t, to: hn, label: 'error' });
303
+ const hw = walk(h.steps, [{ id: hn, label: 'yes' }], lane + 1);
304
+ handlers.push({ id: hn, blocks: hw.blocks });
305
+ after = [...after, ...hw.open];
306
+ }
307
+ let always = null;
308
+ if (st.always) {
309
+ const an = node('step', 'Always, at the end', { line: st.always.line, lane, does: 'do', always: true });
310
+ connect(after, an);
311
+ const aw = walk(st.always.steps, [{ id: an }], lane);
312
+ always = { id: an, blocks: aw.blocks };
313
+ after = aw.open;
314
+ }
315
+ blocks.push({ id: t, body: body.blocks, ...(handlers.length ? { handlers } : {}), ...(always ? { always } : {}) });
316
+ open = after;
317
+ } else {
318
+ const k = node(does === 'code' ? 'code' : 'step', does === 'code' ? st.code ?? st.says : st.says, base);
319
+ connect(open, k);
320
+ open = [{ id: k }];
321
+ if (st.children?.length) {
322
+ const inner = walk(st.children, open, lane + 1);
323
+ blocks.push({ id: k, body: inner.blocks });
324
+ open = inner.open;
325
+ } else blocks.push({ id: k });
326
+ }
327
+ }
328
+ return { open, blocks };
329
+ };
330
+ const s0 = node('start', start, { lane: 0, does: 'start' });
331
+ const { open, blocks } = walk(steps || [], [{ id: s0 }], 0);
332
+ if (open.length) connect(open, node('end', 'Done', { lane: 0, does: 'answer' }));
333
+ // Rows: order of first appearance, so the picture reads top to bottom like the code.
334
+ nodes.forEach((x, i) => { x.row = i; });
335
+ return { nodes, edges, blocks };
336
+ }
337
+
338
+ // ── The model ──────────────────────────────────────────────────────────────────────────────────────────
339
+
340
+ const idOf = (...parts) => parts.join('#').replace(/\s+/g, '');
341
+
342
+ /**
343
+ * Read files into the one Thunder model. Things come from classes in THING_LANGUAGES; every function in every
344
+ * readable language becomes a member with its flow. Unknowns list what could not be read, so no view hides a gap.
345
+ */
346
+ export function thunderModel(files, { name = 'app' } = {}) {
347
+ const things = [], members = [], links = [], unknowns = [], fileInfo = [];
348
+ for (const f of files) {
349
+ const language = readableLanguage(f.path);
350
+ if (!language || !f.source) continue;
351
+ let reading;
352
+ try { reading = readCode(f.source, { language, file: f.path }); } catch (e) { unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` }); continue; }
353
+ let fileThings = [];
354
+ try { fileThings = language === 'python' ? pythonThings(f.source, f.path) : THING_LANGUAGES.includes(language) ? tsThings(f.source, f.path) : []; }
355
+ catch (e) { unknowns.push({ file: f.path, line: 1, why: `Classes in this file could not be drawn as Things: ${e.message}` }); } // one file never stops the whole app
356
+ if (!THING_LANGUAGES.includes(language) && /\b(class|struct|record|enum|interface|data class)\s+[A-Z]/.test(f.source)) {
357
+ unknowns.push({ file: f.path, line: 1, why: `Classes, records, and choices in ${language} are not drawn as Things yet; their functions are read.` });
358
+ }
359
+ for (const t of fileThings) { t.id = idOf(f.path, t.name); t.label = cap(words(t.name)); t.can = []; things.push(t); }
360
+ const moduleDoc = language === 'python' ? (f.source.match(/^\s*(?:#.*\n|\s*\n)*[rRuU]?("""|''')([\s\S]*?)\1/)?.[2] ?? '').trim().split(/\n\s*\n/)[0].replace(/\s+/g, ' ') : '';
361
+ fileInfo.push({ path: f.path, language, ...(moduleDoc ? { purpose: moduleDoc } : {}) });
362
+
363
+ const fns = reading.items.filter((i) => i.kind === 'function' || i.kind === 'decision');
364
+ const fileMembers = fns.map((item) => {
365
+ const owner = fileThings.filter((t) => item.line > t.lines[0] && item.line <= t.lines[1]).sort((a, b) => b.lines[0] - a.lines[0])[0];
366
+ const v = visualFor(item);
367
+ const setup = /^(__init__|constructor|init|New)$/.test(item.name) && owner;
368
+ const kind = setup ? 'setup' : v.element === 'action' ? 'action' : v.element === 'decision' ? 'rule' : v.element === 'not-read' ? 'not-read' : 'steps';
369
+ const bodyEnd = item.anchor?.bodyLines?.[1] ?? Math.max(item.line, ...(item.rules || []).map((r) => r.line || 0), item.otherwise?.line || 0);
370
+ let rule = null;
371
+ if (kind === 'rule') { try { rule = plainFromReading(item); } catch { rule = null; } }
372
+ const m = {
373
+ id: idOf(f.path, owner?.name ?? '', item.name, item.line), kind, name: item.name,
374
+ label: setup ? `A new ${owner.label} starts with` : cap(words(item.name.replace(/^__|__$/g, ''))),
375
+ ...(owner ? { owner: owner.id } : {}), file: f.path, language, lines: [item.line, bodyEnd],
376
+ ...(item.doc ? { doc: item.doc } : {}), ...(item.route ? { route: `${item.route.method} ${item.route.path}`.trim() } : {}),
377
+ youGive: (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name)).map((p) => words(p.name)),
378
+ ...(item.returns && kind !== 'rule' ? { youGetBack: kindWords(item.returns) ?? item.returns } : {}),
379
+ ...(rule ? { rule, question: rule.question } : {}),
380
+ // A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
381
+ ...(kind === 'rule' ? { yesNo: [...(item.rules || []).map((r) => r.result), item.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {}),
382
+ _steps: item.steps || [], _item: item,
383
+ };
384
+ if (owner) owner.can.push(m.id);
385
+ if (kind === 'not-read') unknowns.push({ id: m.id, file: f.path, line: item.line, why: 'Thunder cannot explain this function yet; its code is shown instead.' });
386
+ return m;
387
+ });
388
+ // Flows need every member's name in the file, so a step can link to the rule or member it uses.
389
+ const byName = new Map(fileMembers.map((m) => [m.name.toLowerCase(), m.id]));
390
+ const labels = new Map(fileMembers.map((m) => [m.id, m.label]));
391
+ for (const m of fileMembers) {
392
+ const start = m.youGive.length ? `You give it: ${m.youGive.join(', ')}` : 'Start';
393
+ m.flow = m.kind === 'rule' || (m._item.kind === 'decision' && m._item.rules?.length) ? ruleFlow(m._item, start) : flowOf(m._steps, { start, memberIndex: byName, memberLabel: labels });
394
+ for (const nd of m.flow.nodes) if (nd.uses && nd.uses !== m.id) links.push({ from: m.id, to: nd.uses, kind: 'uses', node: nd.id });
395
+ delete m._steps; delete m._item;
396
+ members.push(m);
397
+ }
398
+ }
399
+ return { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns };
400
+ }
401
+
402
+ // ── Thunder Text, projected from the model (the picture is projected from the same nodes) ──────────────
403
+
404
+ /** Thunder Text lines from a flow's blocks: the same tree the picture is drawn from. */
405
+ function flowLines(flow, depth = 1) {
406
+ const byId = new Map(flow.nodes.map((n) => [n.id, n]));
407
+ const out = [];
408
+ const pad = (d) => ' '.repeat(d);
409
+ const at = (n) => (n.line ? ` (line ${n.line})` : '');
410
+ const say = (n) => (n.kind === 'code' ? `\`${n.text}\` (code, not explained)` : n.kind === 'decision' ? `Ask: ${n.text}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
411
+ const go = (blocks, d) => {
412
+ for (const b of blocks || []) {
413
+ const n = byId.get(b.id);
414
+ out.push(`${pad(d)}- ${say(n)}${at(n)}`);
415
+ if (n.kind === 'decision') {
416
+ for (const side of ['yes', 'no']) {
417
+ if (!(side in b)) continue;
418
+ if (b[side].length) { out.push(`${pad(d + 1)}${side === 'yes' ? 'Yes' : 'No'}:`); go(b[side], d + 2); }
419
+ else out.push(`${pad(d + 1)}${side === 'yes' ? 'Yes' : 'No'}: continue`);
420
+ }
421
+ }
422
+ if (b.each) { out.push(`${pad(d + 1)}For each:`); go(b.each, d + 2); }
423
+ if (b.body) go(b.body, d + 1);
424
+ for (const h of b.handlers || []) { out.push(`${pad(d + 1)}${byId.get(h.id).text.replace(/\?$/, '')}:`); go(h.blocks, d + 2); }
425
+ if (b.always) { out.push(`${pad(d + 1)}Always, at the end:`); go(b.always.blocks, d + 2); }
426
+ }
427
+ };
428
+ go(flow.blocks, depth);
429
+ return out;
430
+ }
431
+
432
+ /**
433
+ * Thunder Text for a Thing or a member, made from the same model nodes the picture is drawn from, so the two
434
+ * cannot disagree. Pass the model and an id.
435
+ */
436
+ export function modelText(model, id) {
437
+ const t = model.things.find((x) => x.id === id);
438
+ if (t) {
439
+ const lines = [`${t.kind === 'thing' ? 'Thing' : t.kind === 'record' ? 'Record' : 'Choices'} ${t.label}`];
440
+ if (t.doc) lines.push(` Author's note: ${t.doc}`);
441
+ if (t.choices.length) lines.push(` One of: ${t.choices.join(', ')}`);
442
+ if (t.knows.length) { lines.push(' It knows'); for (const k of t.knows) lines.push(` ${k.label}: ${[k.kind, k.start].filter(Boolean).join(', ') || 'a value'}`); }
443
+ if (t.can.length) { lines.push(' It can'); for (const c of t.can) lines.push(` ${model.members.find((m) => m.id === c)?.label}`); }
444
+ return `${lines.join('\n')}\n`;
445
+ }
446
+ const m = model.members.find((x) => x.id === id);
447
+ if (!m) throw new Error(`Nothing in the model has id ${id}.`);
448
+ const owner = m.owner && model.things.find((x) => x.id === m.owner);
449
+ const lines = [`${m.label}${owner && m.kind !== 'setup' ? ` (${owner.label})` : ''}${m.kind === 'rule' ? ': a rule' : ''}`];
450
+ if (m.route) lines.push(` When someone calls ${m.route}`);
451
+ if (m.doc) lines.push(` Author's note: ${m.doc}`);
452
+ if (m.youGive.length) lines.push(` You give it: ${m.youGive.join(', ')}`);
453
+ if (m.youGetBack) lines.push(` You get back: ${m.youGetBack}`);
454
+ lines.push(...flowLines(m.flow));
455
+ return `${lines.join('\n')}\n`;
456
+ }
@@ -0,0 +1,9 @@
1
+ import type { ObligationResolution, TestReport } from './index.js';
2
+ export function resolveObligations(ast: unknown): {
3
+ obligations: ObligationResolution[];
4
+ tests: TestReport;
5
+ verified: number;
6
+ declared: number;
7
+ unverified: number;
8
+ failed: number;
9
+ };