@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
@@ -0,0 +1,339 @@
1
+ // Experimental plain-English notation (`.thunder-plain`). A deliberately small,
2
+ // strict subset that reads like a policy. It lowers to ordinary ThunderLang, so
3
+ // the existing parser, runtime, tests and code generators do all the real work.
4
+ // Nothing is guessed: a line that does not match the grammar is an error with
5
+ // its line number and an example of what to write instead.
6
+ import { parseIntent } from './parse.mjs';
7
+ import { compileExpr } from './expr.mjs';
8
+ import { runTests } from './testing.mjs';
9
+ import { evaluateDecision } from './runtime.mjs';
10
+
11
+ export const PLAIN_SCHEMA = 'thunder-plain-v1';
12
+
13
+ /** Comparison phrases. The first spelling is the canonical one used when rendering. */
14
+ export const COMPARISONS = [
15
+ { op: '>=', words: ['at least'] },
16
+ { op: '<=', words: ['at most'] },
17
+ { op: '<', words: ['under', 'less than', 'below'] },
18
+ { op: '>', words: ['over', 'more than', 'above'] },
19
+ { op: '==', words: ['exactly'] },
20
+ ];
21
+ const opWord = op => COMPARISONS.find(c => c.op === op)?.words[0] ?? op;
22
+
23
+ const fail = (line, text) => { throw new Error(`Line ${line}: ${text}`); };
24
+ const OUTCOME = /^[A-Z][A-Za-z]*$/;
25
+ const NAME_TEXT = /^[A-Za-z0-9 $.,'_-]+$/;
26
+ const lowerFirst = s => s.charAt(0).toLowerCase() + s.slice(1);
27
+ const pascal = s => s.replace(/[^A-Za-z0-9 ]/g, ' ').trim().split(/\s+/).filter(Boolean)
28
+ .map(w => w[0].toUpperCase() + w.slice(1)).join('');
29
+ const camel = s => lowerFirst(pascal(s));
30
+ const RESERVED = new Set(['and', 'or', 'not', 'in', 'true', 'false', 'case', 'expect']);
31
+
32
+ /** Format a number for a reader: dollar inputs get a $ sign, negatives read -$1. */
33
+ export function formatValue(input, value) {
34
+ if (input.kind === 'yesno') return value ? input.yes : input.no;
35
+ if (input.kind === 'text') return value === '' ? 'empty' : JSON.stringify(String(value));
36
+ if (input.kind === 'dollars') return `${value < 0 ? '-' : ''}$${Math.abs(value)}`;
37
+ return String(value);
38
+ }
39
+
40
+ function parseNumber(text, input, line) {
41
+ const t = text.trim().replace(/,/g, '');
42
+ const dollars = t.match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
43
+ if (input.kind === 'dollars') {
44
+ if (!dollars) fail(line, `${input.label} is in dollars. Write an amount such as $100.`);
45
+ return Number(`${dollars[1] || dollars[2] ? '-' : ''}${dollars[3]}`);
46
+ }
47
+ if (dollars) fail(line, `${input.label} is a plain number, not dollars. Write it without $.`);
48
+ if (!/^-?\d+(?:\.\d+)?$/.test(t)) fail(line, `Write a number for ${input.label}, such as 18.`);
49
+ return Number(t);
50
+ }
51
+
52
+ function parseInputLine(text, line) {
53
+ let m;
54
+ if ((m = text.match(/^whether it is (.+?) or (.+?)\.?$/))) {
55
+ const [yes, no] = [m[1].trim(), m[2].trim()];
56
+ if (yes === no) fail(line, 'Use two different words, such as "whether it is on time or late".');
57
+ return { id: camel(yes), kind: 'yesno', label: `it is ${yes}`, yes, no };
58
+ }
59
+ if ((m = text.match(/^(the .+?), (in dollars|a number)\.?$/))) {
60
+ const label = m[1].trim();
61
+ return { id: camel(label.replace(/^the /, '')), kind: m[2] === 'in dollars' ? 'dollars' : 'number', label };
62
+ }
63
+ fail(line, 'Describe each input as "the amount, in dollars", "the age, a number", or "whether it is on time or late".');
64
+ }
65
+
66
+ function parseCondition(text, inputs, line) {
67
+ const t = text.replace(/^[-•]\s*/, '').replace(/\.$/, '').trim();
68
+ let m;
69
+ if ((m = t.match(/^it is (.+)$/))) {
70
+ const word = m[1].trim();
71
+ const input = inputs.find(i => i.kind === 'yesno' && (i.yes === word || i.no === word));
72
+ if (input) return { input: input.id, op: 'is', value: input.yes === word };
73
+ }
74
+ for (const input of inputs.filter(i => i.kind !== 'yesno')) {
75
+ if (!t.startsWith(`${input.label} is `)) continue;
76
+ const rest = t.slice(input.label.length + 4);
77
+ for (const c of COMPARISONS) for (const w of c.words) {
78
+ if (rest.startsWith(`${w} `)) return { input: input.id, op: c.op, value: parseNumber(rest.slice(w.length + 1), input, line) };
79
+ }
80
+ fail(line, `Compare ${input.label} with at least, at most, under, over, or exactly. For example: "${input.label} is at most ${formatValue(input, 100)}".`);
81
+ }
82
+ const known = inputs.map(i => (i.kind === 'yesno' ? `"it is ${i.yes}"` : `"${i.label} is …"`)).join(', ');
83
+ fail(line, `This condition does not name an input. Start with one of: ${known}.`);
84
+ }
85
+
86
+ /** Parse plain text into the structured model the visual card edits. */
87
+ export function parsePlainContract(source) {
88
+ if (typeof source !== 'string' || source.length > 100000) throw new Error('A plain contract must be text of at most 100 KB.');
89
+ const rows = source.split(/\r?\n/).map((raw, i) => ({ text: raw.trim(), depth: raw.match(/^\s*/)[0].replace(/\t/g, ' ').length, line: i + 1 }))
90
+ .filter(r => r.text && !r.text.startsWith('#'));
91
+ if (!rows.length) throw new Error('Start with a title, such as "Refund approval".');
92
+ const model = { schema: PLAIN_SCHEMA, title: '', why: '', question: '', inputs: [], rules: [], otherwise: '', examples: [] };
93
+ let section = null, rule = null;
94
+ for (const row of rows) {
95
+ const { text, depth, line } = row;
96
+ if (depth === 0) {
97
+ rule = null;
98
+ if (!model.title) { model.title = text.replace(/\.$/, ''); if (!pascal(model.title)) fail(line, 'Give the contract a title with letters, such as "Refund approval".'); continue; }
99
+ if (/^why:/i.test(text)) { model.why = text.replace(/^why:\s*/i, ''); section = null; continue; }
100
+ if (text === 'We need') { section = 'inputs'; continue; }
101
+ if (text === 'Examples') { section = 'examples'; continue; }
102
+ if (text.endsWith('?')) {
103
+ if (model.question) fail(line, 'This notation holds one decision per contract. Put another decision in its own file.');
104
+ if (!model.inputs.length) fail(line, 'List the inputs under "We need" before the decision.');
105
+ model.question = text; section = 'decision'; continue;
106
+ }
107
+ fail(line, 'Expected "Why: …", "We need", a decision question ending in ?, or "Examples".');
108
+ }
109
+ if (section === 'inputs') {
110
+ const input = parseInputLine(text, line);
111
+ if (RESERVED.has(input.id) || !input.id) fail(line, 'Choose a different name for this input.');
112
+ if (model.inputs.some(i => i.id === input.id)) fail(line, `${input.label} is listed twice.`);
113
+ const words = model.inputs.flatMap(i => (i.kind === 'yesno' ? [i.yes, i.no] : []));
114
+ if (input.kind === 'yesno' && (words.includes(input.yes) || words.includes(input.no))) fail(line, 'Each yes/no word must be unique across inputs.');
115
+ model.inputs.push(input);
116
+ } else if (section === 'decision') {
117
+ let m;
118
+ if (rule && depth > rule.depth) { rule.conditions.push(parseCondition(text, model.inputs, line)); continue; }
119
+ if ((m = text.match(/^Otherwise,?\s+([A-Za-z]+)\.?$/))) {
120
+ if (model.otherwise) fail(line, 'Use one "Otherwise" result.');
121
+ if (!OUTCOME.test(m[1])) fail(line, 'Name the outcome with one capitalized word, such as Review.');
122
+ model.otherwise = m[1]; rule = null; continue;
123
+ }
124
+ if (model.otherwise) fail(line, 'Put every rule before "Otherwise".');
125
+ if ((m = text.match(/^([A-Za-z]+) when (all|any) of these (?:are|is) true:?$/))) {
126
+ if (!OUTCOME.test(m[1])) fail(line, 'Name the outcome with one capitalized word, such as Approve.');
127
+ rule = { outcome: m[1], join: m[2], conditions: [], depth, line };
128
+ model.rules.push(rule); continue;
129
+ }
130
+ if ((m = text.match(/^([A-Za-z]+) when (.+)$/))) {
131
+ if (!OUTCOME.test(m[1])) fail(line, 'Name the outcome with one capitalized word, such as Approve.');
132
+ model.rules.push({ outcome: m[1], join: 'all', conditions: [parseCondition(m[2], model.inputs, line)], depth, line });
133
+ rule = null; continue;
134
+ }
135
+ fail(line, 'Write a rule as "Approve when all of these are true:" with conditions indented below, then "Otherwise, Review."');
136
+ } else if (section === 'examples') {
137
+ const m = text.match(/^(.+?)\s+gives\s+([A-Za-z]+)\s*(?:\((.+)\))?\.?$/);
138
+ if (!m) fail(line, `Write an example as "${model.inputs.map(i => formatValue(i, i.kind === 'yesno' ? true : 100)).join(', ')} gives Approve (a short name)".`);
139
+ const parts = m[1].split(/,\s+/);
140
+ if (parts.length !== model.inputs.length) fail(line, `Give ${model.inputs.length} values in this order: ${model.inputs.map(i => (i.kind === 'yesno' ? `${i.yes} or ${i.no}` : i.label)).join(', ')}. A missing value is not the same as no.`);
141
+ const values = {};
142
+ model.inputs.forEach((input, i) => {
143
+ const part = parts[i].trim();
144
+ if (input.kind === 'yesno') {
145
+ if (part !== input.yes && part !== input.no) fail(line, `Write "${input.yes}" or "${input.no}" for value ${i + 1}.`);
146
+ values[input.id] = part === input.yes;
147
+ } else values[input.id] = parseNumber(part, input, line);
148
+ });
149
+ const name = (m[3] ?? `example ${model.examples.length + 1}`).trim();
150
+ if (!NAME_TEXT.test(name)) fail(line, 'Use letters, numbers, spaces, $ and simple punctuation in the example name.');
151
+ if (model.examples.some(e => e.name === name)) fail(line, `Two examples are named "${name}". Give each a different name.`);
152
+ model.examples.push({ name, values, expected: m[2], line });
153
+ } else fail(line, 'This indented line does not belong to "We need", a decision, or "Examples".');
154
+ }
155
+ if (!model.question) throw new Error('Add a decision question ending in ?, such as "When do we approve a refund?"');
156
+ for (const r of model.rules) if (!r.conditions.length) fail(r.line, 'List at least one condition under this rule, indented.');
157
+ if (!model.rules.length) throw new Error('Add at least one rule, such as "Approve when all of these are true:".');
158
+ if (!model.otherwise) throw new Error('Finish the decision with "Otherwise, <Outcome>." so every request gets an answer.');
159
+ if (!model.examples.length) throw new Error('Add at least one example under "Examples".');
160
+ const outcomes = outcomesOf(model);
161
+ for (const e of model.examples) if (!outcomes.includes(e.expected)) fail(e.line, `Unknown outcome ${e.expected}. Use one of: ${outcomes.join(', ')}.`);
162
+ // Positions are parse metadata; keep the model a pure description.
163
+ model.rules = model.rules.map(({ outcome, join, conditions }) => ({ outcome, join, conditions }));
164
+ model.examples = model.examples.map(({ name, values, expected }) => ({ name, values, expected }));
165
+ return model;
166
+ }
167
+
168
+ export function outcomesOf(model) {
169
+ return [...new Set([...model.rules.map(r => r.outcome), model.otherwise])];
170
+ }
171
+
172
+ /** Read one condition as English, e.g. "the amount is at most $100". */
173
+ export function conditionText(model, c) {
174
+ const input = model.inputs.find(i => i.id === c.input);
175
+ if (!input) return '(unknown input)';
176
+ if (input.kind === 'yesno') return `it is ${c.value ? input.yes : input.no}`;
177
+ if (input.kind === 'text') return `${input.label} is ${c.op === '!=' ? 'not ' : ''}${formatValue(input, c.value)}`;
178
+ return `${input.label} is ${opWord(c.op)} ${formatValue(input, c.value)}`;
179
+ }
180
+
181
+ /** Render the model as plain text. parsePlainContract(renderPlainContract(m)) round-trips. */
182
+ export function renderPlainContract(model) {
183
+ const out = [model.title];
184
+ if (model.why) out.push(`Why: ${model.why}`);
185
+ out.push('', 'We need');
186
+ for (const i of model.inputs) out.push(` ${i.kind === 'yesno' ? `whether it is ${i.yes} or ${i.no}` : `${i.label}, ${i.kind === 'dollars' ? 'in dollars' : 'a number'}`}`);
187
+ out.push('', model.question);
188
+ for (const r of model.rules) {
189
+ if (r.conditions.length === 1) out.push(` ${r.outcome} when ${conditionText(model, r.conditions[0])}.`);
190
+ else {
191
+ out.push(` ${r.outcome} when ${r.join} of these ${r.join === 'all' ? 'are' : 'is'} true:`);
192
+ for (const c of r.conditions) out.push(` ${conditionText(model, c)}`);
193
+ }
194
+ }
195
+ out.push(` Otherwise, ${model.otherwise}.`, '', 'Examples');
196
+ const cells = model.examples.map(e => [model.inputs.map(i => formatValue(i, e.values[i.id])).join(', '), `gives ${e.expected}`, `(${e.name})`]);
197
+ const w0 = Math.max(...cells.map(c => c[0].length)), w1 = Math.max(...cells.map(c => c[1].length));
198
+ for (const c of cells) out.push(` ${c[0].padEnd(w0)} ${c[1].padEnd(w1)} ${c[2]}`);
199
+ return out.join('\n') + '\n';
200
+ }
201
+
202
+ function conditionExpr(model, c) {
203
+ const input = model.inputs.find(i => i.id === c.input);
204
+ if (input.kind === 'yesno') return `${input.id} == ${c.value}`;
205
+ if (input.kind === 'text') return `${input.id} ${c.op === '!=' ? '!=' : '=='} ${JSON.stringify(String(c.value))}`;
206
+ return `${input.id} ${c.op} ${c.value}`;
207
+ }
208
+
209
+ /** Lower the model to ordinary ThunderLang source. */
210
+ export function plainToThunder(model) {
211
+ const name = pascal(model.title);
212
+ const lit = v => (typeof v === 'boolean' ? String(v) : String(v));
213
+ const out = [`# Compiled from plain ThunderLang (${PLAIN_SCHEMA}). Edit the plain file, not this one.`,
214
+ `mission ${name}`, '', `title ${JSON.stringify(model.title)}`, '', 'goal', ` ${model.why || model.title}`,
215
+ '', `# ${model.question}`, `decision ${name}`, ' inputs', ...model.inputs.map(i => ` ${i.id}${i.kind === 'yesno' ? ': boolean' : i.kind === 'number' || i.kind === 'dollars' ? ': number' : i.kind === 'text' ? ': string' : ''}`)];
216
+ const used = new Map();
217
+ for (const r of model.rules) {
218
+ const base = lowerFirst(r.outcome); const n = (used.get(base) ?? 0) + 1; used.set(base, n);
219
+ out.push(` rule ${n === 1 ? base : `${base}_${n}`}`, ` when ${r.conditions.map(c => conditionExpr(model, c)).join(r.join === 'all' ? ' and ' : ' or ')}`, ` return ${r.outcome}`);
220
+ }
221
+ out.push(' default', ` return ${model.otherwise}`, '', `test ${name}`);
222
+ for (const e of model.examples) {
223
+ out.push(` case ${e.name}`, ` given ${model.inputs.map(i => `${i.id} ${lit(e.values[i.id])}`).join(', ')}`, ` expect ${e.expected}`);
224
+ }
225
+ return out.join('\n') + '\n';
226
+ }
227
+
228
+ export function compilePlainContract(source) {
229
+ return plainToThunder(parsePlainContract(source));
230
+ }
231
+
232
+ /**
233
+ * Decide one request with the real runtime and explain it in the reader's words.
234
+ * The outcome comes from evaluateDecision on the compiled contract; the per-condition
235
+ * check marks come from the same expression engine, condition by condition.
236
+ */
237
+ export function explainPlain(model, values, ast = parseIntent(plainToThunder(model))) {
238
+ const run = evaluateDecision(ast.decisions[0], values);
239
+ const rules = model.rules.map(r => ({
240
+ outcome: r.outcome, join: r.join,
241
+ checks: r.conditions.map(c => ({ text: conditionText(model, c), ok: !!compileExpr(conditionExpr(model, c))(values), actual: formatValue(model.inputs.find(i => i.id === c.input), values[c.input]), input: c.input })),
242
+ }));
243
+ const index = run.matched === 'default' ? -1 : (ast.decisions[0].rules.findIndex(r => r.name === run.matched));
244
+ return { outcome: run.result, ruleIndex: index, rules, ok: run.ok };
245
+ }
246
+
247
+ /** Everything the reading surface needs: model, compiled source, and executed examples. */
248
+ export function previewPlainContract(sourceOrModel) {
249
+ const model = typeof sourceOrModel === 'string' ? parsePlainContract(sourceOrModel) : sourceOrModel;
250
+ const canonicalSource = plainToThunder(model);
251
+ const ast = parseIntent(canonicalSource);
252
+ const results = runTests(ast).results.map((r, i) => ({
253
+ name: model.examples[i].name, values: model.examples[i].values, expected: r.expected, actual: r.actual, pass: !!r.pass && !r.error,
254
+ }));
255
+ return {
256
+ schema: PLAIN_SCHEMA, experimental: true, model, canonicalSource, plainSource: renderPlainContract(model),
257
+ tests: { total: results.length, passed: results.filter(r => r.pass).length, failed: results.filter(r => !r.pass).length, results },
258
+ application: 'not_checked',
259
+ };
260
+ }
261
+
262
+ const spaced = s => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, ' ').toLowerCase();
263
+
264
+ /**
265
+ * "Thunder" a decision the code reader lifted from any supported language into the visual
266
+ * model. Only simple shapes are accepted (comparisons with numbers, yes/no flags, joined by
267
+ * all-and or all-or); anything else returns null so the caller shows the reader's own sentence
268
+ * instead of an invented picture. Names come from the code, so the result needs human review:
269
+ * the code cannot say that a number is money or what a flag means in business words.
270
+ */
271
+ export function plainFromReading(item) {
272
+ if (!item || item.kind !== 'decision' || !item.rules?.length || !item.otherwise) return null;
273
+ // Untyped languages (JavaScript, Ruby, untyped Python): infer a type only from how the rule uses the input,
274
+ // and say so in needsReview. Compared with a number -> number; used alone as a condition -> yes/no.
275
+ const inferred = [];
276
+ const whens = (item.rules ?? []).map(r => r.when ?? '').join(' and ');
277
+ const typed = (item.inputs ?? []).map(i => {
278
+ if (i.type) return i;
279
+ const esc = i.name.replace(/[$]/g, '\\$');
280
+ if (new RegExp(`\\b${esc}\\s*(>=|<=|<|>|==)\\s*-?\\d`).test(whens)) { inferred.push(i.name); return { ...i, type: 'number' }; }
281
+ if (new RegExp(`(^|\\s|not\\s+|!)${esc}(\\s|$)`).test(whens)) { inferred.push(i.name); return { ...i, type: 'boolean' }; }
282
+ return i;
283
+ });
284
+ const inputs = typed.map(i => (i.type === 'boolean'
285
+ ? { id: i.name, kind: 'yesno', label: `it is ${spaced(i.name)}`, yes: spaced(i.name), no: `not ${spaced(i.name)}` }
286
+ : i.type === 'number' ? { id: i.name, kind: 'number', label: `the ${spaced(i.name)}` }
287
+ : { id: i.name, kind: 'other', label: `the ${spaced(i.name)}` }));
288
+ const model = { schema: PLAIN_SCHEMA, title: spaced(item.name).replace(/^./, c => c.toUpperCase()), why: '',
289
+ question: `How is ${spaced(item.name)} decided?`, inputs, rules: [], otherwise: '', examples: [],
290
+ provenance: 'inferred-from-code', needsReview: [] };
291
+ const outcome = t => (/^[A-Za-z_][A-Za-z0-9_]*$/.test(t) || /^-?\d+(\.\d+)?$/.test(t) ? t : null);
292
+ const stateFacts = [];
293
+ const input = id => inputs.find(i => i.id === id);
294
+ // A bare name or path the function reads that is not a parameter (a field, a method with no
295
+ // arguments): shown as a yes/no fact and flagged, because it comes from the code's state.
296
+ const factFor = path => {
297
+ const id = path.replace(/[^A-Za-z0-9_]/g, '_');
298
+ let f = input(id);
299
+ if (!f) {
300
+ const word = spaced(path.split('.').pop());
301
+ f = { id, kind: 'yesno', label: `it is ${word}`, yes: word, no: `not ${word}`, fromState: true };
302
+ if (inputs.some(i => i.kind === 'yesno' && (i.yes === f.yes || i.no === f.yes))) return null;
303
+ inputs.push(f); stateFacts.push(path);
304
+ }
305
+ return f;
306
+ };
307
+ for (const r of item.rules) {
308
+ const when = r.when.trim();
309
+ const join = / or /.test(when) ? 'any' : 'all';
310
+ if (/ or /.test(when) && / and /.test(when)) return null;
311
+ const conditions = [];
312
+ for (const part of when.split(join === 'all' ? ' and ' : ' or ')) {
313
+ const t = part.trim(); let m;
314
+ const input = id => inputs.find(i => i.id === id);
315
+ if ((m = t.match(/^(not\s+|!)?([A-Za-z_]\w*)$/)) && input(m[2])?.kind === 'yesno') conditions.push({ input: m[2], op: 'is', value: !m[1] });
316
+ else if ((m = t.match(/^([A-Za-z_]\w*)\s*(>=|<=|<|>|==)\s*(-?\d+(?:\.\d+)?)$/)) && input(m[1])?.kind === 'number') conditions.push({ input: m[1], op: m[2], value: Number(m[3]) });
317
+ else if ((m = t.match(/^([A-Za-z_][\w.]*)\s*(==|!=)\s*"([^"]*)"$/))) {
318
+ let f = input(m[1]);
319
+ if (!f) { const id = m[1].replace(/[^A-Za-z0-9_]/g, '_'); f = { id, kind: 'text', label: `the ${spaced(m[1].split('.').pop())}` }; if (m[1].includes('.')) stateFacts.push(m[1]); inputs.push(f); }
320
+ if (f.kind === 'yesno' || f.kind === 'number') return null;
321
+ f.kind = 'text'; conditions.push({ input: f.id, op: m[2], value: m[3] });
322
+ }
323
+ else if ((m = t.match(/^(not\s+|!)?([A-Za-z_][\w.]*)$/)) && !input(m[2])) { const f = factFor(m[2]); if (!f) return null; conditions.push({ input: f.id, op: 'is', value: !m[1] }); }
324
+ else return null;
325
+ }
326
+ if (!outcome(r.result)) return null;
327
+ model.rules.push({ outcome: r.result, join, conditions });
328
+ }
329
+ if (!outcome(item.otherwise.result)) return null;
330
+ model.otherwise = item.otherwise.result;
331
+ for (const i of inputs) {
332
+ model.needsReview.push(i.kind === 'yesno' ? `What does "${i.yes}" mean in business words?` : `Is ${i.label} money, a count, or something else?`);
333
+ }
334
+ for (const path of stateFacts) model.needsReview.push(`${spaced(path.split('.').pop())} comes from the code's own state, not from an input.`);
335
+ if (item.status === 'partial') { model.partial = true; model.needsReview.unshift(`Thunder could not read ${item.unread?.length || 'some'} line(s) of this function, so the picture may be incomplete.`); }
336
+ for (const name of inferred) model.needsReview.push(`The code does not declare a type for ${spaced(name)}; Thunder inferred it from how the rule uses it.`);
337
+ model.needsReview.push('Why does this rule exist? Code shows what happens, not why.', 'No examples yet: add cases before relying on it.');
338
+ return model;
339
+ }
@@ -0,0 +1,6 @@
1
+ import type { ReadItem } from './read.mjs';
2
+ export const PROMOTE_SCHEMA: 'thunder-promotion-v1';
3
+ export type Promotion =
4
+ | { schema: 'thunder-promotion-v1'; ok: true; name: string; source: string; examples: number; notes: string[] }
5
+ | { ok: false; reason: string };
6
+ export function promoteDecision(item: ReadItem & { file?: string }, options?: { file?: string }): Promotion;
@@ -0,0 +1,179 @@
1
+ // Promote a reading to a rule: turn a decision recovered by the reader (read.mjs) into a readable
2
+ // ThunderLang contract with starter examples, so a person can confirm it and from then on every change
3
+ // is checked against it. Deterministic, no AI, browser-safe.
4
+ //
5
+ // The examples are characterization examples: their expected answers are computed from the recovered
6
+ // rule, so they record what the code does TODAY, not what it should do. They are chosen where mistakes
7
+ // hide: one example per rule, plus both sides of every numeric threshold. The contract says so in its
8
+ // header; a person confirms each answer or changes it.
9
+ import { parseIntent } from './parse.mjs';
10
+ import { tokenize } from './expr.mjs';
11
+ import { evaluateDecision } from './runtime.mjs';
12
+ import { sayCondition } from './read.mjs';
13
+
14
+ export const PROMOTE_SCHEMA = 'thunder-promotion-v1';
15
+
16
+ const pascal = (s) => String(s).replace(/(^|[_\s-]+)([a-zA-Z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/[^A-Za-z0-9]/g, '') || 'Rule';
17
+ const flat = (path) => path.split('.').map((seg, i) => (i ? seg[0].toUpperCase() + seg.slice(1) : seg)).join('');
18
+ const OUTCOME = /^[A-Za-z_][A-Za-z0-9_]*$/;
19
+ const STRING_LIT = /^[A-Za-z0-9 _-]*$/;
20
+
21
+ /**
22
+ * Inputs a condition references, with how each is used: compared to a number, to text, or alone.
23
+ * Only the function's parameters (and fields on them) are inputs; any other bare name in a condition
24
+ * is an enum value (plan == FREE), which a contract compares as text.
25
+ */
26
+ function usage(conditions, params) {
27
+ const isInput = (name) => (params.size ? params.has(name.split('.')[0]) : !/^[A-Z]/.test(name));
28
+ const refs = new Map(); // path -> { numbers:Set, strings:Set, bare:boolean }
29
+ const entry = (name) => { if (!refs.has(name)) refs.set(name, { numbers: new Set(), strings: new Set(), bare: false }); return refs.get(name); };
30
+ for (const cond of conditions) {
31
+ const toks = tokenize(cond);
32
+ toks.forEach((t, i) => {
33
+ if (t.t !== 'id' || !isInput(t.v)) return;
34
+ const u = entry(t.v);
35
+ const after = toks[i + 1]?.t === 'op';
36
+ const op = after ? toks[i + 1] : toks[i - 1]?.t === 'op' ? toks[i - 1] : null;
37
+ const other = after ? toks[i + 2] : toks[i - 1]?.t === 'op' ? toks[i - 2] : null;
38
+ if (op && other?.t === 'num') u.numbers.add(other.v);
39
+ else if (op && other?.t === 'str') u.strings.add(other.v);
40
+ else if (op && other?.t === 'id' && !isInput(other.v)) u.strings.add(other.v); // enum member
41
+ else if (op && other?.t === 'id') u.numbers.add(0); // compared with another input
42
+ else if (!op) u.bare = true;
43
+ });
44
+ }
45
+ return refs;
46
+ }
47
+
48
+ function candidates(type, u) {
49
+ if (type === 'boolean') return [false, true];
50
+ if (type === 'string') return [...u.strings].concat('other').filter((s, i, a) => a.indexOf(s) === i);
51
+ const out = new Set();
52
+ for (const n of u.numbers) {
53
+ const step = Number.isInteger(n) ? 1 : 0.01;
54
+ for (const v of [n - step, n, n + step]) out.add(Math.round(v * 100) / 100);
55
+ }
56
+ if (!out.size) out.add(0);
57
+ return [...out].sort((a, b) => a - b);
58
+ }
59
+
60
+ /** Every combination of candidate values, capped; past the cap, vary one input at a time from a base. */
61
+ function assignments(inputs, values, cap = 4096) {
62
+ const total = inputs.reduce((n, i) => n * values[i].length, 1);
63
+ if (total <= cap) {
64
+ let acc = [{}];
65
+ for (const name of inputs) acc = acc.flatMap((a) => values[name].map((v) => ({ ...a, [name]: v })));
66
+ return acc;
67
+ }
68
+ const base = Object.fromEntries(inputs.map((n) => [n, values[n][0]]));
69
+ return [base, ...inputs.flatMap((n) => values[n].map((v) => ({ ...base, [n]: v })))];
70
+ }
71
+
72
+ const lit = (v) => (typeof v === 'string' ? JSON.stringify(v) : String(v));
73
+
74
+ /**
75
+ * The recovered rule as something that can run: plain input names, candidate values on both sides of every
76
+ * threshold, and an evaluator. `extraConditions` widens the candidate values (Thunder write uses the edited
77
+ * rule's conditions, so the before and after versions are checked on the same inputs).
78
+ * Returns { ok: true, notes, refs, renames, names, types, values, rules, decisionName, canonical, run, all }
79
+ * or { ok: false, reason }.
80
+ */
81
+ export function recoverModel(item, { extraConditions = [] } = {}) {
82
+ if (!item || item.kind !== 'decision' || !item.rules?.length || !item.otherwise) return { ok: false, reason: 'Only decisions (functions that choose between fixed answers) can become a contract.' };
83
+ const results = [...item.rules.map((r) => r.result), item.otherwise.result];
84
+ const bad = results.find((r) => !OUTCOME.test(r));
85
+ if (bad) return { ok: false, reason: `The answer ${bad} is not a name. Contracts answer with names such as Approve or Review.` };
86
+ // Flatten field paths (order.total -> orderTotal) so every input is a plain name.
87
+ const notes = [];
88
+ const renames = new Map();
89
+ const conditions = [...item.rules.map((r) => r.when), ...extraConditions];
90
+ const refs = usage(conditions, new Set((item.inputs || []).map((p) => p.name)));
91
+ for (const path of refs.keys()) if (path.includes('.')) { renames.set(path, flat(path)); notes.push(`${flat(path)} stands for ${path} in the code.`); }
92
+ const rewrite = (cond) => tokenize(cond).map((t) => {
93
+ if (t.t === 'id') return refs.has(t.v) ? (renames.get(t.v) ?? t.v) : JSON.stringify(t.v); // enum members are text in a contract
94
+ if (t.t === 'str') return JSON.stringify(t.v);
95
+ if (t.t === 'num' || t.t === 'bool') return String(t.v);
96
+ return t.v;
97
+ }).join(' ').replace(/\( /g, '(').replace(/ \)/g, ')');
98
+ const declared = new Map((item.inputs || []).map((p) => [p.name, p.type]));
99
+ // Keep the function's own parameter order; flattened fields follow their object parameter.
100
+ const order = (path) => { const i = (item.inputs || []).findIndex((p) => p.name === path.split('.')[0]); return i < 0 ? 999 : i; };
101
+ const names = [...refs.keys()].sort((a, b) => order(a) - order(b)).map((p) => renames.get(p) ?? p);
102
+ if (!names.length) return { ok: false, reason: 'The rules do not depend on any input, so there is nothing to give examples for.' };
103
+ const types = {}, values = {};
104
+ for (const [path, u] of refs) {
105
+ const name = renames.get(path) ?? path;
106
+ const t = declared.get(path);
107
+ types[name] = ['number', 'boolean', 'string'].includes(t) && !(t !== 'string' && u.strings.size) ? t : u.strings.size ? 'string' : u.numbers.size ? 'number' : 'boolean';
108
+ for (const s of u.strings) if (!STRING_LIT.test(s)) return { ok: false, reason: `The text "${s}" has characters a contract example cannot hold yet.` };
109
+ values[name] = candidates(types[name], u);
110
+ }
111
+ const rules = item.rules.map((r) => ({ when: rewrite(r.when), result: r.result }));
112
+ const decisionName = pascal(item.name);
113
+
114
+ // Evaluate the recovered rule to choose examples where it changes its answer.
115
+ const canonical = parseIntent([`decision ${decisionName}`, ' inputs', ...names.map((n) => ` ${n}`),
116
+ ...rules.flatMap((r, i) => [` rule r${i + 1}`, ` when ${r.when}`, ` return ${r.result}`]), ' default', ` return ${item.otherwise.result}`].join('\n')).decisions[0];
117
+ const run = (a) => evaluateDecision(canonical, a);
118
+ const all = assignments(names, values).map((a) => ({ a, r: run(a) }));
119
+ return { ok: true, notes, refs, renames, names, types, values, rules, decisionName, canonical, run, all };
120
+ }
121
+
122
+ /**
123
+ * Turn a decision item from readCode/readRepo into a readable contract.
124
+ * Returns { ok: true, source, name, examples, notes } or { ok: false, reason }.
125
+ */
126
+ export function promoteDecision(item, { file = item.file || '' } = {}) {
127
+ const model = recoverModel(item);
128
+ if (!model.ok) return model;
129
+ const { notes, refs, renames, names, types, rules, decisionName, run, all } = model;
130
+ const results = [...item.rules.map((r) => r.result), item.otherwise.result];
131
+ const chosen = [];
132
+ const key = (a) => names.map((n) => lit(a[n])).join('|');
133
+ const add = (a, label) => {
134
+ if (chosen.length >= 10 || chosen.some((c) => key(c.a) === key(a) || c.label === label)) return;
135
+ chosen.push({ a, label, result: run(a).result });
136
+ };
137
+ // One example per rule (and the fallback), in rule order.
138
+ rules.forEach((r, i) => { const hit = all.find((x) => x.r.matched === `r${i + 1}`); if (hit) add(hit.a, `when ${sayCondition(r.when)}`); });
139
+ const fallback = all.find((x) => x.r.matched === 'default');
140
+ if (fallback) add(fallback.a, 'when no rule matches');
141
+ // Both sides of each numeric threshold, where the answer changes.
142
+ for (const [path, u] of refs) {
143
+ const name = renames.get(path) ?? path;
144
+ if (types[name] !== 'number') continue;
145
+ for (const n of u.numbers) {
146
+ const step = Number.isInteger(n) ? 1 : 0.01;
147
+ for (const x of all) {
148
+ if (x.a[name] !== n) continue;
149
+ for (const [v, word] of [[Math.round((n - step) * 100) / 100, 'just below'], [Math.round((n + step) * 100) / 100, 'just above']]) {
150
+ const y = all.find((z) => z.a[name] === v && names.every((m) => m === name || z.a[m] === x.a[m]));
151
+ if (y && y.r.result !== x.r.result) { add(x.a, `${name} exactly ${n}`); add(y.a, `${name} ${word} ${n}`); }
152
+ }
153
+ if (chosen.some((c) => c.label === `${name} exactly ${n}`)) break;
154
+ }
155
+ }
156
+ }
157
+ const unreached = rules.filter((_, i) => !all.some((x) => x.r.matched === `r${i + 1}`)).map((r) => r.when);
158
+ for (const w of unreached) notes.push(`No example reaches the rule "${sayCondition(w)}"; an earlier rule always answers first, or the examples need other values.`);
159
+
160
+ const outcomes = [...new Set(results)];
161
+ const sig = names.map((n) => `${n}: ${types[n]}`).join(', ');
162
+ const where = file ? `${file} line ${item.line}` : `line ${item.line}`;
163
+ const source = [
164
+ `# Recovered from ${where} by thunder read. Inferred from code, not written by a person.`,
165
+ '# The examples record what the code does today. Confirm each answer, or change it where the code is wrong.',
166
+ ...notes.map((n) => `# ${n}`),
167
+ `contract ${decisionName}`,
168
+ `purpose ${decisionName} decides between ${outcomes.length === 2 ? outcomes.join(' and ') : `${outcomes.slice(0, -1).join(', ')}, and ${outcomes[outcomes.length - 1]}`}. Confirm what it is for.`,
169
+ '',
170
+ `decision ${decisionName}(${sig})`,
171
+ ...rules.map((r) => ` when ${r.when} -> ${r.result}`),
172
+ ` otherwise -> ${item.otherwise.result}`,
173
+ '',
174
+ `examples ${decisionName}`,
175
+ ...chosen.map((c) => ` case "${c.label.replace(/"/g, '')}": (${names.map((n) => `${n}: ${lit(c.a[n])}`).join(', ')}) -> ${c.result}`),
176
+ '',
177
+ ].join('\n');
178
+ return { schema: PROMOTE_SCHEMA, ok: true, name: decisionName, source, examples: chosen.length, notes };
179
+ }
@@ -0,0 +1,29 @@
1
+ // Node-only helper: collect readable source files from a folder on disk for readRepo().
2
+ // Kept apart from read-repo.mjs so the reader itself stays browser-safe.
3
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
4
+ import { join, relative } from 'node:path';
5
+ import { READ_SKIP_DIRS, readableLanguage } from './read-repo.mjs';
6
+
7
+ /** Returns [{ path, source }] with paths relative to `root`. Stops after `maxFiles` files. */
8
+ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000 } = {}) {
9
+ const out = [];
10
+ const walk = (dir) => {
11
+ let names;
12
+ try { names = readdirSync(dir).sort(); } catch { return; }
13
+ for (const name of names) {
14
+ if (out.length > maxFiles) return;
15
+ if (READ_SKIP_DIRS.has(name) || name.startsWith('.')) continue;
16
+ const full = join(dir, name);
17
+ let st;
18
+ try { st = statSync(full); } catch { continue; }
19
+ if (st.isDirectory()) walk(full);
20
+ else if (readableLanguage(name)) {
21
+ const path = relative(root, full).split('\\').join('/');
22
+ // Oversized files are not loaded; readRepo lists them as skipped from their size.
23
+ out.push(st.size > maxFileBytes ? { path, source: '', size: st.size } : { path, source: readFileSync(full, 'utf8') });
24
+ }
25
+ }
26
+ };
27
+ walk(root);
28
+ return out;
29
+ }
@@ -0,0 +1,21 @@
1
+ import type { ReadItem, ReadKind } from './read.mjs';
2
+ export interface RepoItem extends ReadItem { file: string; language: string }
3
+ export interface RepoFacet { name: string; decisions: string[] }
4
+ export interface RepoReading {
5
+ schema: 'thunder-repo-reading-v1';
6
+ files: Array<{ path: string; language: string; counts: Record<ReadKind | 'partial', number> }>;
7
+ items: RepoItem[];
8
+ counts: Record<ReadKind | 'partial' | 'guarded' | 'route', number>;
9
+ languages: Record<string, number>;
10
+ folders: Record<string, number>;
11
+ answers: RepoFacet[];
12
+ inputs: RepoFacet[];
13
+ skipped: Array<{ path: string; reason: string }>;
14
+ }
15
+ export interface RepoFilter { query?: string; kinds?: Array<ReadKind | 'route' | 'guard'>; status?: string[]; languages?: string[]; path?: string; answer?: string; input?: string }
16
+ export const READ_REPO_SCHEMA: 'thunder-repo-reading-v1';
17
+ export const READ_SKIP_DIRS: Set<string>;
18
+ export function readableLanguage(path: string): string | null;
19
+ export function readRepo(files: Array<{ path: string; source: string; size?: number }>, options?: { maxFileBytes?: number; maxFiles?: number }): RepoReading;
20
+ export function searchRepo(index: RepoReading, filter?: RepoFilter): RepoItem[];
21
+ export function groupByFile(items: RepoItem[]): Array<{ file: string; language: string; items: RepoItem[] }>;