@skillstech/thunderlang 1.7.0 → 2.0.0

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 (73) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +15 -3
  3. package/dist/core.cjs +303 -41
  4. package/dist/index.cjs +9906 -1387
  5. package/dist/learn.cjs +1420 -93
  6. package/package.json +17 -15
  7. package/src/cli-main.mjs +381 -149
  8. package/src/core/ThunderRuntime.cs +22 -1
  9. package/src/core/check.mjs +320 -6
  10. package/src/core/cli.mjs +60 -8
  11. package/src/core/csharp-run.mjs +2 -2
  12. package/src/core/diagnostics.mjs +9 -0
  13. package/src/core/engine-core.mjs +148 -19
  14. package/src/core/engine-values.mjs +3 -0
  15. package/src/core/engine.mjs +131 -7
  16. package/src/core/from-python.mjs +1 -1
  17. package/src/core/go-run.mjs +5 -3
  18. package/src/core/index.mjs +12 -3
  19. package/src/core/java/thunder/ThunderRuntime.java +1 -0
  20. package/src/core/java-run.mjs +2 -2
  21. package/src/core/kind.mjs +6 -0
  22. package/src/core/lexer.mjs +16 -2
  23. package/src/core/parser.mjs +215 -29
  24. package/src/core/project-root.mjs +18 -0
  25. package/src/core/project.mjs +34 -16
  26. package/src/core/react-run.mjs +2 -2
  27. package/src/core/runtime-go/thunder_runtime.go +310 -2
  28. package/src/core/runtime-python.mjs +365 -3
  29. package/src/core/runtime-typescript.mjs +150 -5
  30. package/src/core/rust/thunder_runtime.rs +1 -0
  31. package/src/core/rust-run.mjs +2 -2
  32. package/src/core/serving.mjs +12 -0
  33. package/src/core/store-format.mjs +110 -0
  34. package/src/core/target-csharp.mjs +14 -0
  35. package/src/core/target-go.mjs +24 -3
  36. package/src/core/target-java.mjs +14 -0
  37. package/src/core/target-python.mjs +46 -5
  38. package/src/core/target-rust.mjs +14 -0
  39. package/src/core/target-typescript.mjs +76 -6
  40. package/src/core/typescript-run.mjs +6 -4
  41. package/src/core-changes-fs.mjs +28 -0
  42. package/src/core-changes.d.mts +67 -0
  43. package/src/core-changes.mjs +603 -0
  44. package/src/core-rules.mjs +146 -0
  45. package/src/core-services.d.mts +4 -0
  46. package/src/core-services.mjs +49 -0
  47. package/src/emit.mjs +3 -3
  48. package/src/evidence-words.d.mts +6 -0
  49. package/src/evidence-words.mjs +47 -0
  50. package/src/evidence.mjs +36 -1
  51. package/src/examples.d.mts +21 -0
  52. package/src/examples.mjs +175 -0
  53. package/src/index.d.ts +19 -0
  54. package/src/index.mjs +8 -1
  55. package/src/learn-lessons.mjs +1 -1
  56. package/src/lsp.mjs +110 -0
  57. package/src/mcp.mjs +47 -12
  58. package/src/obligations.d.mts +5 -0
  59. package/src/obligations.mjs +30 -2
  60. package/src/program.d.mts +7 -0
  61. package/src/program.mjs +7 -0
  62. package/src/read-repo-fs.mjs +2 -1
  63. package/src/review.mjs +75 -6
  64. package/src/same.mjs +16 -6
  65. package/src/scan-queries.mjs +2 -1
  66. package/src/symbols.d.mts +23 -0
  67. package/src/symbols.mjs +351 -0
  68. package/src/system.mjs +1 -1
  69. package/src/template.d.mts +31 -0
  70. package/src/template.mjs +189 -0
  71. package/src/trace-cli.mjs +8 -3
  72. package/src/trace-fs.mjs +29 -3
  73. package/src/trace.mjs +23 -7
