@skillstech/thunderlang 0.4.2 → 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.
- package/CHANGELOG.md +28 -0
- package/dist/core.cjs +6082 -3970
- package/dist/index.cjs +2798 -384
- package/package.json +1 -1
- package/src/cli.mjs +130 -4
- package/src/core.d.ts +9 -0
- package/src/core.mjs +5 -0
- package/src/emit.mjs +1 -1
- package/src/expr.mjs +42 -1
- package/src/human-contract.d.mts +20 -0
- package/src/human-contract.mjs +213 -0
- package/src/lift.mjs +7 -0
- package/src/mcp.mjs +120 -22
- package/src/promote.d.mts +6 -0
- package/src/promote.mjs +165 -0
- package/src/read-repo-fs.mjs +29 -0
- package/src/read-repo.d.mts +21 -0
- package/src/read-repo.mjs +139 -0
- package/src/read.d.mts +29 -0
- package/src/read.mjs +1485 -0
- package/src/target-elixir.mjs +79 -0
- package/src/target-go.mjs +95 -0
- package/src/target-kotlin.mjs +91 -0
- package/src/target-rust.mjs +99 -0
- package/src/target-scala.mjs +93 -0
- package/src/target-types.mjs +62 -0
- package/src/target-util.mjs +1 -59
- package/src/translate.d.mts +5 -0
- package/src/translate.mjs +126 -0
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
239
|
-
|
|
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
|
-
|
|
338
|
+
return null; // notifications , no response
|
|
244
339
|
case 'ping':
|
|
245
|
-
|
|
246
|
-
break;
|
|
340
|
+
return ok(id, {});
|
|
247
341
|
case 'tools/list':
|
|
248
|
-
|
|
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 =
|
|
252
|
-
if (!tool)
|
|
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
|
-
|
|
349
|
+
return ok(id, { content: [{ type: 'text', text }] });
|
|
257
350
|
} catch (e) {
|
|
258
|
-
|
|
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
|
-
|
|
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;
|
package/src/promote.mjs
ADDED
|
@@ -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
|
+
}
|
|
@@ -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[] }>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Read a whole repository: run the single-file reader (read.mjs) over every supported file and
|
|
2
|
+
// merge the results into one searchable index, with facets a newcomer actually asks about:
|
|
3
|
+
// "where does the code decide Decline?" (answers), "which rules use creditScore?" (inputs),
|
|
4
|
+
// plus language, folder, kind, and how completely each item was read.
|
|
5
|
+
// Pure and browser-safe: callers pass { path, source } pairs (the CLI reads them from disk, the
|
|
6
|
+
// browser from a folder the person picks; nothing is uploaded). Deterministic, no AI.
|
|
7
|
+
import { readCode } from './read.mjs';
|
|
8
|
+
|
|
9
|
+
export const READ_REPO_SCHEMA = 'thunder-repo-reading-v1';
|
|
10
|
+
|
|
11
|
+
const EXT_LANG = [
|
|
12
|
+
[/\.d\.ts$/i, null],
|
|
13
|
+
[/\.min\.js$/i, null],
|
|
14
|
+
[/\.(ts|tsx|mts|cts)$/i, 'typescript'],
|
|
15
|
+
[/\.(js|jsx|mjs|cjs)$/i, 'javascript'],
|
|
16
|
+
[/\.pyi?$/i, 'python'],
|
|
17
|
+
[/\.go$/i, 'go'],
|
|
18
|
+
[/\.rs$/i, 'rust'],
|
|
19
|
+
[/\.cs$/i, 'csharp'],
|
|
20
|
+
[/\.java$/i, 'java'],
|
|
21
|
+
[/\.kts?$/i, 'kotlin'],
|
|
22
|
+
[/\.php$/i, 'php'],
|
|
23
|
+
[/\.rb$/i, 'ruby'],
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** Folders that hold dependencies, build output, or tooling state rather than the application. */
|
|
27
|
+
export const READ_SKIP_DIRS = new Set([
|
|
28
|
+
'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.vercel', '.turbo', 'coverage',
|
|
29
|
+
'vendor', 'target', 'bin', 'obj', '__pycache__', '.venv', 'venv', 'env', '.tox', '.mypy_cache',
|
|
30
|
+
'.gradle', '.idea', '.vscode', '.intent', 'third_party', 'Pods', '.terraform',
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
/** The language the reader uses for a path, or null when the file is not read. */
|
|
34
|
+
export function readableLanguage(path) {
|
|
35
|
+
const p = String(path).replace(/\\/g, '/');
|
|
36
|
+
if (p.split('/').some((seg) => READ_SKIP_DIRS.has(seg))) return null;
|
|
37
|
+
for (const [re, lang] of EXT_LANG) if (re.test(p)) return lang;
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** True for files that look machine-generated or minified (very long lines), which read as noise. */
|
|
42
|
+
function looksGenerated(source) {
|
|
43
|
+
const lines = source.split('\n');
|
|
44
|
+
if (/^\s*(\/\/|#)\s*(Code generated|@generated|<auto-generated)/im.test(lines.slice(0, 5).join('\n'))) return true;
|
|
45
|
+
const long = lines.filter((l) => l.length > 400).length;
|
|
46
|
+
return long > 3 && long / lines.length > 0.2;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const topFolder = (path) => {
|
|
50
|
+
const parts = String(path).replace(/\\/g, '/').split('/');
|
|
51
|
+
return parts.length > 1 ? parts[0] : '.';
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Read every supported file into one index. `files` is [{ path, source }]. Files outside the
|
|
56
|
+
* supported languages, inside dependency/build folders, generated, or too large are listed in
|
|
57
|
+
* `skipped` with the reason, never silently dropped.
|
|
58
|
+
*/
|
|
59
|
+
export function readRepo(files, { maxFileBytes = 400000, maxFiles = 5000 } = {}) {
|
|
60
|
+
const items = [], fileSummaries = [], skipped = [];
|
|
61
|
+
let considered = 0;
|
|
62
|
+
for (const f of files || []) {
|
|
63
|
+
const path = String(f.path).replace(/\\/g, '/').replace(/^\.\//, '');
|
|
64
|
+
const language = readableLanguage(path);
|
|
65
|
+
if (!language) continue; // not code this reader understands; not worth listing one by one
|
|
66
|
+
considered++;
|
|
67
|
+
if (considered > maxFiles) { skipped.push({ path, reason: `More than ${maxFiles} files; read a smaller folder to include this one.` }); continue; }
|
|
68
|
+
const source = String(f.source ?? '');
|
|
69
|
+
if (source.length > maxFileBytes || (f.size ?? 0) > maxFileBytes) { skipped.push({ path, reason: `Larger than ${Math.round(maxFileBytes / 1000)} KB.` }); continue; }
|
|
70
|
+
if (looksGenerated(source)) { skipped.push({ path, reason: 'Looks generated or minified.' }); continue; }
|
|
71
|
+
let reading;
|
|
72
|
+
try { reading = readCode(source, { language, file: path }); }
|
|
73
|
+
catch (e) { skipped.push({ path, reason: e instanceof Error ? e.message : 'Could not be read.' }); continue; }
|
|
74
|
+
for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
|
|
75
|
+
fileSummaries.push({ path, language, counts: reading.counts });
|
|
76
|
+
}
|
|
77
|
+
return { schema: READ_REPO_SCHEMA, ...summarize(items, fileSummaries), skipped };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function summarize(items, files) {
|
|
81
|
+
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
82
|
+
const languages = {}, folders = {}, answers = new Map(), inputs = new Map();
|
|
83
|
+
for (const f of files) {
|
|
84
|
+
languages[f.language] = (languages[f.language] || 0) + 1;
|
|
85
|
+
const top = topFolder(f.path);
|
|
86
|
+
folders[top] = (folders[top] || 0) + 1;
|
|
87
|
+
}
|
|
88
|
+
for (const it of items) {
|
|
89
|
+
counts[it.kind]++;
|
|
90
|
+
if (it.status === 'partial') counts.partial++;
|
|
91
|
+
if (it.guards?.length) counts.guarded++;
|
|
92
|
+
if (it.route) counts.route++;
|
|
93
|
+
// Answers include what guards fail with or respond, so "where does the code fail with NotFound?" works.
|
|
94
|
+
const guardAnswers = (it.guards || []).filter((g) => ['fails', 'responds', 'returns'].includes(g.effect.kind)).map((g) => g.effect.name);
|
|
95
|
+
if (it.kind !== 'decision' && !guardAnswers.length) continue;
|
|
96
|
+
for (const result of new Set([...(it.rules || []).map((r) => r.result), it.otherwise?.result, ...guardAnswers].filter(Boolean))) {
|
|
97
|
+
if (!answers.has(result)) answers.set(result, []);
|
|
98
|
+
answers.get(result).push(it.id);
|
|
99
|
+
}
|
|
100
|
+
if (it.kind !== 'decision') continue;
|
|
101
|
+
for (const p of it.inputs || []) {
|
|
102
|
+
if (!inputs.has(p.name)) inputs.set(p.name, []);
|
|
103
|
+
inputs.get(p.name).push(it.id);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const byUse = (m) => [...m].map(([name, ids]) => ({ name, decisions: ids })).sort((a, b) => b.decisions.length - a.decisions.length || a.name.localeCompare(b.name));
|
|
107
|
+
return { files, items, counts, languages, folders, answers: byUse(answers), inputs: byUse(inputs) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Filter the index. Every filter narrows: free text (all words must match), kinds, statuses,
|
|
112
|
+
* languages, a path prefix, an answer the decision can give, and an input it uses.
|
|
113
|
+
*/
|
|
114
|
+
export function searchRepo(index, { query = '', kinds = [], status = [], languages = [], path = '', answer = '', input = '' } = {}) {
|
|
115
|
+
const terms = String(query).trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
116
|
+
const prefix = String(path).replace(/\\/g, '/').replace(/^\.\//, '');
|
|
117
|
+
return index.items.filter((it) => {
|
|
118
|
+
if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes('guard') && it.guards?.length) && !(kinds.includes('route') && it.route)) return false;
|
|
119
|
+
if (status.length && !status.includes(it.status)) return false;
|
|
120
|
+
if (languages.length && !languages.includes(it.language)) return false;
|
|
121
|
+
if (prefix && !it.file.startsWith(prefix)) return false;
|
|
122
|
+
if (answer && !((it.rules || []).some((r) => r.result === answer) || it.otherwise?.result === answer || (it.guards || []).some((g) => g.effect.name === answer))) return false;
|
|
123
|
+
if (input && !(it.inputs || []).some((p) => p.name === input)) return false;
|
|
124
|
+
if (!terms.length) return true;
|
|
125
|
+
const hay = [it.file, it.name, it.route && `${it.route.method} ${it.route.path}`, it.says, it.thunder, ...(it.guards || []).flatMap((g) => [g.code, g.effect.name, g.says]), ...(it.inputs || []).map((p) => `${p.name} ${p.type ?? ''}`), ...(it.rules || []).flatMap((r) => [r.when, r.result, r.says]), it.otherwise?.result]
|
|
126
|
+
.filter(Boolean).join(' ').toLowerCase();
|
|
127
|
+
return terms.every((t) => hay.includes(t));
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Group items by file, keeping file order stable (path order) and item order (line order). */
|
|
132
|
+
export function groupByFile(items) {
|
|
133
|
+
const groups = new Map();
|
|
134
|
+
for (const it of items) {
|
|
135
|
+
if (!groups.has(it.file)) groups.set(it.file, []);
|
|
136
|
+
groups.get(it.file).push(it);
|
|
137
|
+
}
|
|
138
|
+
return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([file, list]) => ({ file, language: list[0].language, items: list }));
|
|
139
|
+
}
|
package/src/read.d.mts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type ReadKind = 'decision' | 'function' | 'error' | 'test';
|
|
2
|
+
export interface ReadInput { name: string; type: string | null }
|
|
3
|
+
export interface ReadRule { when: string; result: string; line: number; says: string }
|
|
4
|
+
export interface ReadUnread { line: number; text: string; reason: string }
|
|
5
|
+
export interface ReadGuard {
|
|
6
|
+
when: string | null; code: string; line: number; readable: boolean; says: string;
|
|
7
|
+
effect: { kind: 'fails' | 'responds' | 'nothing' | 'stops' | 'returns' | 'returns-computed'; name?: string; detail?: string | null };
|
|
8
|
+
}
|
|
9
|
+
export interface ReadItem {
|
|
10
|
+
id: string; kind: ReadKind; name: string; line: number; status: 'read' | 'partial' | 'signature-only';
|
|
11
|
+
says: string; provenance: 'inferred-from-code';
|
|
12
|
+
inputs?: ReadInput[]; returns?: string | null;
|
|
13
|
+
rules?: ReadRule[]; otherwise?: { result: string; line: number } | null;
|
|
14
|
+
thunder?: string; unread?: ReadUnread[]; guards?: ReadGuard[];
|
|
15
|
+
route?: { method: string; path: string };
|
|
16
|
+
}
|
|
17
|
+
export interface Reading {
|
|
18
|
+
schema: 'thunder-reading-v1'; language: string; detected: boolean; items: ReadItem[];
|
|
19
|
+
counts: Record<ReadKind | 'partial' | 'guarded' | 'route', number>; limitations: string[];
|
|
20
|
+
}
|
|
21
|
+
export const READ_SCHEMA: 'thunder-reading-v1';
|
|
22
|
+
export const READ_LANGUAGES: string[];
|
|
23
|
+
export function detectLanguage(source: string, file?: string): string;
|
|
24
|
+
export function readCode(source: string, options?: { language?: string; file?: string }): Reading;
|
|
25
|
+
export function searchReading(reading: Reading, filter?: { query?: string; kinds?: Array<ReadKind | 'route' | 'guard'>; status?: string[] }): ReadItem[];
|
|
26
|
+
export function terminatorEffect(stmt: string, language: string): ReadGuard['effect'] | { kind: 'passes-error' } | null;
|
|
27
|
+
export function toThunderCondition(text: string, inputs?: string[]): string | null;
|
|
28
|
+
export function toThunderOutcome(text: string): string | null;
|
|
29
|
+
export function sayCondition(cond: string): string;
|