@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
package/src/mcp.mjs CHANGED
@@ -15,48 +15,27 @@ import { sha256 } from './hash.mjs';
15
15
  import { verifyDiff } from './verify-diff.mjs';
16
16
  import { liftSource, SUPPORTED_LANGUAGES } from './lift.mjs';
17
17
  import { runTests } from './testing.mjs';
18
+ import { resolveObligations } from './obligations.mjs';
19
+ import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
18
20
  import { evaluateDecision } from './runtime.mjs';
19
21
  import { buildIntentGraph } from './intent-graph.mjs';
20
22
  import { buildConformance } from './conformance.mjs';
21
23
  import { checkDrift } from './drift.mjs';
22
24
  import { draftIntent } from './draft.mjs';
23
25
  import { ALL_DIAGNOSTICS } from './intent-schema.mjs';
26
+ import { readCode, searchReading, READ_LANGUAGES } from './read.mjs';
27
+ import { readRepo, searchRepo } from './read-repo.mjs';
28
+ import { promoteDecision } from './promote.mjs';
29
+ import { collectReadableFiles } from './read-repo-fs.mjs';
30
+ import { resolve } from 'node:path';
31
+ import { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
32
+ import { previewHumanContract } from './human-contract.mjs';
24
33
 
25
34
  const PROTOCOL_VERSION = '2024-11-05';
35
+ // Versions this server can speak; it answers with the client's requested version when listed.
36
+ const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
26
37
  const str = { type: 'string' };
27
38
 
28
- // ── prove helpers ────────────────────────────────────────────────────────────
29
- // Per-claim resolution , mirrors resolveObligations in cli.mjs (shared there by `thunder test
30
- // --contracts` and `thunder prove`) so the MCP proof and the CLI proof agree claim for claim.
31
- // States: verified (proven by a passing named test), failed (its test fails), declared (a
32
- // verification is named but not runnable in-file), unverified (nothing).
33
- function resolveObligations(ast) {
34
- const t = runTests(ast);
35
- const testPass = new Map();
36
- for (const res of (t.results || [])) {
37
- const cur = testPass.get(res.target);
38
- testPass.set(res.target, cur === undefined ? !!res.pass : cur && !!res.pass);
39
- }
40
- const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
41
- const matchTest = (verifyText) => {
42
- const v = norm(verifyText); if (!v) return null;
43
- for (const [name, pass] of testPass) { const n = norm(name); if (n && (n === v || n.includes(v) || v.includes(n))) return { name, pass }; }
44
- return null;
45
- };
46
- const build = (kind, o) => {
47
- const verify = o.verify || [];
48
- let status = 'unverified', provenBy = null;
49
- if (verify.length) {
50
- let m = null;
51
- for (const vt of verify) { const x = matchTest(vt); if (x) { m = x; if (!x.pass) break; } }
52
- if (m) { status = m.pass ? 'verified' : 'failed'; provenBy = m.name; } else status = 'declared';
53
- }
54
- return { kind, id: o.id, status, provenBy };
55
- };
56
- const obligations = [...ast.guarantees.map((g) => build('guarantee', g)), ...ast.neverRules.map((n) => build('prohibition', n))];
57
- return { obligations, tests: t, failed: obligations.filter((o) => o.status === 'failed').length };
58
- }
59
-
60
39
  // Freshness tuple , the (intent, implementation, dependencies, compiler, environment) binding
61
40
  // `thunder verify` recomputes later to mark a proof STALE. Mirrors freshnessFor in cli.mjs;
62
41
  // implementation/dependencies are read from the server's working directory when available.
@@ -81,6 +60,23 @@ function proofFreshness(proof, environment) {
81
60
 
82
61
  // Each tool is a pure function of its arguments. `run` returns a JSON-able value or a string.
83
62
  const TOOLS = [
63
+ {
64
+ name: 'intent_atlas',
65
+ description: 'Review multiple ThunderLang contracts before an AI change. Runs declared cases, ranks failed and unresolved claims, and returns source hashes plus a bounded agent brief. Optional OpenThunder intent prove JSON snapshots are compared by source hash and compiler; imported status never promotes a claim. Does not test application code.',
66
+ inputSchema: {
67
+ type: 'object', required: ['files'], properties: {
68
+ files: { type: 'array', maxItems: 100, items: { type: 'object', required: ['path', 'source'], properties: { path: str, source: str } } },
69
+ evidence: { type: 'object', description: 'Optional OpenThunder intent prove --json report' },
70
+ strict: { type: 'boolean', description: 'Require cases in every file and no unresolved evidence' },
71
+ },
72
+ },
73
+ run: ({ files, evidence, strict = false }) => {
74
+ if (!Array.isArray(files) || files.length > 100 || files.reduce((n, f) => n + (typeof f?.source === 'string' ? f.source.length : 0), 0) > 1000000) throw new Error('Provide up to 100 files and 1 MB of source.');
75
+ const atlas = buildReviewAtlas(files, { evidence });
76
+ const exitCode = reviewAtlasExitCode(atlas, { strict });
77
+ return { ok: exitCode === 0, exitCode, atlas, brief: renderReviewBrief(atlas) };
78
+ },
79
+ },
84
80
  {
85
81
  name: 'intent_check',
86
82
  description: 'Run ThunderLang semantic diagnostics on .intent source. Returns the diagnostics (codes, severity, messages) , the deterministic checks that catch missing verification, secrets on the bus, contradictions, and more.',
@@ -221,48 +217,137 @@ const TOOLS = [
221
217
  inputSchema: { type: 'object', required: ['code'], properties: { code: { ...str, description: 'e.g. IL-SEC-001' } } },
222
218
  run: ({ code }) => ALL_DIAGNOSTICS.find((r) => r.ruleId.toLowerCase() === String(code).toLowerCase()) || { code, found: false },
223
219
  },
220
+ {
221
+ name: 'intent_read',
222
+ 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.`,
223
+ inputSchema: {
224
+ type: 'object', required: ['source'],
225
+ properties: {
226
+ source: { ...str, description: 'the source code' },
227
+ language: { ...str, description: `source language; detected when omitted. One of: ${READ_LANGUAGES.join(', ')}` },
228
+ query: { ...str, description: 'free-text search over names, inputs, conditions, and answers' },
229
+ kinds: { type: 'array', items: { type: 'string', enum: ['decision', 'function', 'error', 'test'] }, description: 'only these kinds' },
230
+ in: { ...str, description: `rewrite decisions in this language: ${TRANSLATE_LANGUAGES.map((l) => l.key).join(', ')}` },
231
+ },
232
+ },
233
+ run: ({ source, language, query = '', kinds = [], in: inLang }) => {
234
+ const reading = readCode(String(source), { language });
235
+ const items = searchReading(reading, { query, kinds }).map((it) => (inLang && it.thunder
236
+ ? { ...it, rewritten: { language: inLang, code: translateDecisions(parseIntent(it.thunder), inLang) } }
237
+ : it));
238
+ return { ...reading, items };
239
+ },
240
+ },
241
+ {
242
+ name: 'intent_read_repo',
243
+ 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.`,
244
+ inputSchema: {
245
+ type: 'object', required: ['path'],
246
+ properties: {
247
+ path: { ...str, description: 'folder to read (absolute, or relative to the server working directory)' },
248
+ query: str,
249
+ kinds: { type: 'array', items: { type: 'string', enum: ['route', 'decision', 'guard', 'function', 'error', 'test'] } },
250
+ languages: { type: 'array', items: { type: 'string', enum: READ_LANGUAGES } },
251
+ folder: { ...str, description: 'only files under this relative path prefix' },
252
+ answer: { ...str, description: 'only items that answer, fail, or respond with this value' },
253
+ input: { ...str, description: 'only decisions that use this input' },
254
+ limit: { type: 'number', description: 'max items to return (default 50)' },
255
+ },
256
+ },
257
+ run: ({ path, query = '', kinds = [], languages = [], folder = '', answer = '', input = '', limit = 50 }) => {
258
+ const index = readRepo(collectReadableFiles(resolve(String(path))));
259
+ const items = searchRepo(index, { query, kinds, languages, path: folder, answer, input });
260
+ const { files, ...rest } = index;
261
+ return { ...rest, files: files.length, matched: items.length, items: items.slice(0, Math.max(1, Math.min(500, Number(limit) || 50))) };
262
+ },
263
+ },
264
+ {
265
+ name: 'intent_promote',
266
+ 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.',
267
+ inputSchema: {
268
+ type: 'object', required: ['source', 'name'],
269
+ 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)` } },
270
+ },
271
+ run: ({ source, name, language }) => {
272
+ const item = readCode(String(source), { language }).items.find((i) => i.name === name);
273
+ if (!item) return { ok: false, reason: `No function named ${name} was found.` };
274
+ const p = promoteDecision(item);
275
+ return p.ok ? { ...p, examplesPass: previewHumanContract(p.source).tests } : p;
276
+ },
277
+ },
278
+ {
279
+ name: 'intent_translate',
280
+ 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.`,
281
+ inputSchema: {
282
+ type: 'object', required: ['source', 'language'],
283
+ properties: { source: str, language: { type: 'string', enum: TRANSLATE_LANGUAGES.map((l) => l.key) } },
284
+ },
285
+ run: ({ source, language }) => {
286
+ const text = String(source);
287
+ const canonical = /^\s*contract\s/m.test(text.split('\n').find((l) => l.trim() && !l.trim().startsWith('#')) || '')
288
+ ? previewHumanContract(text).canonicalSource : text;
289
+ return translateDecisions(parseIntent(canonical), language);
290
+ },
291
+ },
292
+ {
293
+ name: 'intent_human',
294
+ 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.',
295
+ inputSchema: { type: 'object', required: ['source'], properties: { source: str } },
296
+ run: ({ source }) => previewHumanContract(String(source)),
297
+ },
224
298
  ];
225
299
 
226
- export const MCP_TOOLS = TOOLS.map((t) => t.name);
300
+ // Tools that are pure functions of their arguments (no filesystem, git, or process state), so they
301
+ // are safe to serve to remote clients such as ChatGPT. intent_prove reads the local repository.
302
+ 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
303
 
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 } });
304
+ export const MCP_TOOLS = TOOLS.map((t) => t.name);
233
305
 