@@ -0,0 +1,146 @@
1
+ // The rules of a Thunder™ Core program and what each one uses: the shared base of core-changes.mjs (behaviour changes,
2
+ // affectedBy) and core-services.mjs (Thunder Trace). Only the checker is used here, never the engine, so reading the
3
+ // rules runs nothing. Browser-safe.
4
+ //
5
+ // A rule's name comes from what it is, never from its line: `function:decide refund`, `endpoint:POST /orders`,
6
+ // `keep:review limit`, `never:Product: Never allow a negative stock`, `record:Product`, `store:products`,
7
+ // `test:the refund rule`, `main:<file>`. What it uses (functions it calls, kept values, data types and their Never
8
+ // rules, stored lists, endpoints a test calls, "http" for a call to another service) is read from the checked program.
9
+
10
+ import { compileCore } from './core/index.mjs';
11
+ import { isCoreProgram } from './core/kind.mjs';
12
+
13
+ export { isCoreProgram };
14
+ const isTestPath = (p) => /(^|\/)tests\//.test(p);
15
+ const projectRoot = (p, dir) => { const m = new RegExp(`(^|/)${dir}/`).exec(p); return m ? p.slice(0, m.index + m[1].length) : null; };
16
+ const moduleName = (p) => p.replace(/^.*\//, '').replace(/\.thunder$/i, '').toLowerCase().replace(/[^a-z0-9_]+/g, '_') || 'program';
17
+
18
+ // ── 1. A side: its files compiled, and its rules with what each uses ────────────────────────────────────────────
19
+
20
+ export function coreSide(files) {
21
+ const core = (files ?? []).filter((f) => f && isCoreProgram(f.path, f.source));
22
+ const results = [];
23
+ const srcs = core.filter((f) => !isTestPath(f.path));
24
+ for (const f of srcs) results.push(Object.assign(compileCore(f.source, { file: f.path }), { path: f.path, source: f.source, kind: 'src' }));
25
+ for (const f of core.filter((x) => isTestPath(x.path))) {
26
+ // A test sees the src/ files of its own project (the folder above tests/), as in thunder test.
27
+ const root = projectRoot(f.path, 'tests') ?? '';
28
+ const seen = results.filter((r) => r.kind === 'src' && r.ok && r.path.startsWith(root));
29
+ results.push(Object.assign(compileCore(f.source, { file: f.path, imported: seen, srcModules: seen.map((r) => moduleName(r.path)) }), { path: f.path, source: f.source, kind: 'test' }));
30
+ }
31
+ const units = new Map();
32
+ const records = new Map(); // a data type's name (lowercase) -> its unit id
33
+ for (const r of results) for (const u of unitsOf(r)) {
34
+ let id = u.id;
35
+ if (units.has(id)) id = `${u.id} (${r.path})`; // the same name in two files: told apart by the file
36
+ units.set(id, { ...u, id });
37
+ if (u.kind === 'record') records.set(u.node.name, id);
38
+ }
39
+ for (const u of units.values()) u.uses = usesOf(u, units, records);
40
+ // Who uses each rule, for impact.
41
+ const usedBy = new Map();
42
+ for (const u of units.values()) for (const d of u.uses) { if (!usedBy.has(d)) usedBy.set(d, new Set()); usedBy.get(d).add(u.id); }
43
+ return { files: core, results, units, usedBy, records, engine: null };
44
+ }
45
+
46
+ export const KIND_WORD = { function: 'function', endpoint: 'endpoint', keep: 'kept value', record: 'data type', never: 'rule', store: 'stored list', test: 'test', main: 'main program' };
47
+
48
+ /** The rules of one compiled file: each top-level block, with its own lines (comments and blank lines left out). */
49
+ export function unitsOf(r) {
50
+ const body = r.program?.body ?? [];
51
+ if (!body.length) return [];
52
+ const lines = r.source.split(/\r?\n/);
53
+ const starts = body.map((s) => s.line).filter((n) => n != null);
54
+ const endOf = (s) => { const next = starts.filter((n) => n > s.line); return next.length ? Math.min(...next) - 1 : lines.length; };
55
+ const clean = (from, to, skip = new Set()) => {
56
+ const out = [];
57
+ for (let n = from; n <= to; n++) { if (skip.has(n)) continue; const t = (lines[n - 1] ?? '').replace(/\s+$/, ''); if (t.trim() && !t.trim().startsWith('#')) out.push(t); }
58
+ return out;
59
+ };
60
+ const out = [];
61
+ const main = [];
62
+ for (const s of body) {
63
+ const base = { file: r.path, line: s.line, end: endOf(s), node: s, result: r };
64
+ if (s.k === 'func' && s.endpoint) out.push({ ...base, id: `endpoint:${s.endpoint.method} ${s.endpoint.path}`, kind: 'endpoint', subject: `${s.endpoint.method} ${s.endpoint.path}`, text: clean(s.line, endOf(s)) });
65
+ else if (s.k === 'func') out.push({ ...base, id: `function:${s.text}`, kind: 'function', subject: s.text, text: clean(s.line, endOf(s)) });
66
+ else if (s.k === 'keep') out.push({ ...base, id: `keep:${s.text}`, kind: 'keep', subject: s.text, text: clean(s.line, endOf(s)) });
67
+ else if (s.k === 'store') out.push({ ...base, id: `store:${s.text}`, kind: 'store', subject: `stored list ${s.text}`, text: clean(s.line, endOf(s)) });
68
+ else if (s.k === 'test') out.push({ ...base, id: `test:${s.title}`, kind: 'test', subject: `test "${s.title}"`, text: clean(s.line, endOf(s)) });
69
+ else if (s.k === 'record') {
70
+ const nevers = (s.rules ?? []).filter((x) => x.k === 'never');
71
+ out.push({ ...base, id: `record:${s.text}`, kind: 'record', subject: s.text, text: clean(s.line, endOf(s), new Set(nevers.map((x) => x.line))) });
72
+ for (const n of nevers) out.push({ ...base, line: n.line, end: n.line, node: n, record: s, id: `never:${s.text}: ${n.text}`, kind: 'never', subject: `${s.text}: ${n.text}`, text: [n.text] });
73
+ } else main.push(s);
74
+ }
75
+ if (main.length) {
76
+ const text = main.flatMap((s) => clean(s.line, endOf(s)));
77
+ out.push({ file: r.path, line: main[0].line, node: { k: 'main', body: main }, result: r, id: `main:${r.path}`, kind: 'main', subject: `the main program of ${r.path}`, text });
78
+ }
79
+ return out;
80
+ }
81
+
82
+ export const SKIP_KEYS = new Set(['type', 'ref', 'rulesToCheck', 'records', 'fieldMap', 'record', 'mod', 'f']);
83
+
84
+ /** What a rule uses, as rule ids: functions it calls, kept values, stored lists, data types and their rules. */
85
+ export function usesOf(u, units, records) {
86
+ const uses = new Set();
87
+ const addRecord = (name) => {
88
+ const id = records.get(name);
89
+ if (!id) return;
90
+ uses.add(id);
91
+ const rec = units.get(id);
92
+ for (const n of rec.node.rules ?? []) if (n.k === 'never') uses.add(`never:${rec.node.text}: ${n.text}`);
93
+ };
94
+ const recordType = (t) => { while (t && (t.k === 'optional' || t.k === 'list')) t = t.of; return t?.k === 'record' ? t.name : null; };
95
+ const seen = new Set();
96
+ const walk = (x) => {
97
+ if (!x || typeof x !== 'object' || seen.has(x)) return;
98
+ seen.add(x);
99
+ if (Array.isArray(x)) { for (const y of x) walk(y); return; }
100
+ const ref = x.ref;
101
+ if (ref?.kind === 'const') uses.add(`keep:${ref.text ?? x.text}`);
102
+ else if (ref?.kind === 'store') uses.add(`store:${ref.text ?? x.text}`);
103
+ if (x.k === 'call' && x.method) { const e = endpointFor(units, x.method, x.path); if (e) uses.add(e); } // a test's "calling POST /orders/1"
104
+ else if (x.k === 'call' && x.text) uses.add(`function:${x.text}`);
105
+ else if (x.k === 'new' && x.record) addRecord(x.record);
106
+ else if (x.k === 'httpCall') uses.add('http');
107
+ else if (x.k === 'callEndpoint') { const e = endpointFor(units, x.method, x.path); if (e) uses.add(e); }
108
+ else if (x.k === 'field' && x.obj?.type) { const r = recordType(x.obj.type); if (r) addRecord(r); }
109
+ if (Array.isArray(x.params)) for (const p of x.params) { const r = recordType(p.type); if (r) addRecord(r); }
110
+ for (const [k, v] of Object.entries(x)) if (!SKIP_KEYS.has(k)) walk(v);
111
+ };
112
+ walk(u.kind === 'never' ? u.node.cond : u.node);
113
+ uses.delete(u.id);
114
+ // Only rules this side has (and "http", a call to another service), so a built-in name is not a dependency.
115
+ return new Set([...uses].filter((d) => d === 'http' || units.has(d)));
116
+ }
117
+
118
+ /** The endpoint answering METHOD /path (a test's "calling POST /orders/1/refunds" -> POST /orders/{number}/refunds). */
119
+ export function endpointFor(units, method, path) {
120
+ const got = String(path).split('/').filter(Boolean);
121
+ for (const u of units.values()) {
122
+ if (u.kind !== 'endpoint' || u.node.endpoint.method !== method) continue;
123
+ const parts = u.node.endpoint.path.split('/').filter(Boolean);
124
+ if (parts.length === got.length && parts.every((p, i) => /^\{.*\}$/.test(p) || p === got[i])) return u.id;
125
+ }
126
+ return null;
127
+ }
128
+
129
+ /** Everything a rule uses, all the way down. */
130
+ export function reach(s, id) {
131
+ const out = new Set();
132
+ const todo = [id];
133
+ while (todo.length) { const x = todo.pop(); for (const d of s.units.get(x)?.uses ?? []) if (!out.has(d)) { out.add(d); todo.push(d); } }
134
+ return out;
135
+ }
136
+
137
+ /** Everything that uses one of `ids`, all the way up, each with the chain that reaches it: Map(id -> [via ids]). */
138
+ export function dependents(s, ids) {
139
+ const via = new Map();
140
+ const todo = [...ids].map((id) => [id, [id]]);
141
+ while (todo.length) {
142
+ const [x, chain] = todo.shift();
143
+ for (const u of s.usedBy.get(x) ?? []) if (!via.has(u) && !ids.has(u)) { via.set(u, chain); todo.push([u, [...chain, u]]); }
144
+ }
145
+ return via;
146
+ }
@@ -0,0 +1,4 @@
1
+ // Types for core-services.mjs: a Thunder Core program's endpoints and calls, for Thunder Trace.
2
+ export interface CoreRoute { method: string; path: string; segs: string[]; member: string; label: string; file: string; line: number; lines: [number, number]; reach: Array<{ file: string; lines: [number, number]; subject: string }> }
3
+ export interface CoreRequest { method: string; path: string; segs: string[]; base: string; member: string; label: string; file: string; line: number; lines: [number, number] }
4
+ export function coreServiceFacts(files: Array<{ path: string; source: string }>): { routes: CoreRoute[]; requests: CoreRequest[]; unknown: Array<{ member: string; label: string; file: string; line: number; call: string; why: string }>; files: number };
@@ -0,0 +1,49 @@
1
+ // What a Thunder™ Core program offers other services and asks of them, for Thunder Trace: its endpoints (routes) and
2
+ // its calls to other services ("the answer from GET …", requests), in the shape serviceFacts gives for other
3
+ // languages. Read from the checked program; nothing is run. Browser-safe.
4
+ //
5
+ // One thing other languages don't have: each route carries what it reaches (`reach`): the lines of every rule it
6
+ // uses, all the way down (helpers, kept values, data types and their Never rules). So a changed kept value on line 29
7
+ // is a change to POST /orders/{number}/refunds on line 84, through decide refund, and Trace can say who calls it.
8
+
9
+ import { coreSide, reach, isCoreProgram } from './core-rules.mjs';
10
+ import { routeSegs, requestTarget } from './system.mjs';
11
+
12
+
13
+ /** { routes, requests, unknown, files } for the Core programs among `files` ([{ path, source }]). Other files are ignored. */
14
+ export function coreServiceFacts(files) {
15
+ const core = (files ?? []).filter((f) => f && isCoreProgram(f.path, f.source));
16
+ if (!core.length) return { routes: [], requests: [], unknown: [], files: 0 };
17
+ const s = coreSide(core);
18
+ const routes = [], requests = [], unknown = [];
19
+ const at = (u, line) => ({ member: u.id, label: u.subject, file: u.file, line: line ?? u.line, lines: [u.line, u.end] });
20
+ for (const u of s.units.values()) {
21
+ if (u.kind === 'endpoint') {
22
+ const { method, path } = u.node.endpoint;
23
+ // What it reaches, as line ranges in each file, with the rule each range belongs to.
24
+ const reached = [...reach(s, u.id)].map((id) => s.units.get(id)).filter(Boolean).map((x) => ({ file: x.file, lines: [x.line, x.end], subject: x.subject }));
25
+ routes.push({ method, path, segs: routeSegs(path), ...at(u), reach: reached });
26
+ }
27
+ if (u.kind !== 'function' && u.kind !== 'endpoint' && u.kind !== 'main') continue;
28
+ for (const call of httpCallsIn(u.node)) {
29
+ const t = call.url?.k === 'str' ? requestTarget({ kind: 'template', parts: call.url.parts.map((p) => (typeof p === 'string' ? p : {})) }) : null;
30
+ if (t) requests.push({ method: call.method, path: t.path, segs: t.segs, base: t.base, ...at(u, call.line) });
31
+ else unknown.push({ ...at(u, call.line), call: `${call.method} request`, why: call.url?.k === 'str' ? 'the address is not a full URL written in the code' : 'computed URL: the address is worked out when it runs' });
32
+ }
33
+ }
34
+ return { routes, requests, unknown, files: core.length };
35
+ }
36
+
37
+ function httpCallsIn(node) {
38
+ const out = [], seen = new Set();
39
+ const walk = (x) => {
40
+ if (!x || typeof x !== 'object' || seen.has(x)) return;
41
+ seen.add(x);
42
+ if (Array.isArray(x)) { for (const y of x) walk(y); return; }
43
+ if (x.k === 'httpCall') out.push(x);
44
+ for (const [k, v] of Object.entries(x)) if (k !== 'type' && k !== 'ref' && k !== 'record' && k !== 'records') walk(v);
45
+ };
46
+ walk(node);
47
+ return out;
48
+ }
49
+
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '1.7.0';
33
+ export const COMPILER_VERSION = '2.0.0';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
@@ -475,7 +475,6 @@ export function semanticDiagnostics(ast) {
475
475
  // ── .intent-proof.json ───────────────────────────────────────────────────────
476
476
  export function buildProof(ast, { sourceFile, sourceHash, targetsRequested, targetsGenerated, diagnostics, generatedAt, origin = 'authored' }) {
477
477
  const passedSemantic = !diagnostics.some((x) => x.level === 'error');
478
- const verifiedText = ast.verify.join(' ').toLowerCase();
479
478
  return {
480
479
  schemaVersion: PROOF_SCHEMA_VERSION,
481
480
  sourceProduct: SOURCE_PRODUCT,
@@ -492,7 +491,8 @@ export function buildProof(ast, { sourceFile, sourceHash, targetsRequested, targ
492
491
  targetsGenerated,
493
492
  guarantees: ast.guarantees.map((g) => ({
494
493
  id: g.id, text: g.statement,
495
- status: g.verify.length > 0 || verifiedText ? 'planned' : 'needs_verification',
494
+ // planned only when this guarantee names its own check; a verify block elsewhere in the mission doesn't count.
495
+ status: g.verify.length > 0 ? 'planned' : 'needs_verification',
496
496
  evidence: g.verify,
497
497
  verifications: g.verifications || [],
498
498
  })),
@@ -0,0 +1,6 @@
1
+ export type EvidenceLevel = 'proven' | 'tested' | 'partial' | 'unverified' | 'violated';
2
+ export const EVIDENCE_LEVELS: EvidenceLevel[];
3
+ export const EVIDENCE_WORDS: Record<EvidenceLevel, { word: string; means: string }>;
4
+ export function evidenceWord(level: string): string | null;
5
+ export function evidenceMeaning(level: string): string | null;
6
+ export function combineEvidence(levels: Iterable<string>): EvidenceLevel;
@@ -0,0 +1,47 @@
1
+ // The five evidence words (roadmap 4.5). Everywhere Thunder tells a person how strongly something is checked, it
2
+ // uses one of these words, with this meaning, and says what the evidence was. Browser-safe, no dependencies.
3
+ //
4
+ // Proven holds for every possible input: checked exhaustively, or proved by a solver
5
+ // Tested passed on the cases that ran, and only on those
6
+ // Partially checked some parts are checked and passed; others are not checked yet (each is named)
7
+ // Unverified nothing checks it yet
8
+ // Violated a check failed: there is a case where it does not hold (the case is shown)
9
+ //
10
+ // The words are about evidence, not about how sure anyone feels. "Tested" never becomes "Proven" because there were
11
+ // many tests. Machine fields keep their own values (an obligation's status is still "verified" in JSON, for the
12
+ // tools that read it); each also carries `evidence`, one of the keys below, and people see the word.
13
+
14
+ export const EVIDENCE_LEVELS = ['proven', 'tested', 'partial', 'unverified', 'violated'];
15
+
16
+ export const EVIDENCE_WORDS = {
17
+ proven: { word: 'Proven', means: 'holds for every possible input: checked exhaustively, or proved by a solver' },
18
+ tested: { word: 'Tested', means: 'passed on the cases that ran, and only on those' },
19
+ partial: { word: 'Partially checked', means: 'some parts are checked and passed; others are not checked yet' },
20
+ unverified: { word: 'Unverified', means: 'nothing checks it yet' },
21
+ violated: { word: 'Violated', means: 'a check failed: there is a case where it does not hold' },
22
+ };
23
+
24
+ /** The word for a level ("Tested"), or null for a level that isn't one of the five. */
25
+ export function evidenceWord(level) {
26
+ return EVIDENCE_WORDS[level]?.word ?? null;
27
+ }
28
+
29
+ /** "Tested: passed on the cases that ran, and only on those". */
30
+ export function evidenceMeaning(level) {
31
+ const w = EVIDENCE_WORDS[level];
32
+ return w ? `${w.word}: ${w.means}` : null;
33
+ }
34
+
35
+ /**
36
+ * The level of something made of parts: a failed part makes it Violated; every part Proven makes it Proven; every
37
+ * part checked makes it Tested; some checked and some not makes it Partially checked; nothing checked, Unverified.
38
+ */
39
+ export function combineEvidence(levels) {
40
+ const ls = [...levels].filter((l) => EVIDENCE_LEVELS.includes(l));
41
+ if (!ls.length) return 'unverified';
42
+ if (ls.includes('violated')) return 'violated';
43
+ if (ls.every((l) => l === 'proven')) return 'proven';
44
+ if (ls.every((l) => l === 'proven' || l === 'tested')) return 'tested';
45
+ if (ls.every((l) => l === 'unverified')) return 'unverified';
46
+ return 'partial';
47
+ }
package/src/evidence.mjs CHANGED
@@ -13,6 +13,14 @@
13
13
  // NOTE: the evidence-event-v1 envelope below is ThunderLang's PROPOSED shape, pending STW's canonical
14
14
  // schema (see the TL->STW proposal on the comms bus). Field names may adjust once STW confirms.
15
15
 
16
+ import { sha256hex } from './hash.mjs';
17
+ import { combineEvidence } from './evidence-words.mjs';
18
+
19
+ // The evidence word for a claim (docs/evidence-words.md). evidenceType 'tool_verified' names the layer (a deterministic
20
+ // tool made the event), not how strong the evidence is: that is `evidence`, one of proven / tested / partial /
21
+ // unverified / violated. A claim whose named test passed is tested; a planned one (named, not run) is unverified.
22
+ const CLAIM_EVIDENCE = { verified: 'tested', failed: 'violated', planned: 'unverified', needs_verification: 'unverified' };
23
+
16
24
  const COUNTED_STATUSES = ['verified', 'failed', 'planned', 'needs_verification'];
17
25
  const stripHash = (h) => String(h || '').replace(/^sha256:/, '');
18
26
  const short = (h, n = 16) => stripHash(h).slice(0, n);
@@ -34,7 +42,7 @@ function envelope(eventType, evidenceId, ctx = {}, payload = {}) {
34
42
  };
35
43
  }
36
44
 
37
- const safeClaim = (kind, c) => ({ id: c.id, kind, status: c.status, provenBy: c.provenBy || null });
45
+ const safeClaim = (kind, c) => ({ id: c.id, kind, status: c.status, evidence: c.evidenceLevel || CLAIM_EVIDENCE[c.status] || 'unverified', provenBy: c.provenBy || null });
38
46
  function countByStatus(claims) {
39
47
  const counts = Object.fromEntries(COUNTED_STATUSES.map((s) => [s, 0]));
40
48
  for (const c of claims) if (c && Object.prototype.hasOwnProperty.call(counts, c.status)) counts[c.status]++;
@@ -60,6 +68,7 @@ export function toEvidenceEvents(proof) {
60
68
  proofStatus: proof.proofStatus || null,
61
69
  total: claims.length,
62
70
  counts: countByStatus(claims),
71
+ evidence: combineEvidence(claims.map((c) => c.evidence)),
63
72
  freshness: { implementation: fr.implementation || null, dependencies: fr.dependencies ? fr.dependencies.hash || null : null, environment: fr.environment || null },
64
73
  claims,
65
74
  })];
@@ -114,3 +123,29 @@ export function driftToEvidence(report, ctx = {}) {
114
123
  findings: findings.map(safeFinding),
115
124
  })];
116
125
  }
126
+
127
+ // behaviour.compared , from a thunder-core-changes-v1 result (thunder review on Thunder Core programs, roadmap 3.4).
128
+ // Safe-derived like the others: rule ids, kinds of change, and counts; never source lines, answers, or messages.
129
+ // The comparison ran both versions on the inputs it tried: tested evidence, not a proof, and the payload says so.
130
+ export function behaviourToEvidence(result, ctx = {}) {
131
+ if (!result || typeof result !== 'object' || !Array.isArray(result.changes)) return [];
132
+ const changes = result.changes;
133
+ // Stable for the same change: the refs and what was found (not when it ran).
134
+ const id = `tl-behaviour-${short(ctx.changeHash || sha256hex(JSON.stringify([ctx.base ?? null, ctx.head ?? null, changes.map((c) => [c.id, c.change, c.severity, c.behaviour?.changed ?? null])])), 16)}`;
135
+ const runs = changes.map((c) => c.behaviour).filter((b) => b && !b.why);
136
+ return [envelope('behaviour.compared', id, ctx, {
137
+ method: 'both versions run on the same inputs; tested on the inputs tried, not proven',
138
+ base: ctx.base || null,
139
+ head: ctx.head || null,
140
+ total: changes.length,
141
+ risks: changes.filter((c) => c.severity === 'risk').length,
142
+ testsNowFailing: changes.filter((c) => c.kind === 'test' && c.severity === 'risk' && c.change !== 'removed').length,
143
+ inputsTried: runs.reduce((n, b) => n + (b.tried || 0), 0),
144
+ answersChanged: runs.reduce((n, b) => n + (b.changed || 0), 0),
145
+ rules: changes.map((c) => ({
146
+ id: c.id, change: c.change, severity: c.severity,
147
+ ...(c.behaviour ? (c.behaviour.why ? { run: false } : { run: true, tried: c.behaviour.tried, changed: c.behaviour.changed, kinds: c.behaviour.groups.length }) : {}),
148
+ affects: (c.affects || []).length,
149
+ })),
150
+ })];
151
+ }
@@ -0,0 +1,21 @@
1
+ export const EXAMPLES_SCHEMA: 'thunder-examples-v1';
2
+ export interface ThunderExample {
3
+ kind: 'expect' | 'case' | 'scenario';
4
+ /** The Test title, or the decision or lifecycle a mission test is for. */
5
+ block: string | null;
6
+ /** The case or scenario name (missions), or null. */
7
+ name: string | null;
8
+ line: number;
9
+ subject: { kind: 'function' | 'decision' | 'lifecycle' | 'expression'; name: string | null };
10
+ /** Core: in order, unnamed. Missions: given name and value. Scenarios: one per event, named "event". */
11
+ inputs: Array<{ name: string | null; text: string }>;
12
+ /** True when a call's inputs could not be cut from the line as written (inputs is then empty). */
13
+ inputsUnread?: boolean;
14
+ /** True when the line was read from its text, not the parser (e.g. a test file calling functions from another file). */
15
+ fromText?: boolean;
16
+ expected: { mode: 'equals' | 'compares' | 'fails' | 'result' | 'state' | 'valid' | 'invalid' | 'none'; comparison: string | null; text: string | null };
17
+ raw: string;
18
+ }
19
+ export interface ThunderExamples { schema: 'thunder-examples-v1'; kind: 'program' | 'mission'; examples: ThunderExample[]; problems: number }
20
+ /** Every example in a Thunder file (Core Test/Expect, mission test/case/scenario), read even when other parts do not compile. */
21
+ export function examplesOf(source: string, options?: { file?: string; kind?: 'program' | 'mission' | null }): ThunderExamples;
@@ -0,0 +1,175 @@
1
+ // examplesOf(source): every example in a Thunder file, as data, so tools (OpenThunder's Check, the Design Recipe
2
+ // screens, agents) read examples through one call instead of parsing Thunder text.
3
+ //
4
+ // Thunder Core: Test "members get 20% off":
5
+ // Expect calculate discount with 150 and yes to be 30
6
+ // Expect withdraw with 10 and 30 to fail with "Insufficient funds"
7
+ // Mission: test SpendAdmission
8
+ // case below the budget
9
+ // given remainingCents 100, reservedCents 99
10
+ // expect Admit
11
+ // scenario a refund (a lifecycle)
12
+ // events submit, approve
13
+ // expect Approved
14
+ //
15
+ // The examples are read from the file's text as written: an example is found even when another part of the file
16
+ // does not compile yet, because a person changing a file is exactly when a tool needs to see its examples.
17
+ // Shape: thunder-examples-v1 (see EXAMPLE below). The syntax read here is stable; a change to it is announced first.
18
+
19
+ import { parseCore } from './core/index.mjs';
20
+ import { fileKind } from './core/kind.mjs';
21
+ import { parseIntent } from './parse.mjs';
22
+
23
+ export const EXAMPLES_SCHEMA = 'thunder-examples-v1';
24
+
25
+ /**
26
+ * One example:
27
+ * { kind: 'expect' | 'case' | 'scenario',
28
+ * block: the Test title, or the decision/lifecycle a mission test is for,
29
+ * name: the case or scenario name (missions), or null,
30
+ * line: the example's line (1-based),
31
+ * subject: { kind: 'function' | 'decision' | 'lifecycle' | 'expression', name },
32
+ * inputs: [{ name: string | null, text }] (Core: in order, unnamed; missions: given name and value; scenario:
33
+ * one input per event, named "event"),
34
+ * expected: { mode: 'equals' | 'compares' | 'fails' | 'result' | 'state' | 'valid' | 'invalid' | 'none',
35
+ * comparison: 'is' | 'is at least' | …, text },
36
+ * raw: the example's own text (Core: its line; missions: its block, joined) }
37
+ */
38
+ export const EXAMPLE = null;
39
+
40
+ const COMPARISON = { '==': 'is', '!=': 'is not', '>=': 'is at least', '<=': 'is at most', '>': 'is more than', '<': 'is less than' };
41
+
42
+ /** Split `a, b and c` into its top-level parts (not inside quotes, brackets, or parentheses). */
43
+ function splitArgs(text) {
44
+ const parts = [];
45
+ let depth = 0, quote = null, cur = '';
46
+ const flush = () => { if (cur.trim()) parts.push(cur.trim()); cur = ''; };
47
+ for (let i = 0; i < text.length; i++) {
48
+ const c = text[i];
49
+ if (quote) { cur += c; if (c === quote && text[i - 1] !== '\\') quote = null; continue; }
50
+ if (c === '"' || c === "'") { quote = c; cur += c; continue; }
51
+ if ('([{'.includes(c)) depth++;
52
+ if (')]}'.includes(c)) depth--;
53
+ if (depth === 0 && c === ',') { flush(); continue; }
54
+ if (depth === 0 && text.startsWith(' and ', i)) { flush(); i += 4; continue; }
55
+ cur += c;
56
+ }
57
+ flush();
58
+ return parts;
59
+ }
60
+
61
+ /** The inputs of `Expect <function> with <inputs> to …`, as the person wrote them, or null when they cannot be cut. */
62
+ function inputsOf(raw, e) {
63
+ const n = e.args?.length ?? 0;
64
+ if (n === 0) return [];
65
+ const m = /^expect\s+(.*?)\s+to\s+(?:be|fail)\b/i.exec(raw);
66
+ if (!m) return null;
67
+ const w = m[1].toLowerCase().indexOf(' with ');
68
+ if (w < 0) return null;
69
+ const parts = splitArgs(m[1].slice(w + 6));
70
+ return parts.length === n ? parts.map((text) => ({ name: null, text })) : null;
71
+ }
72
+
73
+ function coreExamples(source, file) {
74
+ const r = parseCore(source, { file });
75
+ const out = [];
76
+ for (const t of (r.body ?? []).filter((s) => s.k === 'test')) {
77
+ for (const s of t.body ?? []) {
78
+ if (s.k !== 'expect') continue;
79
+ const raw = String(s.raw ?? '').trim();
80
+ const e = s.e ?? {};
81
+ const isCall = e.k === 'call';
82
+ let expected;
83
+ if (s.mode === 'fail') {
84
+ const m = /\bto\s+fail(?:\s+with\s+(.*))?$/i.exec(raw);
85
+ expected = { mode: 'fails', comparison: null, text: m?.[1]?.trim() ?? null };
86
+ } else {
87
+ const op = s.check?.op ?? '==';
88
+ const comparison = COMPARISON[op] ?? op;
89
+ const m = /\bto\s+be\s+(.*)$/i.exec(raw);
90
+ let text = m?.[1]?.trim() ?? null;
91
+ if (text && op !== '==') text = text.replace(/^(?:at least|at most|more than|less than|above|below|fewer than|greater than|not)\s+/i, '');
92
+ expected = { mode: op === '==' ? 'equals' : 'compares', comparison, text };
93
+ }
94
+ out.push({
95
+ kind: 'expect', block: t.title ?? null, name: null, line: s.line,
96
+ subject: isCall ? { kind: 'function', name: e.text ?? e.name } : { kind: 'expression', name: null },
97
+ inputs: isCall ? inputsOf(raw, e) ?? [] : [],
98
+ ...(isCall && inputsOf(raw, e) == null && (e.args?.length ?? 0) > 0 ? { inputsUnread: true } : {}),
99
+ expected, raw,
100
+ });
101
+ }
102
+ }
103
+ // Expect lines the parser could not place (a test file that calls functions defined in another file, or a line
104
+ // that does not parse yet) are read from their text, and say so (fromText).
105
+ const seen = new Set(out.map((e) => e.line));
106
+ const lines = String(source).split('\n');
107
+ let block = null;
108
+ lines.forEach((line, i) => {
109
+ const t = /^test\s+"([^"]*)"\s*:\s*$/i.exec(line);
110
+ if (t) { block = t[1]; return; }
111
+ if (line.trim() && !/^\s/.test(line)) { block = null; return; }
112
+ const m = block != null && /^\s+expect\s+(.+?)\s+to\s+(be|fail)\b\s*(.*)$/i.exec(line);
113
+ if (!m || seen.has(i + 1)) return;
114
+ const [, what, verb, tail] = m;
115
+ const w = what.toLowerCase().indexOf(' with ');
116
+ const name = w >= 0 ? what.slice(0, w).trim() : null;
117
+ let expected;
118
+ if (verb.toLowerCase() === 'fail') expected = { mode: 'fails', comparison: null, text: (/^with\s+(.*)$/i.exec(tail)?.[1] ?? '').trim() || null };
119
+ else {
120
+ const c = /^(at least|at most|more than|less than|not)\s+(.*)$/i.exec(tail);
121
+ expected = c ? { mode: 'compares', comparison: `is ${c[1].toLowerCase()}`, text: c[2].trim() } : { mode: 'equals', comparison: 'is', text: tail.trim() || null };
122
+ }
123
+ out.push({
124
+ kind: 'expect', block, name: null, line: i + 1,
125
+ subject: name ? { kind: 'function', name } : { kind: 'expression', name: null },
126
+ inputs: name ? splitArgs(what.slice(w + 6)).map((text) => ({ name: null, text })) : [],
127
+ expected, raw: line.trim(), fromText: true,
128
+ });
129
+ });
130
+ out.sort((a, b) => a.line - b.line);
131
+ return { examples: out, problems: (r.diagnostics ?? []).filter((d) => d.severity !== 'warning').length };
132
+ }
133
+
134
+ function missionExamples(source) {
135
+ const ast = parseIntent(source);
136
+ const lifecycles = new Set((ast.lifecycles ?? []).map((l) => l.name));
137
+ const lines = source.split('\n');
138
+ const blockText = (line) => {
139
+ // The case's own lines: its header and the lines indented under it.
140
+ const start = line - 1;
141
+ const ind = (lines[start] ?? '').match(/^\s*/)[0].length;
142
+ const out = [lines[start]?.trim() ?? ''];
143
+ for (let i = start + 1; i < lines.length && (lines[i].trim() === '' || lines[i].match(/^\s*/)[0].length > ind); i++) if (lines[i].trim()) out.push(lines[i].trim());
144
+ return out.join('\n');
145
+ };
146
+ const out = [];
147
+ for (const t of ast.tests ?? []) {
148
+ const isLifecycle = lifecycles.has(t.name);
149
+ for (const c of t.cases ?? []) {
150
+ const scenario = Array.isArray(c.events);
151
+ const expected = c.expectValid === true ? { mode: 'valid', comparison: null, text: null }
152
+ : c.expectValid === false ? { mode: 'invalid', comparison: null, text: null }
153
+ : c.expect != null ? { mode: scenario ? 'state' : 'result', comparison: 'is', text: c.expect }
154
+ : { mode: 'none', comparison: null, text: null };
155
+ out.push({
156
+ kind: scenario ? 'scenario' : 'case', block: t.name, name: c.name, line: c.line,
157
+ subject: { kind: scenario || isLifecycle ? 'lifecycle' : 'decision', name: t.name },
158
+ inputs: scenario ? c.events.map((ev) => ({ name: 'event', text: ev })) : Object.entries(c.given ?? {}).map(([name, text]) => ({ name, text })),
159
+ expected, raw: blockText(c.line),
160
+ });
161
+ }
162
+ }
163
+ return { examples: out, problems: 0 };
164
+ }
165
+
166
+ /**
167
+ * Every example in `source`: { schema, kind: 'program' | 'mission', examples, problems }. `kind` is decided the way
168
+ * the compiler decides it (a file's first line), unless given ({ kind: 'program' } for a file in a Core project).
169
+ * `problems` counts errors elsewhere in a program; the examples are read anyway.
170
+ */
171
+ export function examplesOf(source, { file = 'main.thunder', kind = null } = {}) {
172
+ const k = kind ?? fileKind(String(source)).kind;
173
+ const r = k === 'program' ? coreExamples(String(source), file) : missionExamples(String(source));
174
+ return { schema: EXAMPLES_SCHEMA, kind: k, ...r };
175
+ }
package/src/index.d.ts CHANGED
@@ -464,6 +464,11 @@ export function runTests(ast: IntentAst): TestReport;
464
464
  export interface ObligationResolution {
465
465
  kind: 'guarantee' | 'prohibition'; id?: string; text: string;
466
466
  status: 'verified' | 'failed' | 'declared' | 'unverified';
467
+ /** The evidence word's key (docs/evidence-words.md): passing named cases are 'tested', a failed one 'violated'. */
468
+ evidenceLevel: 'tested' | 'partial' | 'unverified' | 'violated';
469
+ /** "Tested", "Partially checked", "Unverified", or "Violated". */
470
+ evidenceWord: string;
471
+ /** The names of the tests that ran for it (passed or failed). A name kept for compatibility: a passing test is Tested evidence, not a proof. */
467
472
  verify: string[]; kinds: string[]; provenBy: string | null;
468
473
  evidence: Array<{ name: string; pass: boolean | null; cases: number }>;
469
474
  unresolved: string[];
@@ -471,7 +476,15 @@ export interface ObligationResolution {
471
476
  export function resolveObligations(ast: IntentAst): {
472
477
  obligations: ObligationResolution[]; tests: TestReport;
473
478
  verified: number; failed: number; declared: number; unverified: number;
479
+ evidence: { tested: number; partial: number; unverified: number; violated: number };
474
480
  };
481
+ export const CLAIM_STATUS: { verified: 'verified'; failed: 'failed'; declared: 'planned'; unverified: 'needs_verification' };
482
+ export function claimStatus(status: string): 'verified' | 'failed' | 'planned' | 'needs_verification';
483
+ export const EVIDENCE_LEVELS: Array<'proven' | 'tested' | 'partial' | 'unverified' | 'violated'>;
484
+ export const EVIDENCE_WORDS: Record<'proven' | 'tested' | 'partial' | 'unverified' | 'violated', { word: string; means: string }>;
485
+ export function evidenceWord(level: string): string | null;
486
+ export function evidenceMeaning(level: string): string | null;
487
+ export function combineEvidence(levels: Iterable<string>): 'proven' | 'tested' | 'partial' | 'unverified' | 'violated';
475
488
 
476
489
  // Outcome contracts (executable commitments)
477
490
  export const OUTCOME_SCHEMA: string;
@@ -762,6 +775,12 @@ export type { Promotion } from './promote.mjs';
762
775
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
763
776
  export type { ChangedCase, ChangedCases, WriteChange, RulePart } from './write.mjs';
764
777
  export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from './write-steps.mjs';
778
+ export { examplesOf, EXAMPLES_SCHEMA } from './examples.mjs';
779
+ export { templateOf, TEMPLATE_SCHEMA } from './template.mjs';
780
+ export { symbolAt, definitionsAt, referencesAt, renameAt, applyRename } from './symbols.mjs';
781
+ export { coreChanges, affectedBy, CORE_CHANGES_SCHEMA, AFFECTED_SCHEMA } from './core-changes.mjs';
782
+ export { withCoreBehaviour } from './core-changes.mjs';
783
+ export { coreServiceFacts } from './core-services.mjs';
765
784
  export type { ThunderEdit, ThunderWriteResult, WriteProof } from './write-steps.mjs';
766
785
  export { buildPassport, checkPassportOnDisk, accessEvidence } from './passport-fs.mjs';
767
786
  export { PASSPORT_SCHEMA, assemblePassport, checkPassport, renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
package/src/index.mjs CHANGED
@@ -189,7 +189,8 @@ export { startLspServer } from "./lsp.mjs";
189
189
  // Formatter , canonical .intent formatting (whitespace only)
190
190
  export { formatSource, isFormatted } from "./format.mjs";
191
191
 
192
- export { resolveObligations } from './obligations.mjs';
192
+ export { resolveObligations, CLAIM_STATUS, claimStatus } from './obligations.mjs';
193
+ export { EVIDENCE_LEVELS, EVIDENCE_WORDS, evidenceWord, evidenceMeaning, combineEvidence } from './evidence-words.mjs';
193
194
  // Read code you don't know: one file, a whole repository, files from disk, and promotion of a recovered decision
194
195
  // into a contract with edge-case examples.
195
196
  export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES } from "./read.mjs";
@@ -207,6 +208,12 @@ export { promoteDecision, PROMOTE_SCHEMA } from "./promote.mjs";
207
208
  // Thunder write: change a recovered rule and write exactly those characters back, verified by re-reading.
208
209
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from "./write.mjs";
209
210
  export { WRITE_STEPS_SCHEMA, WRITE_STEPS_LANGUAGES, EDIT_OPS, thunderWrite, proveChange, describeEdit, unifiedDiff } from "./write-steps.mjs";
211
+ export { examplesOf, EXAMPLES_SCHEMA } from "./examples.mjs";
212
+ export { templateOf, TEMPLATE_SCHEMA } from "./template.mjs";
213
+ export { symbolAt, definitionsAt, referencesAt, renameAt, applyRename } from "./symbols.mjs";
214
+ export { coreChanges, affectedBy, CORE_CHANGES_SCHEMA, AFFECTED_SCHEMA } from "./core-changes.mjs";
215
+ export { withCoreBehaviour } from "./core-changes.mjs";
216
+ export { coreServiceFacts } from "./core-services.mjs";
210
217
  // The Thunder Software Passport (docs/passport.md): build one from folders (git, runs) and check it on disk.
211
218
  export { buildPassport, checkPassportOnDisk, accessEvidence } from './passport-fs.mjs';
212
219
  export { PASSPORT_SCHEMA, assemblePassport, checkPassport, renderPassportSummary, renderPassportMarkdown } from './passport.mjs';
@@ -837,7 +837,7 @@ export const WRITE_LESSONS = [
837
837
  explain: "Only the web tests depended on shipping.ts. Billing's claim depended on receipt.py, which did not change, so it stays current. Nothing is re-run: check compares fingerprints.",
838
838
  check: ({ passportCheck }) => { const c = passportCheck({ 'web/shipping.ts': SHIP_WEB.replace('50', '45') }); const stale = c.items.filter((i) => i.freshness === 'stale'); return stale.length === 2 ? 'Both' : /in web/.test(stale[0]?.claim) ? 'The web test run' : 'The billing test run'; } },
839
839
  { prompt: "Every test passed. Does the passport say the change works in production?", choices: ["No: deployment is always listed as not verified", "Yes"], expect: "No: deployment is always listed as not verified",
840
- explain: "Tests prove what they ran, on the machine they ran on. How it is deployed, real outside services, more than one machine, and heavy load are listed as not verified unless a claim covers them.",
840
+ explain: "Tests show what they ran, on the machine they ran on. How it is deployed, real outside services, more than one machine, and heavy load are listed as not verified unless a claim covers them.",
841
841
  check: ({ passport }) => (passport.unknowns.notVerified.some((x) => /^Deployment/.test(x)) ? 'No: deployment is always listed as not verified' : 'Yes') },
842
842
  ],
843
843
  questions: [