@skillstech/thunderlang 0.4.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,213 @@
1
+ // Experimental authoring shorthand and a deterministic reading view. Both lower
2
+ // to the existing parser/runtime. This is not a second execution language.
3
+ import { parseIntent } from './parse.mjs';
4
+ import { compileExpr, tokenize } from './expr.mjs';
5
+ import { runTests } from './testing.mjs';
6
+
7
+ const ID = '[A-Za-z_][A-Za-z0-9_]*';
8
+ const id = new RegExp(`^${ID}$`);
9
+ const literal = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?|true|false|"[A-Za-z0-9 _-]*")$/;
10
+ const fail = (line, text) => { throw new Error(`Line ${line}: ${text}`); };
11
+
12
+ function namedCase(text, line, decision) {
13
+ const match = text.match(new RegExp(`^case "([^"\\\\]+)":\\s*\\((.*)\\)\\s*->\\s*(${ID})$`));
14
+ if (!match) fail(line, 'Use case "name": (input: value, otherInput: value) -> Outcome. Use -> for both rules and examples.');
15
+ const values = new Map();
16
+ const entries = match[2].trim().replace(/,\s*$/, '').split(',');
17
+ for (const entry of entries) {
18
+ const arg = entry.trim().match(new RegExp(`^(${ID})\\s*:\\s*(.+)$`));
19
+ if (!arg) fail(line, 'Name every example input, such as amount: 100.');
20
+ if (!decision.inputs.includes(arg[1])) fail(line, `Unknown input ${arg[1]}. Expected: ${decision.inputs.join(', ')}.`);
21
+ if (values.has(arg[1])) fail(line, `Duplicate input ${arg[1]}. Provide each input once.`);
22
+ values.set(arg[1], arg[2].trim());
23
+ }
24
+ const missing = decision.inputs.filter(input => !values.has(input));
25
+ if (missing.length) fail(line, `Missing input ${missing.join(', ')}. Missing is not the same as false.`);
26
+ return { cells: [match[1].trim(), ...decision.inputs.map(input => values.get(input)), match[3]], line };
27
+ }
28
+
29
+ /** Compile the small, explicit human-v1 subset into ordinary .thunder source. */
30
+ export function compileHumanContract(source) {
31
+ if (typeof source !== 'string' || source.length > 200000) throw new Error('A human contract must be text of at most 200 KB.');
32
+ const rows = source.split(/\r?\n/).map((text, i) => ({ text: text.trim(), indented: /^\s/.test(text), line: i + 1 }))
33
+ .filter(r => r.text && !r.text.startsWith('#'));
34
+ let mission = null, purpose = null, active = null;
35
+ const decisions = [], tables = new Map();
36
+ for (let index = 0; index < rows.length; index++) {
37
+ const row = rows[index];
38
+ const { text, line } = row;
39
+ if (!row.indented) {
40
+ active = null;
41
+ let match;
42
+ if ((match = text.match(new RegExp(`^contract (${ID})$`)))) {
43
+ if (mission || decisions.length) fail(line, 'Declare one contract before its decisions.');
44
+ mission = match[1];
45
+ } else if (text.startsWith('purpose ')) {
46
+ if (!mission || purpose) fail(line, 'Declare one purpose after the contract name.');
47
+ purpose = text.slice(8).trim();
48
+ } else if ((match = text.match(new RegExp(`^decision (${ID})\\(([^)]*)\\)$`)))) {
49
+ const signature = match[2].split(',').map(x => x.trim().match(new RegExp(`^(${ID})(?:\\s*:\\s*(number|boolean|string))?$`)));
50
+ if (signature.some(input => !input)) fail(line, 'Use input names, optionally typed as number, boolean, or string.');
51
+ const inputs = signature.map(input => input[1]);
52
+ const inputTypes = Object.fromEntries(signature.filter(input => input[2]).map(input => [input[1], input[2]]));
53
+ if (!mission || !purpose) fail(line, 'Start with contract and purpose before a decision.');
54
+ if (!inputs.length || inputs.some(x => !id.test(x) || ['case', 'expect', 'true', 'false', 'and', 'or', 'not', 'in'].includes(x)) || new Set(inputs).size !== inputs.length) fail(line, 'Use unique input names, such as decision RefundPolicy(amount, withinWindow).');
55
+ if (decisions.some(d => d.name === match[1])) fail(line, 'Decision names must be unique.');
56
+ active = { kind: 'decision', name: match[1], inputs, inputTypes, rules: [], otherwise: null, line };
57
+ decisions.push(active);
58
+ } else if ((match = text.match(new RegExp(`^examples (${ID})$`)))) {
59
+ if (tables.has(match[1]) || !decisions.some(d => d.name === match[1])) fail(line, 'Examples must name one preceding decision exactly, with one examples block per decision.');
60
+ active = { kind: 'examples', name: match[1], rows: [], format: null, line };
61
+ tables.set(match[1], active);
62
+ } else fail(line, 'Expected contract, purpose, decision Name(inputs), or examples Name. This preview does not guess unknown syntax.');
63
+ } else if (active?.kind === 'decision') {
64
+ let match;
65
+ if ((match = text.match(new RegExp(`^when (.+) -> (${ID})$`)))) {
66
+ if (active.otherwise) fail(line, 'Put conditional rules before otherwise.');
67
+ try {
68
+ compileExpr(match[1]);
69
+ for (const token of tokenize(match[1])) {
70
+ if (token.t === 'id' && !active.inputs.includes(token.v)) fail(line, `Unknown input ${token.v}. Declare it, or quote it if it is a text value.`);
71
+ if (token.t === 'num' && !Number.isFinite(token.v)) fail(line, 'Use a finite number in the condition.');
72
+ }
73
+ } catch (e) { fail(line, e.message); }
74
+ active.rules.push({ condition: match[1], result: match[2], line });
75
+ } else if ((match = text.match(new RegExp(`^otherwise -> (${ID})$`)))) {
76
+ if (active.otherwise) fail(line, 'Use one otherwise result.');
77
+ active.otherwise = match[1];
78
+ } else fail(line, 'Use when <condition> -> Outcome or otherwise -> Outcome.');
79
+ } else if (active?.kind === 'examples') {
80
+ const format = text.startsWith('|') ? 'table' : 'named';
81
+ if (active.format && active.format !== format) fail(line, 'Use named cases or a table within one examples block, not both.');
82
+ active.format = format;
83
+ if (format === 'table') {
84
+ if (!text.endsWith('|')) fail(line, 'Write an examples table row with | around every cell.');
85
+ active.rows.push({ cells: text.slice(1, -1).split('|').map(s => s.trim()), line });
86
+ } else {
87
+ let statement = text;
88
+ while (!/\)\s*(?:->|=>)/.test(statement) && index + 1 < rows.length && rows[index + 1].indented && !/^(case |\|)/.test(rows[index + 1].text)) {
89
+ statement += ` ${rows[++index].text}`;
90
+ }
91
+ active.rows.push(namedCase(statement, line, decisions.find(d => d.name === active.name)));
92
+ }
93
+ } else fail(line, 'This indented line has no decision or examples block.');
94
+ }
95
+ if (!mission || !purpose || !decisions.length) throw new Error('Include a contract, purpose, and at least one decision with examples.');
96
+ const out = [`mission ${mission}`, '', 'goal', ` ${purpose}`];
97
+ for (const d of decisions) {
98
+ if (!d.rules.length || !d.otherwise) fail(d.line, 'Each decision needs at least one when rule and an otherwise result.');
99
+ out.push('', `decision ${d.name}`, ' inputs', ...d.inputs.map(i => ` ${i}`));
100
+ d.rules.forEach((r, i) => out.push(` rule condition_${i + 1}`, ` when ${r.condition}`, ` return ${r.result}`));
101
+ out.push(' default', ` return ${d.otherwise}`);
102
+ const table = tables.get(d.name);
103
+ if (!table || !table.rows.length) fail(d.line, `Add examples ${d.name} with at least one case.`);
104
+ const expectedHeader = ['case', ...d.inputs, 'expect'];
105
+ const header = table.format === 'table' ? table.rows[0].cells : expectedHeader;
106
+ if (JSON.stringify(header) !== JSON.stringify(expectedHeader)) fail(table.rows[0].line, `Use this header: | ${expectedHeader.join(' | ')} |`);
107
+ const names = new Set();
108
+ out.push('', `test ${d.name}`);
109
+ for (const row of table.rows.slice(table.format === 'table' ? 1 : 0)) {
110
+ if (row.cells.every(c => /^:?-+:?$/.test(c))) continue; // optional Markdown separator
111
+ const [name, ...values] = row.cells;
112
+ if (row.cells.length !== header.length || !name || names.has(name)) fail(row.line, 'Use a unique case name and fill every column.');
113
+ names.add(name);
114
+ const expected = values.pop();
115
+ if (!id.test(expected)) fail(row.line, 'The expected outcome must be a named result, such as Approve or Review.');
116
+ const outcomes = [...d.rules.map(r => r.result), d.otherwise];
117
+ if (!outcomes.includes(expected)) fail(row.line, `Unknown outcome ${expected}. Use one of: ${[...new Set(outcomes)].join(', ')}.`);
118
+ values.forEach((v, i) => {
119
+ if (!literal.test(v) || (!v.startsWith('"') && !['true', 'false'].includes(v) && !Number.isFinite(Number(v)))) fail(row.line, 'Inputs must be finite numbers, true/false, or quoted simple text. Complex values need ordinary ThunderLang.');
120
+ const type = v.startsWith('"') ? 'string' : ['true', 'false'].includes(v) ? 'boolean' : 'number';
121
+ if (d.inputTypes[d.inputs[i]] && type !== d.inputTypes[d.inputs[i]]) fail(row.line, `${d.inputs[i]} expects ${d.inputTypes[d.inputs[i]]}, received ${type}. Values are not coerced.`);
122
+ });
123
+ out.push(` case ${name}`, ` given ${d.inputs.map((input, i) => `${input} ${values[i]}`).join(', ')}`, ` expect ${expected}`);
124
+ }
125
+ if (!names.size) fail(table.line, 'The table has no examples; add a row with inputs and an expected outcome.');
126
+ }
127
+ return out.join('\n') + '\n';
128
+ }
129
+
130
+ const words = s => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, ' ');
131
+ const operators = { '>=': 'is at least', '<=': 'is at most', '>': 'is greater than', '<': 'is less than', '==': 'equals', '=': 'equals', '!=': 'does not equal', '&&': 'and', '||': 'or', '!': 'not' };
132
+ function readCondition(expression) {
133
+ try { return tokenize(expression).map(t => t.t === 'str' ? JSON.stringify(t.v) : t.t === 'id' ? words(t.v) : operators[t.v] ?? String(t.v)).join(' '); }
134
+ catch { return expression; } // keep unsupported text visible, never fabricate a translation
135
+ }
136
+
137
+ // Older lifted drafts have a free-text `unknown` block; their AST only retains
138
+ // named unknowns. Preserve the source's words in this view instead of dropping
139
+ // them or rendering an empty internal record to a reader.
140
+ function readUnknowns(ast, source) {
141
+ const notes = (ast.unknowns ?? []).filter(u => u.name).map(u => u.name);
142
+ let block = false;
143
+ for (const line of source.split(/\r?\n/)) {
144
+ if (/^unknown\s*$/.test(line)) { block = true; continue; }
145
+ if (/^\S/.test(line)) block = false;
146
+ if (block && /^\s+\S/.test(line)) notes.push(line.trim());
147
+ }
148
+ return notes;
149
+ }
150
+
151
+ /** Read authored decisions. Existing files retain all content in canonicalSource;
152
+ * this view deliberately makes no claim to summarize other language constructs. */
153
+ export function previewHumanContract(source) {
154
+ const first = source.split(/\r?\n/).find(l => l.trim() && !l.trim().startsWith('#'))?.trim() ?? '';
155
+ const compact = first.startsWith('contract ');
156
+ const canonicalSource = compact ? compileHumanContract(source) : source;
157
+ const ast = parseIntent(canonicalSource);
158
+ const tests = runTests(ast);
159
+ const declared = (ast.tests ?? []).flatMap(t => t.cases);
160
+ const results = tests.results.map((r, i) => ({ ...r, given: declared[i]?.given ?? {}, pass: !!r.pass && !r.error && !r.note && declared[i]?.expect != null }));
161
+ const passed = results.filter(r => r.pass).length;
162
+ const report = {
163
+ schema: 'thunder-human-preview-v1', experimental: true, origin: ast.lift?.inferred ? 'inferred-code' : compact ? 'human-v1' : 'thunderlang',
164
+ mission: ast.mission, purpose: ast.goal, canonicalSource,
165
+ signatureInputs: ast.inputs ?? [], sourceReferences: ast.lift?.maps_to ?? [],
166
+ needsReview: ast.lift?.needs_review ?? [], unknowns: readUnknowns(ast, canonicalSource),
167
+ decisions: (ast.decisions ?? []).map(d => ({ name: d.name, inputs: d.inputs, order: 'first matching rule wins',
168
+ rules: d.rules.map(r => ({ condition: r.when, readAs: readCondition(r.when ?? ''), outcome: r.result })), otherwise: d.default })),
169
+ tests: { total: results.length, passed, failed: results.length - passed, results },
170
+ application: 'not_checked',
171
+ limitations: ['This reading view covers authored decisions and examples. Other constructs remain in the full source.',
172
+ 'Purpose is author-stated intent, not inferred from code or established by tests.',
173
+ 'Passing examples check those contract inputs only. Use OpenThunder intent test-app to exercise the application.'],
174
+ };
175
+ return report;
176
+ }
177
+
178
+ export function renderHumanContract(report) {
179
+ const inferred = report.origin === 'inferred-code';
180
+ const out = [`${report.mission || 'Untitled contract'} (experimental reading view)`, '',
181
+ inferred ? 'Recovered from code: inferred draft, needs human review. Business purpose is not established.' : `Purpose: ${report.purpose || 'Not stated'}`];
182
+ if (inferred) {
183
+ out.push(`Candidate description: ${report.purpose || 'Not inferred'}`);
184
+ for (const ref of report.sourceReferences) out.push(`Source: ${ref}`);
185
+ if (report.signatureInputs.length) out.push(`Signature inputs: ${report.signatureInputs.map(i => `${i.name}${i.type ? ` (${i.type})` : ''}`).join(', ')}`);
186
+ if (!report.decisions.length) out.push('Behavior rules: not recovered. Inspect the original code before approving a contract.');
187
+ for (const note of report.needsReview) out.push(`Needs review: ${note}`);
188
+ for (const note of report.unknowns) out.push(`Unknown: ${note}`);
189
+ }
190
+ for (const d of report.decisions) {
191
+ out.push('', `Decision: ${words(d.name)}`, `Inputs: ${d.inputs.map(words).join(', ')}`, 'Read rules in order; the first match wins.');
192
+ d.rules.forEach((r, i) => out.push(`${i + 1}. If ${r.readAs}, choose ${r.outcome}.`));
193
+ out.push(`Otherwise choose ${d.otherwise ?? '(not stated)'}.`);
194
+ }
195
+ out.push('', `Contract examples: ${report.tests.passed}/${report.tests.total} passed. Application: not checked.`);
196
+ for (const target of new Set(report.tests.results.map(r => r.target))) {
197
+ const rows = report.tests.results.filter(r => r.target === target);
198
+ const inputs = report.decisions.find(d => d.name === target)?.inputs ?? [...new Set(rows.flatMap(r => Object.keys(r.given)))];
199
+ out.push('', `Examples: ${target}`, renderExampleTable(inputs, rows.map(r => ({ ...r, status: r.pass ? 'Passed' : 'Failed' }))));
200
+ for (const row of rows) if (row.error || row.note) out.push(`${row.case}: ${row.error || row.note}`);
201
+ }
202
+ out.push('', ...report.limitations);
203
+ return out.join('\n');
204
+ }
205
+
206
+ /** Generated presentation only. Input order comes from the decision signature. */
207
+ export function renderExampleTable(inputs, rows) {
208
+ const cell = value => String(value ?? 'Not available').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\|/g, '\\|');
209
+ const header = ['Case', ...inputs, 'Expected', 'Actual', 'Result'];
210
+ const values = rows.map(row => [row.case, ...inputs.map(input => row.given?.[input]), row.expected,
211
+ Object.prototype.hasOwnProperty.call(row, 'actual') ? row.actual : 'Not checked', row.status]);
212
+ return [header, header.map(() => '---'), ...values].map(row => `| ${row.map(cell).join(' | ')} |`).join('\n');
213
+ }
package/src/index.mjs CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  // Parsing
10
10
  export { parseIntent, slug, KNOWN_LENSES } from './parse.mjs';
