@skillstech/thunderlang 0.5.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.
package/src/steps.mjs ADDED
@@ -0,0 +1,297 @@
1
+ // Steps: read any function as a short list of plain steps (check, branch, loop, set, call, return, fail).
2
+ // Decisions become rules; everything else becomes steps. Deterministic and pattern-based, like the rest of
3
+ // the reader: a statement it does not recognize is kept as `other` with its original text, never guessed.
4
+ export const STEPS_SCHEMA = 'thunder-steps-v1';
5
+ const MAX_STEPS = 14;
6
+
7
+ const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
8
+ const clip = (s, n = 70) => { const t = String(s).replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
9
+ const stripTail = (s) => String(s).trim().replace(/[;{]\s*$/, '').replace(/:\s*$/, '').trim();
10
+
11
+ // Calls that mean something to a reader, recognized by name. Same spirit as the Thunder map patterns.
12
+ const KNOWN_CALLS = [
13
+ { re: /^(?:requests\.(?:get|post|put|patch|delete)|fetch|axios(?:\.\w+)?|http\.(?:Get|Post|NewRequest)|HttpClient\.\w+|client\.(?:get|post|put|delete))$/i, say: () => 'Calls another service over HTTP' },
14
+ { re: /^stripe\./i, say: () => 'Calls Stripe' },
15
+ { re: /^(?:send_?email|sendMail|mailer\.\w+|smtp\.\w+)$/i, say: () => 'Sends an email' },
16
+ { re: /^(?:db|database|repo|repository|session|conn|cursor)\.(?:insert|save|add|create|update|execute|exec|query|delete|remove|commit)\w*$/i, say: (m) => `Writes to the database (${m.split('.').pop()})` },
17
+ { re: /^(?:events?|bus|publisher|emitter|queue)\.(?:publish|emit|send|enqueue|push)$/i, say: () => 'Announces an event' },
18
+ { re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf)\b/i, say: () => 'Writes a log or message' },
19
+ ];
20
+
21
+ /** A condition as words when it can't be fully translated: c.ctx == nil -> "c.ctx is empty". */
22
+ export function sayCodeCondition(cond) {
23
+ let c = String(cond).trim().replace(/\s*(\{|:|then|do)\s*$/, '').trim();
24
+ while (c.startsWith('(') && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
25
+ return clip(c
26
+ .replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, ' is empty')
27
+ .replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, ' is not empty')
28
+ .replace(/\s*(!==|!=)\s*(nil|null|None|undefined)\b/g, ' is set')
29
+ .replace(/\bis not None\b/g, 'is set').replace(/\bis None\b/g, 'is empty')
30
+ .replace(/\s*(===|==)\s*/g, ' is ').replace(/\s*(!==|!=)\s*/g, ' is not ')
31
+ .replace(/\s*&&\s*/g, ' and ').replace(/\s*\|\|\s*/g, ' or ')
32
+ .replace(/(^|[\s(])!(?=[\w(])/g, '$1not ').replace(/\s+/g, ' '), 70);
33
+ }
34
+ function matchingClose(str, open) {
35
+ let depth = 0;
36
+ for (let i = open; i < str.length; i++) { if (str[i] === '(') depth++; else if (str[i] === ')' && --depth === 0) return i; }
37
+ return -1;
38
+ }
39
+ const lastWords = (path) => words(String(path).split('.').pop());
40
+ /** "cmd.commandCalledAs.called" -> "called on command called as"; "this.count" -> "count". */
41
+ function targetWords(path) {
42
+ const parts = String(path).replace(/^@+/, '').replace(/#/g, '').replace(/\[.*$/, '').split('.').filter((p) => !/^(this|self)$/.test(p));
43
+ if (parts.length <= 1) return words(parts[0] || path);
44
+ return `${words(parts[parts.length - 1])} on ${words(parts[parts.length - 2])}`;
45
+ }
46
+
47
+ function callee(text) {
48
+ const m = String(text).match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
49
+ return m ? m[1].replace(/<[^()]*?>/g, '').replace(/\(\)/g, '').replace(/::|->/g, '.').replace(/#/g, '') : null;
50
+ }
51
+ function sayCall(name, args) {
52
+ for (const k of KNOWN_CALLS) if (k.re.test(name)) {
53
+ const target = (args.match(/^\s*["'`]([\w.\-/: ]{1,60})["'`]/) || [])[1];
54
+ const base = k.say(name);
55
+ return target ? `${base}: ${target}` : base;
56
+ }
57
+ return null;
58
+ }
59
+ function firstArgs(text) {
60
+ const open = text.indexOf('(');
61
+ return open >= 0 ? text.slice(open + 1, open + 120) : '';
62
+ }
63
+
64
+ function sayValue(expr) {
65
+ const e = stripTail(expr);
66
+ if (/^["'`].*["'`]$/.test(e)) return `"${clip(e.slice(1, -1), 40)}"`;
67
+ if (/^-?\d+(\.\d+)?$/.test(e) || /^(true|false|True|False|nil|null|None|undefined)$/.test(e)) return e;
68
+ const c = callee(e);
69
+ if (c) {
70
+ if (/^new\s/.test(e)) return `a new ${c.split('.').pop()}`;
71
+ return `the result of ${lastWords(c)}`;
72
+ }
73
+ if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words(e.split('.').pop());
74
+ return null;
75
+ }
76
+
77
+ /** Classify one statement (its first line or header). Returns { kind, says, code } where code is the original text. */
78
+ const CHAIN = [
79
+ { re: /\.(?:map|Select|flatMap|SelectMany|map_values|collect\{)\s*[({]/, say: (src) => `one for each item in ${src}` },
80
+ { re: /\.(?:filter|Where|filter_map|select|reject|grep)\s*[({]/, say: (src) => `the items in ${src} that match` },
81
+ { re: /\.(?:find|First|FirstOrDefault|find_first|detect)\s*[({]/, say: (src) => `the first item in ${src} that matches` },
82
+ { re: /\.(?:some|Any|any)\s*[({]/, say: (src) => `whether any item in ${src} matches` },
83
+ { re: /\.(?:every|All|all)\s*[({]/, say: (src) => `whether every item in ${src} matches` },
84
+ { re: /\.(?:reduce|Aggregate|fold|inject|sum|Sum)\s*[({]/, say: (src) => `a total over ${src}` },
85
+ { re: /\.(?:sort|sorted|OrderBy|sortBy|sort_by)\s*[({]/, say: (src) => `${src}, sorted` },
86
+ { re: /\.(?:join|Join|joinToString)\s*[({]/, say: (src) => `${src} joined into text` },
87
+ ];
88
+ /** "items.filter(x => …).map(…)" -> "one for each item in items" (the last collection step wins). */
89
+ function sayChain(value) {
90
+ const src = (value.match(/^(?:await\s+)?([A-Za-z_$#][\w$#.]*?)(?:\.(?:iter|into_iter|stream|asSequence|values|keys|entries)\(\))?\./) || [])[1];
91
+ if (!src) return null;
92
+ let hit = null;
93
+ for (const c of CHAIN) { const m = value.match(c.re); if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c }; }
94
+ return hit ? hit.c.say(words(src.split('.').pop().replace(/^#/, ''))) : null;
95
+ }
96
+
97
+ export function classifyStatement(raw, { inner = 0 } = {}) {
98
+ const text = String(raw).trim();
99
+ // TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
100
+ const head = text.split('\n')[0].trim()
101
+ .replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, '$1').replace(/([\w$\])])!(?=[.(\[])/g, '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.');
102
+ const code = clip(head, 90);
103
+ let m;
104
+ const innerNote = inner ? ` (${inner} step${inner === 1 ? '' : 's'} inside)` : '';
105
+ // Failures
106
+ if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
107
+ const name = m?.[1] ? m[1].split('.').pop() : null;
108
+ const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
109
+ return { kind: 'fail', says: `Fails${name ? ` with ${name}` : ''}${msg ? `: "${msg}"` : ''}`, code };
110
+ }
111
+ // Returns (Go/Rust error returns read as failures)
112
+ if ((m = head.match(/^return\b\s*(.*)$/))) {
113
+ const expr = stripTail(m[1]);
114
+ if (!expr) return { kind: 'return', says: 'Stops here', code };
115
+ const lastVal = expr.split(',').pop().trim();
116
+ if (/,/.test(expr) && /^(?:err|error|e)$|^Err[A-Z]\w*$|^\w*Error$|^errors\.New\(|^fmt\.Errorf\(/.test(lastVal)) {
117
+ const named = /^Err[A-Z]\w*$|^\w+Error$/.test(lastVal) ? `: ${lastVal}` : '';
118
+ return { kind: 'fail', says: `Returns an error to the caller${named}`, code };
119
+ }
120
+ if (/^(Err|Error)\s*\(/.test(expr) || /\berrors\.New\(|fmt\.Errorf\(/.test(expr)) {
121
+ const msg = (expr.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
122
+ return { kind: 'fail', says: `Returns an error${msg ? `: "${msg}"` : ''}`, code };
123
+ }
124
+ const chain = sayChain(expr);
125
+ if (chain) return { kind: 'return', says: `Returns ${chain}`, code };
126
+ if (/^[({]/.test(expr) || /^\{/.test(expr)) return { kind: 'return', says: /^\(?\s*</.test(expr) ? 'Returns what to show on screen' : 'Returns an object', code };
127
+ if (/^\(?\s*</.test(expr)) return { kind: 'return', says: 'Returns what to show on screen', code };
128
+ const v = sayValue(expr);
129
+ return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', code, ...(v ? {} : { value: clip(expr, 60) }) };
130
+ }
131
+ // Loops
132
+ if ((m = head.match(/^for\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
133
+ return { kind: 'loop', says: `For each ${words(m[1].split(',').pop().trim())} in ${words(stripTail(m[2]).split('.').pop().replace(/\(\)$/, ''))}${innerNote}`, code };
134
+ }
135
+ if ((m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/))) return { kind: 'loop', says: `For each item in ${words(stripTail(m[1]).split('.').pop())}${innerNote}`, code };
136
+ if ((m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[1])} in ${words(m[2].split('.').pop())}${innerNote}`, code };
137
+ if ((m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
138
+ if ((m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
139
+ if ((m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/))) return { kind: 'loop', says: `For each item in ${words(m[1].split('.').pop())}${innerNote}`, code };
140
+ if ((m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${clip(m[1], 50)}${innerNote}` : `Repeats${innerNote}`, code };
141
+ // Branches
142
+ if ((m = head.match(/^(?:if|elif|else\s+if|unless|when)\b\s*(.*?)\s*(?:\{|:|then)?\s*$/))) { const cond = sayCodeCondition(m[1]); return { kind: 'branch', says: `If ${/^unless\b/.test(head) ? 'not: ' : ''}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, '$1'), code, negate: /^unless\b/.test(head) }; }
143
+ if ((m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/))) return { kind: 'branch', says: `Chooses by ${words(clip(m[1], 40)) || 'value'}${innerNote}`, code };
144
+ if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
145
+ if ((m = head.match(/^assert\b\s*(.*?)\s*;?$/))) return { kind: 'check', says: `Checks that ${m[1] ? sayCodeCondition(m[1].replace(/,\s*["'].*$/, '')) : 'a condition holds'}`, code };
146
+ if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
147
+ if ((m = head.match(/^(?:expect|t\.(?:Error|Fatal|Errorf|Fatalf|Run)|require\.\w+|assert\.\w+)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
148
+ if ((m = head.match(/^with\s+(.+?)\s+as\s+(.+?):\s*$/))) { const what = /^open\s*\(/.test(m[1]) ? 'a file' : words(clip(stripTail(m[1]).replace(/\(.*$/, ''), 40)); return { kind: 'set', says: `Opens ${what} as ${words(m[2].replace(/[()]/g, ''))}`, code }; }
149
+ if ((m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
150
+ if (/^defer\b/.test(head)) return { kind: 'call', says: `At the end, ${clip(head.replace(/^defer\s+/, ''), 60)}`, code };
151
+ if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version first', code };
152
+ if (/^yield\b/.test(head)) return { kind: 'call', says: 'Hands control to the given block', code };
153
+ if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
154
+ if ((m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/))) return { kind: 'return', says: `Returns ${m[1]}`, code };
155
+ if (/^vec!?\[/.test(head)) return { kind: 'return', says: 'Returns a list', code };
156
+ // A bare value as a statement is an implicit return (Ruby, Rust, Kotlin/Scala expression bodies).
157
+ if (/^(?:["'`].*["'`]|-?\d+(?:\.\d+)?|true|false|nil|null|None|self|[a-z_][\w.]*)$/.test(head) && !/^(?:else|end|break|next|redo|retry|pass)$/.test(head)) {
158
+ const v = sayValue(head);
159
+ return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a value', code };
160
+ }
161
+ if ((m = head.match(/^(?:\+\+|--)?([@A-Za-z_$#][\w$#.]*)(\+\+|--)?;?$/)) && (/^(\+\+|--)/.test(head) || m[2])) return { kind: 'set', says: `${/\+\+/.test(head) ? 'Adds one to' : 'Subtracts one from'} ${targetWords(m[1].replace(/#/g, ''))}`, code };
162
+ if ((m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/))) return { kind: 'set', says: `Defines ${words(m[1])}`, code };
163
+ if ((m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}`, code };
164
+ if ((m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}`, code };
165
+ if ((m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/))) {
166
+ const names = m[2].split(',').map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, '')).filter(Boolean).map(words);
167
+ const value = stripTail(m[3]); const c = callee(value);
168
+ const from = c ? lastWords(c) : (sayValue(value) || words(value.split('.').pop()));
169
+ return { kind: 'set', says: `Takes ${names.slice(0, 4).join(', ')}${names.length > 4 ? ', …' : ''} from ${from}`, code };
170
+ }
171
+ if ((m = head.match(/^(?:var|const)\s*\($/))) return { kind: 'set', says: 'Declares some values', code };
172
+ if ((m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/))) return { kind: 'set', says: `Declares ${m[1].split(/\s*,\s*/).map(words).join(', ')}`, code };
173
+ // Typed declaration: Type name = value (Java, C#, C++); the value may continue on the next line.
174
+ if ((m = head.match(/^(?:final\s+|static\s+|readonly\s+)*([A-Z][\w.]*(?:<[^=]*>)?(?:\[\])?|int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto)\s+([a-zA-Z_$][\w$]*)\s*=(?!=)\s*(.*)$/))) {
175
+ const value = stripTail(m[3]); const target = words(m[2]);
176
+ const c = value ? callee(value) : null;
177
+ if (c) {
178
+ const known = sayCall(c, firstArgs(value));
179
+ if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
180
+ if (/^new\s/.test(value)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
181
+ return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
182
+ }
183
+ const v = value ? sayValue(value) : null;
184
+ return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
185
+ }
186
+ // Assignment (not comparisons)
187
+ if ((m = head.match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
188
+ const target = m[1].split(/\s*,\s*/).map(targetWords).join(', ');
189
+ const value = stripTail(m[3]);
190
+ const chain = value ? sayChain(value) : null;
191
+ if (chain) return { kind: 'set', says: `Works out ${target}: ${chain}`, code };
192
+ const c = callee(value);
193
+ if (c) {
194
+ const known = sayCall(c, firstArgs(value));
195
+ if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
196
+ if (/^new\s/.test(value)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
197
+ return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
198
+ }
199
+ if (!value) return { kind: 'set', says: `Works out ${target}`, code };
200
+ if (m[2] === '+=' || m[2] === '-=') return { kind: 'set', says: `${m[2] === '+=' ? 'Adds to' : 'Subtracts from'} ${target}`, code };
201
+ const v = sayValue(value);
202
+ return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
203
+ }
204
+ // Calls
205
+ const c = callee(head);
206
+ if (c) {
207
+ const known = sayCall(c, firstArgs(head));
208
+ return { kind: 'call', says: known || `Calls ${lastWords(c)}`, code, callee: c };
209
+ }
210
+ if ((m = head.match(/^([a-z_][\w.]*[?!]?)\s+(?![=<>!+\-*/%]|and\b|or\b|if\b|unless\b)(.+)$/)) && !/^(?:if|for|while|return|else|elsif|when|case|def|class|module|end|not|const|let|var|val|new|await|typeof|delete|void|in|of|throw|import|export|from|as|is)$/.test(m[1])) {
211
+ if (/^assert/.test(m[1])) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
212
+ const known = sayCall(m[1], m[2]);
213
+ return { kind: 'call', says: known || `Calls ${lastWords(m[1])}`, code, callee: m[1] };
214
+ }
215
+ return { kind: 'other', says: clip(head, 70), code };
216
+ }
217
+
218
+ /** Steps for a function body. `statements` are top-level [{ text, line, inner? }]. */
219
+ const spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...(s.start != null && s.end != null ? { start: s.start, end: s.end } : {}) });
220
+
221
+ export function stepsFrom(statements) {
222
+ const steps = [];
223
+ const skipped = [];
224
+ for (const s of statements) {
225
+ if (s.text && /^(?:else\b|elsif\b|end\b|\}|except\b|catch\b|finally\b|rescue\b|ensure\b|pass$|break$|continue$)/.test(s.text.trim())) { skipped.push(spanOf(s)); continue; }
226
+ if (!s.text || /^(?:else\b|elsif\b|end\b|\}|except\b|catch\b|finally\b|rescue\b|ensure\b|pass$|break$|continue$|#)/.test(s.text.trim())) continue;
227
+ const t = s.text.trim();
228
+ if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments
229
+ if (/^[)\]}]+[):;,]*$/.test(t) || /^\.\.\.$/.test(t) || /^\.[A-Za-z_]/.test(t) || /^@\w+(?:\(.*\))?$/.test(t) || /^#?\[[\w:]+(?:\(.*\))?\]$/.test(t) || /^:(?:param|rtype|return|raises|type)\b/.test(t)) { skipped.push(spanOf(s)); continue; }
230
+ const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
231
+ if (s.children?.length && ['branch', 'loop', 'try'].includes(step.kind)) {
232
+ const kids = stepsFrom(s.children.map(({ children, ...rest }) => rest)).steps;
233
+ if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); }
234
+ }
235
+ steps.push(step);
236
+ }
237
+ // Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
238
+ const more = Math.max(0, steps.length - MAX_STEPS);
239
+ return { steps, more, skipped, readable: steps.length ? steps.filter((x) => x.kind !== 'other').length / steps.length : 0 };
240
+ }
241
+
242
+ /** Top-level statements for a brace-language body, with the number of inner statements of each block. */
243
+ export function braceStatements(stmts, split = null) {
244
+ return stmts.map((s) => {
245
+ const open = s.text.indexOf('{');
246
+ // Only the first block (the "then" part of an if, the body of a loop); else-chains stay summarized.
247
+ let body = '';
248
+ if (open >= 0) {
249
+ let depth = 0, end = -1;
250
+ for (let i = open; i < s.text.length; i++) { if (s.text[i] === '{') depth++; else if (s.text[i] === '}' && --depth === 0) { end = i; break; } }
251
+ body = end > open ? s.text.slice(open + 1, end) : '';
252
+ }
253
+ const inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
254
+ const base = s.start != null && open >= 0 ? s.start + open + 1 : null;
255
+ const children = body && split ? split(body, s.line).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...(base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {}) })) : [];
256
+ return { text: s.text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children };
257
+ });
258
+ }
259
+
260
+ /** Top-level statements for an indentation body (Python) or depth body (Ruby). */
261
+ export function indentStatements(body, { depthKey = 'indent' } = {}) {
262
+ if (!body?.length) return [];
263
+ // Drop multi-line docstrings first: everything between an opening and closing triple quote.
264
+ const kept = [];
265
+ let inDoc = null, docEntry = null;
266
+ for (const l of body) {
267
+ const t = l.text.trim();
268
+ if (inDoc) { docEntry.endLine = l.line; if (t.includes(inDoc)) inDoc = null; continue; }
269
+ const q = (t.match(/^[rbuf]{0,2}("""|''')/) || [])[1];
270
+ // Docstrings are kept as one entry so they count as read (skipped as documentation, not dropped).
271
+ if (q) { const doc = { ...l, text: q, endLine: l.line }; kept.push(doc); if (t.slice(t.indexOf(q) + 3).includes(q) === false) { inDoc = q; docEntry = doc; } continue; }
272
+ kept.push(l);
273
+ }
274
+ body = kept;
275
+ if (!body.length) return [];
276
+ const base = Math.min(...body.map((l) => l[depthKey] ?? 0));
277
+ const out = [];
278
+ for (let i = 0; i < body.length; i++) {
279
+ const l = body[i];
280
+ if ((l[depthKey] ?? 0) !== base) continue;
281
+ let inner = 0;
282
+ const children = [];
283
+ let childDepth = null;
284
+ let last = l.endLine ?? l.line;
285
+ for (let k = i + 1; k < body.length && (body[k][depthKey] ?? 0) > base; k++) {
286
+ inner++;
287
+ const d = body[k][depthKey] ?? 0;
288
+ if (childDepth === null) childDepth = d;
289
+ if (d === childDepth) children.push({ text: body[k].text, line: body[k].line });
290
+ last = body[k].line;
291
+ }
292
+ // A child statement runs until the line before the next child (or the end of the block).
293
+ children.forEach((c, n) => { const next = children[n + 1]; const nextIdx = next ? body.findIndex((x) => x.line === next.line) : -1; const until = next ? body[nextIdx - 1]?.line ?? c.line : last; c.endLine = Math.max(c.line, until); });
294
+ out.push({ text: l.text, line: l.line, endLine: last, inner, children });
295
+ }
296
+ return out;
297
+ }
@@ -28,13 +28,47 @@ export function buildCases(ast) {
28
28
  return cases;
29
29
  }
30
30
 
31
- // Infer one type per input for a decision, scanning every case that targets it. Numeric usage
32
- // wins (a relational comparison must compile), then boolean, else string. Falls back to 'string'.
31
+ // A declared input type (`amount: number`, `Money`, `Flag`) as number, bool, or string; null when none.
32
+ const NUMBER_TYPES = /^(number|int|integer|long|short|float|double|decimal|Money|Percentage|Count|Duration)$/i;
33
+ const BOOL_TYPES = /^(boolean|bool|Flag)$/i;
34
+ export function declaredInputType(raw) {
35
+ const m = String(raw).match(/:\s*([A-Za-z][\w<>]*)\s*$/);
36
+ if (!m) return null;
37
+ if (NUMBER_TYPES.test(m[1])) return 'number';
38
+ if (BOOL_TYPES.test(m[1])) return 'bool';
39
+ return 'string';
40
+ }
41
+
42
+ // How each input is used in the decision's rules: compared with a number, compared with text, or on its own (a yes/no).
43
+ function usageTypes(dec, names) {
44
+ const out = {};
45
+ const NUM = /^-?\d+(\.\d+)?$/, STR = /^"[^"]*"$|^'[^']*'$/, CMP = /^(<|<=|>|>=|==|!=)$/;
46
+ for (const r of dec.rules || []) {
47
+ const toks = String(r.when || '').match(/"[^"]*"|'[^']*'|[A-Za-z_][\w.]*|-?\d+(?:\.\d+)?|<=|>=|==|!=|[<>()]/g) || [];
48
+ toks.forEach((t, i) => {
49
+ if (!names.includes(t)) return;
50
+ const op = CMP.test(toks[i + 1] || '') ? toks[i + 1] : CMP.test(toks[i - 1] || '') ? toks[i - 1] : null;
51
+ const other = op === toks[i + 1] ? toks[i + 2] : op ? toks[i - 2] : null;
52
+ if (op && NUM.test(other || '')) out[t] = 'number';
53
+ else if (op && /^[<>]=?$/.test(op) && names.includes(other || '')) out[t] = out[t] ?? 'number';
54
+ else if (op && STR.test(other || '') && out[t] !== 'number') out[t] = 'string';
55
+ else if (!op && out[t] == null) out[t] = 'bool';
56
+ });
57
+ }
58
+ return out;
59
+ }
60
+
61
+ // Infer one type per input for a decision. A declared type wins; then the values the decision's examples give
62
+ // (numeric wins, so a relational comparison compiles, then boolean); then how the rules use the input.
63
+ // Falls back to 'string'.
33
64
  export function inferInputTypes(ast, dec) {
34
65
  const names = inputNames(dec);
66
+ const declared = Object.fromEntries((dec.inputs || []).map((raw) => [String(raw).split(':')[0].trim(), declaredInputType(raw)]));
67
+ const usage = usageTypes(dec, names);
35
68
  const types = {};
36
69
  for (const n of names) {
37
- let t = 'string';
70
+ if (declared[n]) { types[n] = declared[n]; continue; }
71
+ let t = null;
38
72
  for (const test of (ast.tests || []).filter((x) => x.name === dec.name)) {
39
73
  for (const c of test.cases || []) {
40
74
  const raw = (c.given || {})[n];
@@ -42,10 +76,11 @@ export function inferInputTypes(ast, dec) {
42
76
  const cv = coerceVal(raw);
43
77
  if (typeof cv === 'number') { t = 'number'; break; }
44
78
  if (typeof cv === 'boolean' && t !== 'number') t = 'bool';
79
+ if (typeof cv === 'string' && t == null) t = 'string';
45
80
  }
46
81
  if (t === 'number') break;
47
82
  }
48
- types[n] = t;
83
+ types[n] = t ?? usage[n] ?? 'string';
49
84
  }
50
85
  return types;
51
86
  }
package/src/testing.mjs CHANGED
@@ -1,7 +1,5 @@
1
- // First-class tests , make a .intent file SELF-VERIFYING. A `test <target>` block declares
2
- // cases (for a decision) or scenarios (for a lifecycle) right next to the intent they check.
3
- // `runTests` executes them through the deterministic Intent Runtime: no AI, no code, the
4
- // spec proves itself. This is what lets intent be trustworthy , the behavior is asserted.
1
+ // Execute declared cases against the intent runtime. Passing cases are evidence for
2
+ // those inputs, not a proof of every input or of the application's implementation.
5
3
 
6
4
  import { slug } from './parse.mjs';
7
5
  import { evaluateDecision, simulateLifecycle } from './runtime.mjs';
@@ -36,18 +34,23 @@ export function runTests(ast) {
36
34
  for (const t of ast.tests || []) {
37
35
  const dec = decisions.find((d) => slug(d.name) === slug(t.name || ''));
38
36
  const lc = lifecycles.find((l) => slug(l.name) === slug(t.name || ''));
39
- for (const c of t.cases) {
37
+ if (!t.cases?.length) {
38
+ results.push({ target: t.name, case: '(empty test)', kind: 'unknown', pass: false, error: 'test block has no cases' });
39
+ }
40
+ for (const c of t.cases || []) {
40
41
  const label = { target: t.name, case: c.name || `case ${results.length + 1}` };
41
42
  if (dec) {
42
43
  const inputs = coerce(c.given);
43
44
  const run = evaluateDecision(dec, inputs);
44
- const pass = c.expect == null || String(run.result) === String(c.expect);
45
- results.push({ ...label, kind: 'decision', expected: c.expect, actual: run.result, matched: run.matched, pass, ...(run.ok ? {} : { note: 'a condition failed to evaluate' }) });
45
+ const error = !run.ok ? 'a condition failed to evaluate' : c.expect == null ? 'decision case needs an expect assertion' : null;
46
+ const pass = !error && String(run.result) === String(c.expect);
47
+ results.push({ ...label, kind: 'decision', expected: c.expect, actual: run.result, matched: run.matched, pass, ...(error ? { error, note: error } : {}) });
46
48
  } else if (lc) {
47
49
  const sim = simulateLifecycle(lc, c.events || []);
48
50
  const passState = c.expect == null || sim.finalState === c.expect;
49
- const passValid = c.expectValid == null || sim.valid === c.expectValid;
50
- results.push({ ...label, kind: 'lifecycle', expected: c.expect, actual: sim.finalState, valid: sim.valid, expectValid: c.expectValid, pass: passState && passValid });
51
+ const hasAssertion = c.expect != null || c.expectValid != null;
52
+ const passValid = sim.valid === (c.expectValid ?? true);
53
+ results.push({ ...label, kind: 'lifecycle', expected: c.expect, actual: sim.finalState, valid: sim.valid, expectValid: c.expectValid, pass: hasAssertion && passState && passValid, ...(!hasAssertion ? { error: 'scenario needs an expect, valid, or invalid assertion' } : {}) });
51
54
  } else {
52
55
  results.push({ ...label, kind: 'unknown', pass: false, error: `no decision or lifecycle named "${t.name}"` });
53
56
  }
@@ -0,0 +1,96 @@
1
+ // Node-only: Thunder a whole repository (a local folder or a public GitHub repo).
2
+ // Read-only by design: files are parsed by the Thunder code reader, never executed, imported, or built.
3
+ // A GitHub URL is shallow-cloned with `git` (argument list, no shell) into a fresh temp folder.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { mkdtempSync, rmSync, statSync } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { collectReadableFiles } from './read-repo-fs.mjs';
9
+ import { readRepo } from './read-repo.mjs';
10
+ import { plainFromReading, conditionText } from './plain-contract.mjs';
11
+
12
+ export const THUNDER_REPO_SCHEMA = 'thunder-repo-v1';
13
+ const GITHUB = /^(?:https:\/\/github\.com\/)?([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))\/([A-Za-z0-9._-]{1,100}?)(?:\.git)?\/?$/;
14
+ const MONEY = /^(amount|price|total|charge|balance|refund|cost|fee|tax|discount)/i;
15
+ const spaced = (s) => s.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
16
+
17
+ /** Parse "owner/repo" or "https://github.com/owner/repo"; returns null for anything else. */
18
+ export function parseGitHub(target) {
19
+ const m = String(target).trim().match(GITHUB);
20
+ if (!m || m[2] === '.' || m[2] === '..') return null;
21
+ return { owner: m[1], repo: m[2], url: `https://github.com/${m[1]}/${m[2]}.git` };
22
+ }
23
+
24
+ function cloneGitHub(gh, { timeoutMs = 120000 } = {}) {
25
+ const dir = mkdtempSync(join(tmpdir(), 'thunder-repo-'));
26
+ const res = spawnSync('git', ['clone', '--depth', '1', '--quiet', '--no-tags', gh.url, join(dir, 'repo')], {
27
+ timeout: timeoutMs, encoding: 'utf8', env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
28
+ });
29
+ if (res.status !== 0) { rmSync(dir, { recursive: true, force: true }); throw new Error(`Could not clone ${gh.owner}/${gh.repo}: ${(res.stderr || res.error?.message || 'git failed').trim().split('\n')[0]}`); }
30
+ const head = spawnSync('git', ['-C', join(dir, 'repo'), 'rev-parse', 'HEAD'], { encoding: 'utf8' });
31
+ return { root: join(dir, 'repo'), cleanup: () => rmSync(dir, { recursive: true, force: true }), commit: head.stdout.trim() || null };
32
+ }
33
+
34
+ /** Thunder a repository: every readable file through the code reader, every drawable decision as a Thunder card. */
35
+ export function thunderRepo(target, { maxFiles = 3000, keep = false, exampleLimit = 8 } = {}) {
36
+ const gh = parseGitHub(target);
37
+ let isDir = false;
38
+ try { isDir = statSync(target).isDirectory(); } catch { /* not a local path */ }
39
+ if (!isDir && !gh) throw new Error('Give a local folder, owner/repo, or https://github.com/owner/repo.');
40
+ const started = Date.now();
41
+ const src = isDir ? { root: target, cleanup: () => {}, commit: null } : cloneGitHub(gh);
42
+ try {
43
+ const files = collectReadableFiles(src.root, { maxFiles });
44
+ const reading = readRepo(files, { maxFiles });
45
+ const decisions = reading.items.filter((i) => i.kind === 'decision');
46
+ const cards = [], errors = [];
47
+ for (const d of decisions) {
48
+ try { const m = plainFromReading(d); if (m) cards.push({ item: d, model: m }); }
49
+ catch (e) { errors.push({ file: d.file, name: d.name, error: e instanceof Error ? e.message : String(e) }); }
50
+ }
51
+ const functions = reading.items.filter((i) => i.kind === 'function');
52
+ const asSteps = functions.filter((f) => f.steps?.length && (f.stepsReadable ?? 0) >= 0.5);
53
+ const unread = [...decisions.filter((d) => !cards.some((c) => c.item === d)), ...functions.filter((f) => !asSteps.includes(f))];
54
+ const money = cards.filter((c) => c.model.inputs.some((i) => MONEY.test(i.id)));
55
+ const examples = [...money, ...cards.filter((c) => !money.includes(c))].slice(0, exampleLimit).map(({ item, model }) => ({
56
+ file: item.file, name: item.name, line: item.line,
57
+ reads: model.rules.map((r) => `${r.outcome} when ${r.conditions.map((c) => conditionText(model, c)).join(r.join === 'all' ? ' and ' : ' or ')}`).concat(`otherwise ${model.otherwise}`),
58
+ }));
59
+ return {
60
+ schema: THUNDER_REPO_SCHEMA,
61
+ source: gh && !isDir ? `github.com/${gh.owner}/${gh.repo}` : target,
62
+ commit: src.commit,
63
+ seconds: Math.round((Date.now() - started) / 100) / 10,
64
+ languages: reading.languages,
65
+ files: reading.files.length,
66
+ skipped: reading.skipped.length,
67
+ counts: { ...reading.counts, cards: cards.length, decisionsNotDrawn: decisions.length - cards.length, functionsAsSteps: asSteps.length, functionsAsStepsMostly: functions.filter((f) => (f.stepsReadable ?? 0) >= 0.8).length, unreadFunctions: unread.length, readerErrors: errors.length },
68
+ focus: [
69
+ ...money.slice(0, 5).map(({ item }) => ({ kind: 'money', file: item.file, name: item.name, line: item.line, reason: 'Decides about money; read from code only, so a person should confirm it.' })),
70
+ ...unread.slice(0, 5).map((i) => ({ kind: 'unreadable', file: i.file, name: i.name, line: i.line, reason: 'Thunder cannot fully read this yet: read the code.' })),
71
+ ],
72
+ examples, errors,
73
+ readOnly: true,
74
+ note: 'Read from code by the Thunder code reader: no code was executed. Cards show what the code does today; a person decides whether that is what the team wants.',
75
+ ...(keep ? { localPath: src.root } : {}),
76
+ };
77
+ } finally { if (!keep) src.cleanup(); }
78
+ }
79
+
80
+ /** A short Thunder Brief for the terminal. */
81
+ export function renderThunderRepo(r) {
82
+ const langs = Object.entries(r.languages).sort((a, b) => b[1] - a[1]).map(([l, n]) => `${l} ${n}`).join(', ');
83
+ const c = r.counts;
84
+ const out = [
85
+ `Thunder Brief: ${r.source}${r.commit ? ` @ ${r.commit.slice(0, 10)}` : ''}`,
86
+ `${r.files} files read (${langs || 'none'})${r.skipped ? `, ${r.skipped} skipped` : ''}, in ${r.seconds}s. Read-only: nothing was executed.`,
87
+ `${c.decision} decisions found, ${c.cards} drawn as Thunder rule cards. ${c.function} other functions, ${c.functionsAsSteps} read as Thunder steps (${c.functionsAsStepsMostly} at least 80% readable). ${c.unreadFunctions} need a person. ${c.route ?? 0} routes.`,
88
+ ];
89
+ if (r.examples.length) {
90
+ out.push('', 'Rules read in Thunder (read from code; confirm with a person):');
91
+ for (const e of r.examples) { out.push(` ${e.file}:${e.line} ${spaced(e.name)}`); for (const line of e.reads) out.push(` ${line}`); }
92
+ }
93
+ if (r.focus.length) { out.push('', 'Thunder Focus (look here first):'); for (const f of r.focus) out.push(` [${f.kind}] ${f.file}:${f.line} ${spaced(f.name)}: ${f.reason}`); }
94
+ if (r.errors.length) { out.push('', `Reader errors (${r.errors.length}):`); for (const e of r.errors.slice(0, 5)) out.push(` ${e.file} ${e.name}: ${e.error}`); }
95
+ return out.join('\n');
96
+ }
@@ -0,0 +1,24 @@
1
+ export const WRITE_SCHEMA: 'thunder-write-v1';
2
+ export interface ChangedCase { inputs: Record<string, string | number | boolean>; before: string; after: string }
3
+ export interface ChangedCases { checked: number; changed: ChangedCase[]; note: string }
4
+ export interface WriteChange { line: number; column: number; before: string; after: string }
5
+ export function writeRule(args: {
6
+ source: string; language?: string; file?: string; decision: string; line?: number | null;
7
+ /** 1-based rule number, or 'otherwise' for the fallback answer. */
8
+ rule: number | 'otherwise';
9
+ /** The rule's new condition in Thunder form (amount < 75). Only numbers, comparisons, and text may change. */
10
+ when?: string | null;
11
+ /** The rule's new answer (Review). */
12
+ answer?: string | null;
13
+ }):
14
+ | { schema: 'thunder-write-v1'; ok: true; source: string; problems: []; decision: string; rule: number | 'otherwise'; change: WriteChange[]; before: string; after: string; cases: ChangedCases }
15
+ | { schema: 'thunder-write-v1'; ok: false; source: string; problems: string[] };
16
+ export function changedCases(before: unknown, after: unknown): ChangedCases;
17
+ export type RulePart =
18
+ | { kind: 'number'; value: number }
19
+ | { kind: 'text'; value: string }
20
+ | { kind: 'comparison'; value: '<' | '<=' | '>' | '>=' | '==' | '!='; words: string }
21
+ | { kind: 'fixed'; value: string; words: string };
22
+ export const COMPARISON_CHOICES: Array<{ op: '<' | '<=' | '>' | '>=' | '==' | '!='; words: string }>;
23
+ export function ruleParts(when: string): RulePart[];
24
+ export function joinRuleParts(parts: RulePart[]): string;