234
- function handle(msg) {
306
+ /**
307
+ * A transport-free MCP handler: give it one JSON-RPC message, get back the response object (or
308
+ * null for notifications). Shared by the stdio server and the hosted HTTP endpoint.
309
+ */
310
+ export function createMcpHandler({ tools = MCP_TOOLS } = {}) {
311
+ const allowed = TOOLS.filter((t) => tools.includes(t.name));
312
+ const ok = (id, result) => ({ jsonrpc: '2.0', id, result });
313
+ const err = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
314
+ return function handle(msg) {
235
315
  const { id, method, params } = msg || {};
236
316
  switch (method) {
237
- case 'initialize':
238
- respond(id, { protocolVersion: PROTOCOL_VERSION, capabilities: { tools: {} }, serverInfo: { name: 'thunderlang', version: COMPILER_VERSION } });
239
- break;
317
+ case 'initialize': {
318
+ const asked = params?.protocolVersion;
319
+ const protocolVersion = SUPPORTED_PROTOCOLS.includes(asked) ? asked : PROTOCOL_VERSION;
320
+ return ok(id, { protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'thunderlang', version: COMPILER_VERSION } });
321
+ }
240
322
  case 'notifications/initialized':
241
323
  case 'initialized':
242
324
  case 'notifications/cancelled':
243
- break; // notifications , no response
325
+ return null; // notifications , no response
244
326
  case 'ping':
245
- respond(id, {});
246
- break;
327
+ return ok(id, {});
247
328
  case 'tools/list':
248
- respond(id, { tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });
249
- break;
329
+ return ok(id, { tools: allowed.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });
250
330
  case 'tools/call': {
251
- const tool = TOOLS.find((t) => t.name === params?.name);
252
- if (!tool) { fail(id, -32602, `Unknown tool: ${params?.name}`); break; }
331
+ const tool = allowed.find((t) => t.name === params?.name);
332
+ if (!tool) return err(id, -32602, `Unknown tool: ${params?.name}`);
253
333
  try {
254
334
  const result = tool.run(params.arguments || {});
255
335
  const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
256
- respond(id, { content: [{ type: 'text', text }] });
336
+ return ok(id, { content: [{ type: 'text', text }] });
257
337
  } catch (e) {
258
- respond(id, { content: [{ type: 'text', text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true });
338
+ return ok(id, { content: [{ type: 'text', text: `Error: ${e instanceof Error ? e.message : String(e)}` }], isError: true });
259
339
  }
260
- break;
261
340
  }
262
341
  default:
263
- if (id != null) fail(id, -32601, `Method not found: ${method}`);
342
+ return id != null ? err(id, -32601, `Method not found: ${method}`) : null;
264
343
  }
265
- }
344
+ };
345
+ }
346
+
347
+ /** Start the ThunderLang MCP server over the given streams (default: process stdio). */
348
+ export function startMcpServer({ readable = process.stdin, writable = process.stdout } = {}) {
349
+ const respondTo = createMcpHandler();
350
+ const handle = (msg) => { const reply = respondTo(msg); if (reply) writable.write(`${JSON.stringify(reply)}\n`); };
266
351
 
267
352
  let buffer = '';
268
353
  readable.on('data', (chunk) => {
@@ -0,0 +1,9 @@
1
+ import type { ObligationResolution, TestReport } from './index.js';
2
+ export function resolveObligations(ast: unknown): {
3
+ obligations: ObligationResolution[];
4
+ tests: TestReport;
5
+ verified: number;
6
+ declared: number;
7
+ unverified: number;
8
+ failed: number;
9
+ };
@@ -0,0 +1,35 @@
1
+ import { runTests } from './testing.mjs';
2
+
3
+ // One binding policy for CLI, MCP, website, and embedding products. A reference
4
+ // names a complete test target, not a substring, prose description, or similar name.
5
+ // "verified" is scoped to the declared cases; it says nothing about application code.
6
+ export function resolveObligations(ast) {
7
+ const tests = runTests(ast);
8
+ const byTarget = new Map();
9
+ for (const result of tests.results) {
10
+ const name = String(result.target).trim();
11
+ const previous = byTarget.get(name);
12
+ byTarget.set(name, { name, pass: (previous?.pass ?? true) && result.pass, cases: (previous?.cases ?? 0) + 1 });
13
+ }
14
+ const build = (kind, claim) => {
15
+ const verify = claim.verify || [];
16
+ const names = [...new Set(verify.map((v) => String(v).trim()))];
17
+ const evidence = names.map((name) => byTarget.get(name) || (name.startsWith('test ') ? byTarget.get(name.slice(5).trim()) : null) || { name, pass: null, cases: 0 });
18
+ const unresolved = evidence.filter((e) => e.pass === null).map((e) => e.name);
19
+ const status = !names.length ? 'unverified'
20
+ : evidence.some((e) => e.pass === false) ? 'failed'
21
+ : unresolved.length ? 'declared' : 'verified';
22
+ return {
23
+ kind, id: claim.id, text: claim.statement, status, verify,
24
+ kinds: [...new Set((claim.verifications || []).map((v) => v.kind).filter((k) => k && k !== 'unclassified'))],
25
+ provenBy: status === 'verified' || status === 'failed' ? evidence.filter((e) => e.pass !== null).map((e) => e.name).join(', ') : null,
26
+ evidence, unresolved,
27
+ };
28
+ };
29
+ const obligations = [
30
+ ...(ast.guarantees || []).map((g) => build('guarantee', g)),
31
+ ...(ast.neverRules || []).map((n) => build('prohibition', n)),
32
+ ];
33
+ const count = (s) => obligations.filter((o) => o.status === s).length;
34
+ return { obligations, tests, verified: count('verified'), declared: count('declared'), unverified: count('unverified'), failed: count('failed') };
35
+ }
@@ -0,0 +1,30 @@
1
+ export const PLAIN_SCHEMA: 'thunder-plain-v1';
2
+ export const COMPARISONS: ReadonlyArray<{ op: '>=' | '<=' | '<' | '>' | '=='; words: string[] }>;
3
+ export type PlainInput =
4
+ | { id: string; kind: 'dollars' | 'number' | 'text' | 'other'; label: string }
5
+ | { id: string; kind: 'yesno'; label: string; yes: string; no: string; fromState?: boolean };
6
+ export type PlainCondition = { input: string; op: '>=' | '<=' | '<' | '>' | '==' | '!=' | 'is'; value: number | boolean | string };
7
+ export type PlainRule = { outcome: string; join: 'all' | 'any'; conditions: PlainCondition[] };
8
+ export type PlainExample = { name: string; values: Record<string, number | boolean | string>; expected: string };
9
+ export interface PlainModel {
10
+ schema: 'thunder-plain-v1';
11
+ title: string; why: string; question: string;
12
+ inputs: PlainInput[]; rules: PlainRule[]; otherwise: string; examples: PlainExample[];
13
+ }
14
+ export interface PlainCheck { text: string; ok: boolean; actual: string; input: string }
15
+ export interface PlainExplanation { outcome: string | null; ruleIndex: number; rules: Array<{ outcome: string; join: 'all' | 'any'; checks: PlainCheck[] }>; ok: boolean }
16
+ export interface PlainPreview {
17
+ schema: 'thunder-plain-v1'; experimental: true; model: PlainModel; canonicalSource: string; plainSource: string;
18
+ tests: { total: number; passed: number; failed: number; results: Array<{ name: string; values: Record<string, number | boolean | string>; expected: unknown; actual: unknown; pass: boolean }> };
19
+ application: 'not_checked';
20
+ }
21
+ export function parsePlainContract(source: string): PlainModel;
22
+ export function renderPlainContract(model: PlainModel): string;
23
+ export function plainToThunder(model: PlainModel): string;
24
+ export function compilePlainContract(source: string): string;
25
+ export function conditionText(model: PlainModel, condition: PlainCondition): string;
26
+ export function formatValue(input: PlainInput, value: number | boolean | string): string;
27
+ export function outcomesOf(model: PlainModel): string[];
28
+ export function explainPlain(model: PlainModel, values: Record<string, number | boolean | string>): PlainExplanation;
29
+ export function previewPlainContract(sourceOrModel: string | PlainModel): PlainPreview;
30
+ export function plainFromReading(item: unknown): (PlainModel & { provenance: 'inferred-from-code'; needsReview: string[]; partial?: boolean }) | null;