11
+ export { toEvidenceEvents, verifyDiffToEvidence, conformToEvidence, driftToEvidence } from './evidence.mjs';
11
12
 
12
13
  // Semantic analysis, graphs, and proof
13
14
  export {
package/src/lift.mjs CHANGED
@@ -477,6 +477,13 @@ const ADAPTERS = {
477
477
  scala: extractFactsScala, sc: extractFactsScala,
478
478
  elixir: extractFactsElixir, ex: extractFactsElixir, exs: extractFactsElixir,
479
479
  };
480
+ /** Signature-level code facts (functions, errors, tests) for one source, in a supported language. */
481
+ export function extractFacts(source, language, file) {
482
+ const key = String(language).toLowerCase();
483
+ const adapter = ADAPTERS[key];
484
+ return adapter ? adapter(String(source), file || `input.${LANG_EXT[key] || 'txt'}`) : null;
485
+ }
486
+
480
487
  export const SUPPORTED_LANGUAGES = ['typescript', 'javascript', 'python', 'java', 'csharp', 'go', 'rust', 'cpp', 'php', 'ruby', 'perl', 'kotlin', 'scala', 'elixir'];
481
488
  const DYNAMIC_LANGUAGES = new Set(['perl', 'javascript', 'python', 'ruby', 'php', 'elixir']);
482
489
 
@@ -696,7 +703,7 @@ export function liftRepo(files, { language } = {}) {
696
703
  const base = slug(r.lifted.mission);
697
704
  const n = (usedNames.get(base) || 0) + 1;
698
705
  usedNames.set(base, n);
699
- const outName = n === 1 ? `${base}.intent` : `${base}-${n}.intent`;
706
+ const outName = n === 1 ? `${base}.thunder` : `${base}-${n}.thunder`;
700
707
  missions.push({
701
708
  mission: r.lifted.mission, sourceFile: file, outName,
702
709
  intentText: r.intentText, summary: r.summary, diagnostics: r.diagnostics,
package/src/mcp.mjs CHANGED
@@ -21,8 +21,17 @@ import { buildConformance } from './conformance.mjs';
21
21
  import { checkDrift } from './drift.mjs';
22
22
  import { draftIntent } from './draft.mjs';
23
23
  import { ALL_DIAGNOSTICS } from './intent-schema.mjs';
24
+ import { readCode, searchReading, READ_LANGUAGES } from './read.mjs';
25
+ import { readRepo, searchRepo } from './read-repo.mjs';
26
+ import { promoteDecision } from './promote.mjs';
27
+ import { collectReadableFiles } from './read-repo-fs.mjs';
28
+ import { resolve } from 'node:path';
29
+ import { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
30
+ import { previewHumanContract } from './human-contract.mjs';
24
31
 
25
32
  const PROTOCOL_VERSION = '2024-11-05';
33
+ // Versions this server can speak; it answers with the client's requested version when listed.
34
+ const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
26
35
  const str = { type: 'string' };
27
36
 
28
37
  // ── prove helpers ────────────────────────────────────────────────────────────
@@ -221,48 +230,137 @@ const TOOLS = [
221
230
  inputSchema: { type: 'object', required: ['code'], properties: { code: { ...str, description: 'e.g. IL-SEC-001' } } },
222
231
  run: ({ code }) => ALL_DIAGNOSTICS.find((r) => r.ruleId.toLowerCase() === String(code).toLowerCase()) || { code, found: false },
223
232
  },
233
+ {
234
+ name: 'intent_read',
235
+ description: `READ CODE YOU DON'T KNOW. Given source code (${READ_LANGUAGES.join(', ')}), returns each function and the decision rules it makes, as ThunderLang and plain English, plus errors raised and tests found. Inferred from code by pattern (no AI); anything it could not read is listed, never guessed. Optional search text and kind filters. Pass \`in\` to also rewrite each decision in a language the reader knows.`,
236
+ inputSchema: {
237
+ type: 'object', required: ['source'],
238
+ properties: {
239
+ source: { ...str, description: 'the source code' },
240
+ language: { ...str, description: `source language; detected when omitted. One of: ${READ_LANGUAGES.join(', ')}` },
241
+ query: { ...str, description: 'free-text search over names, inputs, conditions, and answers' },
242
+ kinds: { type: 'array', items: { type: 'string', enum: ['decision', 'function', 'error', 'test'] }, description: 'only these kinds' },
243
+ in: { ...str, description: `rewrite decisions in this language: ${TRANSLATE_LANGUAGES.map((l) => l.key).join(', ')}` },
244
+ },
245
+ },
246
+ run: ({ source, language, query = '', kinds = [], in: inLang }) => {
247
+ const reading = readCode(String(source), { language });
248
+ const items = searchReading(reading, { query, kinds }).map((it) => (inLang && it.thunder
249
+ ? { ...it, rewritten: { language: inLang, code: translateDecisions(parseIntent(it.thunder), inLang) } }
250
+ : it));
251
+ return { ...reading, items };
252
+ },
253
+ },
254
+ {
255
+ name: 'intent_read_repo',
256
+ description: `READ A WHOLE REPOSITORY (local only). Reads every ${READ_LANGUAGES.join(', ')} file under a folder (skipping dependency and build folders) into one index: HTTP routes, decisions, checks that fail or respond early, errors, and tests, each with file and line. Filter by text, kind (route, decision, guard, function, error, test), language, folder prefix, an answer the code gives or fails with (e.g. "Decline", "401", "NotFoundError"), or an input a rule uses. Answers "what does this app do?" and "where does it decide X?" without guessing.`,
257
+ inputSchema: {
258
+ type: 'object', required: ['path'],
259
+ properties: {
260
+ path: { ...str, description: 'folder to read (absolute, or relative to the server working directory)' },
261
+ query: str,
262
+ kinds: { type: 'array', items: { type: 'string', enum: ['route', 'decision', 'guard', 'function', 'error', 'test'] } },
263
+ languages: { type: 'array', items: { type: 'string', enum: READ_LANGUAGES } },
264
+ folder: { ...str, description: 'only files under this relative path prefix' },
265
+ answer: { ...str, description: 'only items that answer, fail, or respond with this value' },
266
+ input: { ...str, description: 'only decisions that use this input' },
267
+ limit: { type: 'number', description: 'max items to return (default 50)' },
268
+ },
269
+ },
270
+ run: ({ path, query = '', kinds = [], languages = [], folder = '', answer = '', input = '', limit = 50 }) => {
271
+ const index = readRepo(collectReadableFiles(resolve(String(path))));
272
+ const items = searchRepo(index, { query, kinds, languages, path: folder, answer, input });
273
+ const { files, ...rest } = index;
274
+ return { ...rest, files: files.length, matched: items.length, items: items.slice(0, Math.max(1, Math.min(500, Number(limit) || 50))) };
275
+ },
276
+ },
277
+ {
278
+ name: 'intent_promote',
279
+ description: 'Turn a decision recovered from code into a readable ThunderLang contract with starter examples chosen at every rule and threshold. The examples record what the code does TODAY (computed from the recovered rule), so a person must confirm each answer; after that, intent_verify_diff can hold every change to it. Give the source code and the decision (function) name.',
280
+ inputSchema: {
281
+ type: 'object', required: ['source', 'name'],
282
+ properties: { source: { ...str, description: 'the source code' }, name: { ...str, description: 'the function whose decision to promote' }, language: { ...str, description: `one of: ${READ_LANGUAGES.join(', ')} (detected when omitted)` } },
283
+ },
284
+ run: ({ source, name, language }) => {
285
+ const item = readCode(String(source), { language }).items.find((i) => i.name === name);
286
+ if (!item) return { ok: false, reason: `No function named ${name} was found.` };
287
+ const p = promoteDecision(item);
288
+ return p.ok ? { ...p, examplesPass: previewHumanContract(p.source).tests } : p;
289
+ },
290
+ },
291
+ {
292
+ name: 'intent_translate',
293
+ description: `Generate readable, typed code for every decision in ThunderLang source, in ${TRANSLATE_LANGUAGES.map((l) => l.label).join(', ')}. Deterministic, no AI; the first matching rule wins in every language. Accepts canonical .thunder source or the readable contract notation.`,
294
+ inputSchema: {
295
+ type: 'object', required: ['source', 'language'],
296
+ properties: { source: str, language: { type: 'string', enum: TRANSLATE_LANGUAGES.map((l) => l.key) } },
297
+ },
298
+ run: ({ source, language }) => {
299
+ const text = String(source);
300
+ const canonical = /^\s*contract\s/m.test(text.split('\n').find((l) => l.trim() && !l.trim().startsWith('#')) || '')
301
+ ? previewHumanContract(text).canonicalSource : text;
302
+ return translateDecisions(parseIntent(canonical), language);
303
+ },
304
+ },
305
+ {
306
+ name: 'intent_human',
307
+ description: 'Check a contract written in the readable notation (contract / purpose / decision Name(inputs) / when ... -> Outcome / examples). Runs every example and returns pass/fail per case plus the canonical .thunder source. Use it to write or review business rules with a person.',
308
+ inputSchema: { type: 'object', required: ['source'], properties: { source: str } },
309
+ run: ({ source }) => previewHumanContract(String(source)),
310
+ },
224
311
  ];
225
312
 
226
- export const MCP_TOOLS = TOOLS.map((t) => t.name);
313
+ // Tools that are pure functions of their arguments (no filesystem, git, or process state), so they
314
+ // are safe to serve to remote clients such as ChatGPT. intent_prove reads the local repository.
315
+ export const REMOTE_SAFE_TOOLS = ['intent_check', 'intent_verify_diff', 'intent_conform', 'intent_drift', 'intent_draft', 'intent_lift', 'intent_run', 'intent_test', 'intent_graph', 'intent_explain', 'intent_read', 'intent_promote', 'intent_translate', 'intent_human'];
227
316
 
228
- /** Start the ThunderLang MCP server over the given streams (default: process stdio). */
229
- export function startMcpServer({ readable = process.stdin, writable = process.stdout } = {}) {
230
- const send = (msg) => writable.write(`${JSON.stringify(msg)}\n`);
231
- const respond = (id, result) => send({ jsonrpc: '2.0', id, result });
232
- const fail = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
317
+ export const MCP_TOOLS = TOOLS.map((t) => t.name);
233
318
 
234
- function handle(msg) {
319
+ /**
320
+ * A transport-free MCP handler: give it one JSON-RPC message, get back the response object (or
321
+ * null for notifications). Shared by the stdio server and the hosted HTTP endpoint.
322
+ */
323
+ export function createMcpHandler({ tools = MCP_TOOLS } = {}) {
324
+ const allowed = TOOLS.filter((t) => tools.includes(t.name));
325
+ const ok = (id, result) => ({ jsonrpc: '2.0', id, result });
326
+ const err = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
327
+ return function handle(msg) {
235
328
  const { id, method, params } = msg || {};
236
329
  switch (method) {
237
- case 'initialize':
238
- respond(id, { protocolVersion: PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: { name: 'thunderlang', version: COMPILER_VERSION } });
239
- break;
330
+ case 'initialize': {
331
+ const asked = params?.protocolVersion;
332
+ const protocolVersion = SUPPORTED_PROTOCOLS.includes(asked) ? asked : PROTOCOL_VERSION;
333
+ return ok(id, { protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'thunderlang', version: COMPILER_VERSION } });
334
+ }
240
335
  case 'notifications/initialized':
241
336
  case 'initialized':
242
337
  case 'notifications/cancelled':
243
- break; // notifications , no response
338
+ return null; // notifications , no response
244
339
  case 'ping':
245
- respond(id, {});
246
- break;
340
+ return ok(id, {});
247
341
  case 'tools/list':
248
- respond(id, { tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });
249
- break;
342
+ return ok(id, { tools: allowed.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });
250
343
  case 'tools/call': {
251
- const tool = TOOLS.find((t) => t.name === params?.name);
252
- if (!tool) { fail(id, -32602, `Unknown tool: ${params?.name}`); break; }
344
+ const tool = allowed.find((t) => t.name === params?.name);
345
+ if (!tool) return err(id, -32602, `Unknown tool: ${params?.name}`);
253
346
  try {
254
347
  const result = tool.run(params.arguments || {});
255
348
  const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
256
- respond(id, { content: [{ type: 'text', text }] });
349
+ return ok(id, { content: [{ type: 'text', text }] });
257
350
  } catch (e) {
258
- respond(id, { content: [{ type: 'text', text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true });
351
+ return ok(id, { content: [{ type: 'text', text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true });
259
352
  }
260
- break;
261
353
  }
262
354
  default:
263
- if (id != null) fail(id, -32601, `Method not found: ${method}`);
355
+ return id != null ? err(id, -32601, `Method not found: ${method}`) : null;
264
356
  }
265
- }
357
+ };
358
+ }
359
+
360
+ /** Start the ThunderLang MCP server over the given streams (default: process stdio). */
361
+ export function startMcpServer({ readable = process.stdin, writable = process.stdout } = {}) {
362
+ const respondTo = createMcpHandler();
363
+ const handle = (msg) => { const reply = respondTo(msg); if (reply) writable.write(`${JSON.stringify(reply)}\n`); };
266
364
 
267
365
  let buffer = '';
268
366
  readable.on('data', (chunk) => {
@@ -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,165 @@
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
+ * Turn a decision item from readCode/readRepo into a readable contract.
76
+ * Returns { ok: true, source, name, examples, notes } or { ok: false, reason }.
77
+ */
78
+ export function promoteDecision(item, { file = item.file || '' } = {}) {
79
+ 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.' };
80
+ const results = [...item.rules.map((r) => r.result), item.otherwise.result];
81
+ const bad = results.find((r) => !OUTCOME.test(r));
82
+ if (bad) return { ok: false, reason: `The answer ${bad} is not a name. Contracts answer with names such as Approve or Review.` };
83
+
84
+ // Flatten field paths (order.total -> orderTotal) so every input is a plain name.
85
+ const notes = [];
86
+ const renames = new Map();
87
+ const conditions = item.rules.map((r) => r.when);
88
+ const refs = usage(conditions, new Set((item.inputs || []).map((p) => p.name)));
89
+ for (const path of refs.keys()) if (path.includes('.')) { renames.set(path, flat(path)); notes.push(`${flat(path)} stands for ${path} in the code.`); }
90
+ const rewrite = (cond) => tokenize(cond).map((t) => {
91
+ 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
92
+ if (t.t === 'str') return JSON.stringify(t.v);
93
+ if (t.t === 'num' || t.t === 'bool') return String(t.v);
94
+ return t.v;
95
+ }).join(' ').replace(/\( /g, '(').replace(/ \)/g, ')');
96
+ const declared = new Map((item.inputs || []).map((p) => [p.name, p.type]));
97
+ // Keep the function's own parameter order; flattened fields follow their object parameter.
98
+ const order = (path) => { const i = (item.inputs || []).findIndex((p) => p.name === path.split('.')[0]); return i < 0 ? 999 : i; };
99
+ const names = [...refs.keys()].sort((a, b) => order(a) - order(b)).map((p) => renames.get(p) ?? p);
100
+ if (!names.length) return { ok: false, reason: 'The rules do not depend on any input, so there is nothing to give examples for.' };
101
+ const types = {}, values = {};
102
+ for (const [path, u] of refs) {
103
+ const name = renames.get(path) ?? path;
104
+ const t = declared.get(path);
105
+ types[name] = ['number', 'boolean', 'string'].includes(t) && !(t !== 'string' && u.strings.size) ? t : u.strings.size ? 'string' : u.numbers.size ? 'number' : 'boolean';
106
+ 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.` };
107
+ values[name] = candidates(types[name], u);
108
+ }
109
+ const rules = item.rules.map((r) => ({ when: rewrite(r.when), result: r.result }));
110
+ const decisionName = pascal(item.name);
111
+
112
+ // Evaluate the recovered rule to choose examples where it changes its answer.
113
+ const canonical = parseIntent([`decision ${decisionName}`, ' inputs', ...names.map((n) => ` ${n}`),
114
+ ...rules.flatMap((r, i) => [` rule r${i + 1}`, ` when ${r.when}`, ` return ${r.result}`]), ' default', ` return ${item.otherwise.result}`].join('\n')).decisions[0];
115
+ const run = (a) => evaluateDecision(canonical, a);
116
+ const all = assignments(names, values).map((a) => ({ a, r: run(a) }));
117
+ const chosen = [];
118
+ const key = (a) => names.map((n) => lit(a[n])).join('|');
119
+ const add = (a, label) => {
120
+ if (chosen.length >= 10 || chosen.some((c) => key(c.a) === key(a) || c.label === label)) return;
121
+ chosen.push({ a, label, result: run(a).result });
122
+ };
123
+ // One example per rule (and the fallback), in rule order.
124
+ rules.forEach((r, i) => { const hit = all.find((x) => x.r.matched === `r${i + 1}`); if (hit) add(hit.a, `when ${sayCondition(r.when)}`); });
125
+ const fallback = all.find((x) => x.r.matched === 'default');
126
+ if (fallback) add(fallback.a, 'when no rule matches');
127
+ // Both sides of each numeric threshold, where the answer changes.
128
+ for (const [path, u] of refs) {
129
+ const name = renames.get(path) ?? path;
130
+ if (types[name] !== 'number') continue;
131
+ for (const n of u.numbers) {
132
+ const step = Number.isInteger(n) ? 1 : 0.01;
133
+ for (const x of all) {
134
+ if (x.a[name] !== n) continue;
135
+ for (const [v, word] of [[Math.round((n - step) * 100) / 100, 'just below'], [Math.round((n + step) * 100) / 100, 'just above']]) {
136
+ const y = all.find((z) => z.a[name] === v && names.every((m) => m === name || z.a[m] === x.a[m]));
137
+ if (y && y.r.result !== x.r.result) { add(x.a, `${name} exactly ${n}`); add(y.a, `${name} ${word} ${n}`); }
138
+ }
139
+ if (chosen.some((c) => c.label === `${name} exactly ${n}`)) break;
140
+ }
141
+ }
142
+ }
143
+ const unreached = rules.filter((_, i) => !all.some((x) => x.r.matched === `r${i + 1}`)).map((r) => r.when);
144
+ 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.`);
145
+
146
+ const outcomes = [...new Set(results)];
147
+ const sig = names.map((n) => `${n}: ${types[n]}`).join(', ');
148
+ const where = file ? `${file} line ${item.line}` : `line ${item.line}`;
149
+ const source = [
150
+ `# Recovered from ${where} by thunder read. Inferred from code, not written by a person.`,
151
+ '# The examples record what the code does today. Confirm each answer, or change it where the code is wrong.',
152
+ ...notes.map((n) => `# ${n}`),
153
+ `contract ${decisionName}`,
154
+ `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.`,
155
+ '',
156
+ `decision ${decisionName}(${sig})`,
157
+ ...rules.map((r) => ` when ${r.when} -> ${r.result}`),
158
+ ` otherwise -> ${item.otherwise.result}`,
159
+ '',
160
+ `examples ${decisionName}`,
161
+ ...chosen.map((c) => ` case "${c.label.replace(/"/g, '')}": (${names.map((n) => `${n}: ${lit(c.a[n])}`).join(', ')}) -> ${c.result}`),
162
+ '',
163
+ ].join('\n');
164
+ return { schema: PROMOTE_SCHEMA, ok: true, name: decisionName, source, examples: chosen.length, notes };
165
+ }
@@ -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
+ }