@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
package/src/lsp.mjs CHANGED
@@ -2,11 +2,61 @@
2
2
  // diagnostics + IntelliSense so ANY LSP-capable editor (VS Code, Neovim, Helix, ...) gets
3
3
  // live ThunderLang intelligence: diagnostics on open/change, keyword/type completions, and
4
4
  // hover docs for semantic types and note lenses. Deterministic; no AI. `thunder lsp` starts it.
5
+ //
6
+ // Go to definition, find references, and rename (src/symbols.mjs) work in Thunder Core programs and missions. For
7
+ // a Core program in a project (a folder with thunder.toml), every .thunder file of the project is read, with the
8
+ // editor's unsaved text in place of what is on disk, so a function's references include its tests. Core programs
9
+ // get the Core compiler's diagnostics, at their own lines; missions keep the mission checks.
5
10
 
6
11
  import { parseIntent } from './parse.mjs';
7
12
  import { semanticDiagnostics } from './emit.mjs';
8
13
  import { getCompletions, getHover } from './intellisense.mjs';
9
14
  import { COMPILER_VERSION } from './emit.mjs';
15
+ import { symbolIndex, symbolAt, renameAt } from './symbols.mjs';
16
+ import { fileKind } from './core/kind.mjs';
17
+ import { findProjectRoot } from './core/project-root.mjs';
18
+ import { coreFilesIn } from './core-changes-fs.mjs';
19
+ import { fileURLToPath, pathToFileURL } from 'node:url';
20
+ import { relative, join, basename, sep } from 'node:path';
21
+
22
+ const isCoreText = (uri, text) => /\.thunder$/i.test(uri) && fileKind(text).kind === 'program';
23
+ const pathOf = (uri) => { try { return fileURLToPath(uri); } catch { return null; } };
24
+
25
+ /**
26
+ * The files a request about `uri` needs: for a Core program in a project, every .thunder file of the project
27
+ * (open documents in place of their saved text); otherwise the document alone. Paths are relative to `base`.
28
+ */
29
+ function workspaceFor(uri, docs) {
30
+ const text = docs.get(uri) ?? '';
31
+ const file = pathOf(uri);
32
+ const root = file && isCoreText(uri, text) ? findProjectRoot(file) : null;
33
+ if (!root) {
34
+ const path = file ? basename(file) : uri;
35
+ return { files: [{ path, source: text }], path, uriOf: (p) => (p === path ? uri : null) };
36
+ }
37
+ const open = new Map([...docs].map(([u, t]) => [pathOf(u), t]).filter(([p]) => p));
38
+ let files = [];
39
+ try { files = coreFilesIn(root, root); } catch { files = []; }
40
+ files = files.map((f) => ({ ...f, source: open.get(join(root, f.path)) ?? f.source }));
41
+ const path = relative(root, file).split(sep).join('/');
42
+ if (!files.some((f) => f.path === path)) files.push({ path, source: text });
43
+ return { files, path, uriOf: (p) => pathToFileURL(join(root, p)).href };
44
+ }
45
+
46
+ const range = (o) => ({ start: { line: o.line - 1, character: o.col - 1 }, end: { line: o.line - 1, character: o.col - 1 + o.length } });
47
+
48
+ function toCoreDiagnostic(d, lines) {
49
+ const line = Math.max(0, (d.line ?? 1) - 1);
50
+ const text = lines[line] ?? '';
51
+ const start = d.hole?.col ? d.hole.col - 1 : Math.max(0, text.length - text.trimStart().length);
52
+ return {
53
+ range: { start: { line, character: start }, end: { line, character: Math.max(start + 1, text.length) } },
54
+ severity: d.severity === 'warning' ? 2 : 1,
55
+ code: d.code,
56
+ source: 'thunder',
57
+ message: d.message + (d.hint ? `\n\n${d.hint}` : ''),
58
+ };
59
+ }
10
60
 
11
61
  // LSP CompletionItemKind numbers for the kinds IntelliSense returns.
12
62
  const COMPLETION_KIND = { keyword: 14, semantic_type: 7, field: 5, snippet: 15, value: 12, block: 14 };
@@ -68,10 +118,22 @@ export function startLspServer({ readable = process.stdin, writable = process.st
68
118
  writable.write(payload);
69
119
  };
70
120
  const respond = (id, result) => send({ jsonrpc: '2.0', id, result });
121
+ // A request Thunder answers with a reason instead of a result (a rename it refuses): the editor shows the message.
122
+ const refuse = (id, message) => send({ jsonrpc: '2.0', id, error: { code: -32803, message } });
71
123
  const notify = (method, params) => send({ jsonrpc: '2.0', method, params });
72
124
 
73
125
  const publish = (uri) => {
74
126
  const lines = (docs.get(uri) || '').split('\n');
127
+ if (isCoreText(uri, docs.get(uri) || '')) {
128
+ let diags = [];
129
+ try {
130
+ const w = workspaceFor(uri, docs);
131
+ const r = symbolIndex(w.files).results.find((x) => x.path === w.path);
132
+ diags = (r?.diagnostics ?? []).map((d) => toCoreDiagnostic(d, lines));
133
+ } catch { diags = []; }
134
+ notify('textDocument/publishDiagnostics', { uri, diagnostics: diags });
135
+ return;
136
+ }
75
137
  let diags;
76
138
  try { diags = semanticDiagnostics(parseIntent(docs.get(uri) || '')); } catch { diags = []; }
77
139
  notify('textDocument/publishDiagnostics', { uri, diagnostics: diags.map((d) => toLspDiagnostic(d, lines)) });
@@ -85,6 +147,9 @@ export function startLspServer({ readable = process.stdin, writable = process.st
85
147
  textDocumentSync: 1, // full document sync
86
148
  completionProvider: { triggerCharacters: [' '] },
87
149
  hoverProvider: true,
150
+ definitionProvider: true,
151
+ referencesProvider: true,
152
+ renameProvider: { prepareProvider: true },
88
153
  },
89
154
  serverInfo: { name: 'thunderlang-lsp', version: COMPILER_VERSION },
90
155
  });
@@ -126,6 +191,51 @@ export function startLspServer({ readable = process.stdin, writable = process.st
126
191
  respond(msg.id, hover);
127
192
  break;
128
193
  }
194
+ case 'textDocument/definition':
195
+ case 'textDocument/references': {
196
+ const uri = msg.params.textDocument.uri;
197
+ const p = msg.params.position;
198
+ let out = [];
199
+ try {
200
+ const w = workspaceFor(uri, docs);
201
+ const s = symbolAt(w.files, w.path, { line: p.line + 1, col: p.character + 1 });
202
+ const list = !s ? [] : msg.method === 'textDocument/definition' ? s.definitions
203
+ : s.references.filter((o) => msg.params.context?.includeDeclaration !== false || !o.def);
204
+ out = list.map((o) => ({ uri: w.uriOf(o.path), range: range(o) })).filter((l) => l.uri);
205
+ } catch { out = []; }
206
+ respond(msg.id, out);
207
+ break;
208
+ }
209
+ case 'textDocument/prepareRename': {
210
+ const uri = msg.params.textDocument.uri;
211
+ const p = msg.params.position;
212
+ try {
213
+ const w = workspaceFor(uri, docs);
214
+ const s = symbolAt(w.files, w.path, { line: p.line + 1, col: p.character + 1 });
215
+ if (!s) { refuse(msg.id, 'There is no name here that Thunder can rename: put the cursor on a function, data type, alternative, value, or input (in a mission: a decision, rule, field, or other named block).'); break; }
216
+ const endpoint = s.references.find((o) => o.endpoint)?.endpoint;
217
+ if (endpoint) { refuse(msg.id, `${s.at.written} is what callers send to ${endpoint}, so renaming it here would change the API.`); break; }
218
+ respond(msg.id, { range: range(s.at), placeholder: s.at.written });
219
+ } catch { respond(msg.id, null); }
220
+ break;
221
+ }
222
+ case 'textDocument/rename': {
223
+ const uri = msg.params.textDocument.uri;
224
+ const p = msg.params.position;
225
+ try {
226
+ const w = workspaceFor(uri, docs);
227
+ const r = renameAt(w.files, w.path, { line: p.line + 1, col: p.character + 1 }, msg.params.newName);
228
+ if (!r.ok) { refuse(msg.id, r.problem); break; }
229
+ const changes = {};
230
+ for (const e of r.edits) {
231
+ const u = w.uriOf(e.path);
232
+ if (!u) continue;
233
+ (changes[u] ??= []).push({ range: range(e), newText: e.newText });
234
+ }
235
+ respond(msg.id, { changes });
236
+ } catch (e) { refuse(msg.id, `Thunder could not rename this: ${e.message}`); }
237
+ break;
238
+ }
129
239
  default:
130
240
  if (msg.id != null) respond(msg.id, null); // unknown request -> empty result, keep alive
131
241
  }
package/src/mcp.mjs CHANGED
@@ -16,12 +16,14 @@ import { sha256 } from './hash.mjs';
16
16
  import { verifyDiff } from './verify-diff.mjs';
17
17
  import { liftSource, SUPPORTED_LANGUAGES } from './lift.mjs';
18
18
  import { runTests } from './testing.mjs';
19
- import { resolveObligations } from './obligations.mjs';
19
+ import { resolveObligations, foldObligations } from './obligations.mjs';
20
20
  import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
21
21
  import { evaluateDecision } from './runtime.mjs';
22
22
  import { buildTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
23
+ import { coreChanges, affectedBy, withCoreBehaviour } from './core-changes.mjs';
24
+ import { coreFilesIn } from './core-changes-fs.mjs';
23
25
  import { thunderWrite } from './write-steps.mjs';
24
- import { readRepoDir, gitChanges } from './trace-fs.mjs';
26
+ import { readRepoDir, gitChanges, coreBehaviourOf } from './trace-fs.mjs';
25
27
  import { buildIntentGraph } from './intent-graph.mjs';
26
28
  import { buildConformance } from './conformance.mjs';
27
29
  import { checkDrift } from './drift.mjs';
@@ -92,7 +94,7 @@ const TOOLS = [
92
94
  },
93
95
  {
94
96
  name: 'intent_verify_diff',
95
- description: 'THE AI-LOOP GATE. Prove, deterministically, which of an intent\'s guarantees and never-rules a code change upholds or breaks. Returns verdict PASS or BLOCK. Blocks on regressions (a claim that held on `before` and broke on `after`) and guardrail hits (an added line pushing a protected secret into a log/response). Call this on your own proposed change before shipping it.',
97
+ description: 'THE AI-LOOP GATE. Check, deterministically, which of an intent\'s guarantees and never-rules a code change upholds or breaks, by matching patterns in the code (a check, not a proof; tests and people still own correctness). Returns verdict PASS or BLOCK. Blocks on regressions (a claim that held on `before` and broke on `after`) and guardrail hits (an added line pushing a protected secret into a log/response). Call this on your own proposed change before shipping it.',
96
98
  inputSchema: {
97
99
  type: 'object', required: ['intent', 'after'],
98
100
  properties: {
@@ -106,7 +108,7 @@ const TOOLS = [
106
108
  },
107
109
  {
108
110
  name: 'intent_prove',
109
- description: 'Emit the durable intent-proof-v1 artifact for .intent source: per-claim verdicts (verified / failed / planned / needs_verification, each bound to the named test that proves it) plus the freshness tuple (intent hash, compiler version, commit, dependency lockfile) that lets `thunder verify` mark the proof STALE later. Mirrors `thunder prove`; an unverified claim never reads as passed. Call it after the gate passes to record WHAT was proven.',
111
+ description: 'Emit the durable intent-proof-v1 artifact for .intent source: per-claim verdicts (verified / failed / planned / needs_verification, each bound to the named test that checks it, with its evidence word: Tested, Partially checked, Unverified, or Violated) plus the freshness tuple (intent hash, compiler version, commit, dependency lockfile) that lets `thunder verify` mark the proof STALE later. Mirrors `thunder prove`; an unverified claim never reads as passed. Call it after the gate passes to record what was checked, and how.',
110
112
  inputSchema: {
111
113
  type: 'object', required: ['source'],
112
114
  properties: {
@@ -129,11 +131,7 @@ const TOOLS = [
129
131
  generatedAt: new Date().toISOString(),
130
132
  });
131
133
  // Fold per-claim verdicts into the proof so it records real status, not just planned/needs_verification.
132
- const CLAIM_MAP = { verified: 'verified', failed: 'failed', declared: 'planned', unverified: 'needs_verification' };
133
- const byId = new Map(resolved.obligations.map((o) => [o.id, o]));
134
- const applyStatus = (claim) => { const o = byId.get(claim.id); return o ? { ...claim, status: CLAIM_MAP[o.status], provenBy: o.provenBy || null } : claim; };
135
- proof.guarantees = proof.guarantees.map(applyStatus);
136
- proof.neverRules = proof.neverRules.map(applyStatus);
134
+ foldObligations(proof, resolved);
137
135
  proof.freshness = proofFreshness(proof, environment);
138
136
  const ok = proof.verification.semanticPassed && resolved.tests.ok !== false && resolved.failed === 0;
139
137
  return { ok, proofId: `proof-${proof.sourceHash.replace('sha256:', '').slice(0, 6)}`, ...proof, tests: resolved.tests };
@@ -205,7 +203,7 @@ const TOOLS = [
205
203
  },
206
204
  {
207
205
  name: 'intent_test',
208
- description: 'Run the in-file test blocks (case/scenario) in .intent source through the deterministic runtime. The spec proves itself.',
206
+ description: 'Run the in-file test blocks (case/scenario) in .intent source through the deterministic runtime. A passing case is Tested evidence for its own inputs, not a proof of every input.',
209
207
  inputSchema: { type: 'object', required: ['source'], properties: { source: str } },
210
208
  run: ({ source }) => runTests(parseIntent(String(source))),
211
209
  },
@@ -267,7 +265,7 @@ const TOOLS = [
267
265
  },
268
266
  {
269
267
  name: 'intent_trace',
270
- description: 'ASK THUNDER TRACE BEFORE CHANGING CODE THAT OTHER REPOSITORIES USE (local only). Give the repository folders. With "thing" (a route like "POST /api/orders", an event name, "table:orders", "setting:ORDERS_URL", "package:@acme/client", or "repo:file[:line]") or "diff": true (the branch and uncommitted changes), it answers what the change can affect in the OTHER repositories: callers of a changed or removed route, listeners of a published event, code that uses a changed, dropped, or removed table, other readers of a setting, dependents of a published package, ranked high/medium/low, one hop out, every item cited repo@sha:file:line. With neither, it gives the links between the repositories (HTTP, events, tables, packages) and what they share (settings, tables, package versions that differ). Read from code; nothing is run; a call whose address is worked out when it runs is listed as not linked, never guessed.',
268
+ description: 'ASK THUNDER TRACE BEFORE CHANGING CODE THAT OTHER REPOSITORIES USE (local only). Give the repository folders. With "thing" (a route like "POST /api/orders", an event name, "table:orders", "setting:ORDERS_URL", "package:@acme/client", or "repo:file[:line]") or "diff": true (the branch and uncommitted changes), it answers what the change can affect in the OTHER repositories: callers of a changed or removed route (for a Thunder Core endpoint, also when a rule it uses changed, with what changes in its answers: diff runs both versions on the Thunder engine), listeners of a published event, code that uses a changed, dropped, or removed table, other readers of a setting, dependents of a published package, ranked high/medium/low, one hop out, every item cited repo@sha:file:line. With neither, it gives the links between the repositories (HTTP, events, tables, packages) and what they share (settings, tables, package versions that differ). Read from code; nothing is run, apart from changed Thunder Core programs with diff (on the Thunder engine: no files, network, or saved data); a call whose address is worked out when it runs is listed as not linked, never guessed.',
271
269
  inputSchema: {
272
270
  type: 'object', required: ['paths'],
273
271
  properties: {
@@ -282,10 +280,47 @@ const TOOLS = [
282
280
  const repos = paths.map((p) => readRepoDir(resolve(String(p))));
283
281
  const trace = buildTrace(repos);
284
282
  if (!thing && !diff) return { trace };
285
- const r = thing ? traceImpactOf(trace, String(thing)) : traceImpact(trace, repos.flatMap((repo) => gitChanges(repo, base).changes));
283
+ if (thing) { const r = traceImpactOf(trace, String(thing)); return { ...r, text: renderImpact(r) }; }
284
+ // With diff, a changed Thunder Core program is also run before and after, to say what changes in its answers.
285
+ const changes = [], behaviour = new Map();
286
+ for (const repo of repos) {
287
+ const g = gitChanges(repo, base);
288
+ changes.push(...g.changes);
289
+ const cc = g.base ? coreBehaviourOf(repo, g) : null;
290
+ if (cc) behaviour.set(repo.name, cc);
291
+ }
292
+ const r = withCoreBehaviour(traceImpact(trace, changes), behaviour);
286
293
  return { ...r, text: renderImpact(r) };
287
294
  },
288
295
  },
296
+ {
297
+ name: 'intent_core_changes',
298
+ description: 'WHAT A CHANGE TO A THUNDER CORE PROGRAM DOES, RULE BY RULE (runs the program). Give both versions of the .thunder files ({ path, source }; include the project\'s tests). Each rule is paired with its other version by a stable name from what it is ("function:decide refund", "keep:review limit", "endpoint:POST /orders", "never:Product: Never allow a negative stock", "test:…"), never by line. A function whose steps changed, or that uses something that changed, is run before and after on the same inputs (made from the numbers and text in both versions, each number with one step either side) and the answers that differ are grouped, with the input that decides them as the range tried: "now a review Refund instead of an approved Refund when amount is from $50.00 to $99.99". Tests that reach a change are run before and after. Each change lists what to look at again (affects). Tested evidence on the inputs tried, not a proof; functions that read saved data or call another service are not run, and say so.',
299
+ inputSchema: {
300
+ type: 'object', required: ['before', 'after'],
301
+ properties: {
302
+ before: { type: 'array', maxItems: 500, items: { type: 'object', required: ['path', 'source'], properties: { path: str, source: str } } },
303
+ after: { type: 'array', maxItems: 500, items: { type: 'object', required: ['path', 'source'], properties: { path: str, source: str } } },
304
+ },
305
+ },
306
+ run: ({ before, after }) => coreChanges(before ?? [], after ?? []),
307
+ },
308
+ {
309
+ name: 'intent_affected',
310
+ description: 'WHAT TO LOOK AT AGAIN WHEN A THUNDER CORE RULE CHANGES (read only, nothing is run). Give a Thunder project folder or file (path) or the files themselves, and what changes: a rule\'s name or id ("decide refund", "review limit", "POST /orders", "keep:review limit"), or a list. Answers the functions and endpoints that use it (all the way up, each with the rules in between), the tests and the Expect examples that reach it, and the Never rules and stored lists they rely on, each cited file:line.',
311
+ inputSchema: {
312
+ type: 'object', required: ['change'],
313
+ properties: {
314
+ path: { ...str, description: 'a Thunder project folder or .thunder file' },
315
+ files: { type: 'array', maxItems: 500, items: { type: 'object', required: ['path', 'source'], properties: { path: str, source: str } } },
316
+ change: { description: 'a rule name or id, or a list of them', anyOf: [str, { type: 'array', items: str }] },
317
+ },
318
+ },
319
+ run: ({ path, files, change }) => {
320
+ if (!path && !files) throw new Error('Give a Thunder project folder or file in "path", or the files in "files".');
321
+ return affectedBy(files ?? coreFilesIn(resolve(String(path))), change);
322
+ },
323
+ },
289
324
  {
290
325
  name: 'intent_write',
291
326
  description: 'CHANGE CODE THROUGH THUNDER, WITH PROOF (TypeScript, JavaScript, Python, Go). Give the files ({ path, source }) and one or more Thunder edits; get back a minimal patch, the new file contents, and a proof: the edited function now reads exactly as the edit says, and every other function means the same. Edits: setValue (to, or toValue in Thunder words), setCondition (when: "amount is at least 100 and not member"), addStep / removeStep / moveStep (step: code, "Give …", "Set … to …", "Stop with \"…\"", or { if, then, else }), addStop (when, message), removeStop, addInput (name, default), removeInput, setGivesBack (value), rename. Each edit names its function (member: "name" or { file, name, line }) and its step by the line thunder read shows ("line:12"); lines are the original file\'s lines for every edit in the list. Status is written, refused (with why), or needs-ai (with an instruction for a coding agent). Nothing is written to disk: apply the returned files, then run the project\'s tests. behaviour: true (Python only) also RUNS each edited function before and after on inputs made from its code and lists the inputs whose answer changed: tested evidence on those inputs, not a proof.',
@@ -6,4 +6,9 @@ export function resolveObligations(ast: unknown): {
6
6
  declared: number;
7
7
  unverified: number;
8
8
  failed: number;
9
+ evidence: { tested: number; partial: number; unverified: number; violated: number };
9
10
  };
11
+ export const CLAIM_STATUS: Record<string, string>;
12
+ export function claimStatus(status: string): 'verified' | 'failed' | 'planned' | 'needs_verification';
13
+ /** Fold resolved obligations into an intent-proof-v1 artifact, in place: status, provenBy, evidenceLevel, evidenceWord per claim. */
14
+ export function foldObligations<P>(proof: P, resolved: ReturnType<typeof resolveObligations>): P;
@@ -1,4 +1,27 @@
1
1
  import { runTests } from './testing.mjs';
2
+ import { combineEvidence, evidenceWord } from './evidence-words.mjs';
3
+
4
+ /** The intent-proof-v1 claim status for an obligation status: one table for the CLI, MCP, and the website. */
5
+ export const CLAIM_STATUS = { verified: 'verified', failed: 'failed', declared: 'planned', unverified: 'needs_verification' };
6
+ export const claimStatus = (status) => CLAIM_STATUS[status] ?? 'needs_verification';
7
+
8
+ /**
9
+ * Fold resolved obligations into an intent-proof-v1 artifact (in place): each claim gets its real status, the names
10
+ * of the tests that ran for it, and its evidence word. Claims are matched by id, then by order.
11
+ */
12
+ export function foldObligations(proof, resolved) {
13
+ const byId = new Map(resolved.obligations.filter((o) => o.id).map((o) => [o.id, o]));
14
+ const fold = (claims, kind) => {
15
+ const ofKind = resolved.obligations.filter((o) => o.kind === kind);
16
+ return claims.map((claim, i) => {
17
+ const o = (claim.id && byId.get(claim.id)) || ofKind[i];
18
+ return o ? { ...claim, status: claimStatus(o.status), provenBy: o.provenBy || null, evidenceLevel: o.evidenceLevel, evidenceWord: o.evidenceWord } : claim;
19
+ });
20
+ };
21
+ proof.guarantees = fold(proof.guarantees, 'guarantee');
22
+ proof.neverRules = fold(proof.neverRules, 'prohibition');
23
+ return proof;
24
+ }
2
25
 
3
26
  // One binding policy for CLI, MCP, website, and embedding products. A reference
4
27
  // names a complete test target, not a substring, prose description, or similar name.
@@ -19,8 +42,11 @@ export function resolveObligations(ast) {
19
42
  const status = !names.length ? 'unverified'
20
43
  : evidence.some((e) => e.pass === false) ? 'failed'
21
44
  : unresolved.length ? 'declared' : 'verified';
45
+ // The evidence word (src/evidence-words.mjs): passing named cases are Tested, never Proven; a failed one is
46
+ // Violated; some named cases that ran and some that can't run here is Partially checked.
47
+ const evidenceLevel = combineEvidence(evidence.map((e) => (e.pass === true ? 'tested' : e.pass === false ? 'violated' : 'unverified')));
22
48
  return {
23
- kind, id: claim.id, text: claim.statement, status, verify,
49
+ kind, id: claim.id, text: claim.statement, status, evidenceLevel, evidenceWord: evidenceWord(evidenceLevel), verify,
24
50
  kinds: [...new Set((claim.verifications || []).map((v) => v.kind).filter((k) => k && k !== 'unclassified'))],
25
51
  provenBy: status === 'verified' || status === 'failed' ? evidence.filter((e) => e.pass !== null).map((e) => e.name).join(', ') : null,
26
52
  evidence, unresolved,
@@ -31,5 +57,7 @@ export function resolveObligations(ast) {
31
57
  ...(ast.neverRules || []).map((n) => build('prohibition', n)),
32
58
  ];
33
59
  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') };
60
+ const byLevel = (l) => obligations.filter((o) => o.evidenceLevel === l).length;
61
+ return { obligations, tests, verified: count('verified'), declared: count('declared'), unverified: count('unverified'), failed: count('failed'),
62
+ evidence: { tested: byLevel('tested'), partial: byLevel('partial'), unverified: byLevel('unverified'), violated: byLevel('violated') } };
35
63
  }
package/src/program.d.mts CHANGED
@@ -29,3 +29,10 @@ export function toRust(program: unknown, info: unknown, options?: { source?: str
29
29
  export function toReact(program: unknown, info: unknown, options?: { source?: string }): string;
30
30
  export function hasScreens(info: unknown): boolean;
31
31
  export function pythonToCore(source: string): { core: string; functions: Array<{ name: string; exact: boolean }>; [k: string]: unknown };
32
+ export { examplesOf, EXAMPLES_SCHEMA, type ThunderExample, type ThunderExamples } from './examples.mjs';
33
+ export { templateOf, TEMPLATE_SCHEMA, type ThunderTemplate, type ThunderTemplateField, type ThunderTemplateMissing } from './template.mjs';
34
+ export { EVIDENCE_LEVELS, EVIDENCE_WORDS, evidenceWord, evidenceMeaning, combineEvidence } from './evidence-words.mjs';
35
+ export { symbolAt, definitionsAt, referencesAt, renameAt, applyRename, type ThunderFile, type ThunderLocation, type ThunderSymbol, type ThunderRename } from './symbols.mjs';
36
+ export { coreChanges, affectedBy, CORE_CHANGES_SCHEMA, AFFECTED_SCHEMA, type CoreChanges, type CoreChange, type Affected } from './core-changes.mjs';
37
+ export { withCoreBehaviour } from './core-changes.mjs';
38
+ export { coreServiceFacts } from './core-services.mjs';
package/src/program.mjs CHANGED
@@ -12,3 +12,10 @@ export { toGo, goNamespaces } from './core/target-go.mjs';
12
12
  export { toRust } from './core/target-rust.mjs';
13
13
  export { toReact, hasScreens } from './core/target-react.mjs';
14
14
  export { pythonToCore } from './core/from-python.mjs';
15
+ export { examplesOf, EXAMPLES_SCHEMA } from './examples.mjs';
16
+ export { templateOf, TEMPLATE_SCHEMA } from './template.mjs';
17
+ export { EVIDENCE_LEVELS, EVIDENCE_WORDS, evidenceWord, evidenceMeaning, combineEvidence } from './evidence-words.mjs';
18
+ export { symbolAt, definitionsAt, referencesAt, renameAt, applyRename } from './symbols.mjs';
19
+ export { coreChanges, affectedBy, CORE_CHANGES_SCHEMA, AFFECTED_SCHEMA } from './core-changes.mjs';
20
+ export { withCoreBehaviour } from './core-changes.mjs';
21
+ export { coreServiceFacts } from './core-services.mjs';
@@ -24,7 +24,7 @@ const MANIFEST = /^(go\.mod|package\.json|tsconfig\.json|jsconfig\.json)$/;
24
24
  */
25
25
  // manifestNames: which manifest files `manifests` brings (Thunder Trace also wants requirements.txt and *.csproj).
26
26
  // templates: also bring Angular component templates (*.component.html), which screens read with their component.
27
- export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false, manifestNames = MANIFEST, templates = false } = {}) {
27
+ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400000, manifests = false, manifestNames = MANIFEST, templates = false, thunder = false } = {}) {
28
28
  const out = [];
29
29
  const walk = (dir) => {
30
30
  let names;
@@ -39,6 +39,7 @@ export function collectReadableFiles(root, { maxFiles = 5000, maxFileBytes = 400
39
39
  if (st.isDirectory()) walk(full);
40
40
  else if (manifests && manifestNames.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), manifest: true });
41
41
  else if (templates && /\.component\.html$/i.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8'), template: true });
42
+ else if (thunder && /\.thunder$/i.test(name) && st.size <= maxFileBytes) out.push({ path, source: readFileSync(full, 'utf8') }); // Thunder Core programs (Trace)
42
43
  else if (readableLanguage(path) || (!name.includes('.') && shebangShell(full, st.size))) {
43
44
  // Oversized files are not loaded; readRepo lists them as skipped from their size.
44
45
  out.push(st.size > maxFileBytes ? { path, source: '', size: st.size } : { path, source: readFileSync(full, 'utf8') });
package/src/review.mjs CHANGED
@@ -12,13 +12,14 @@ import { thunderModel, readLevel, modelText } from './model.mjs';
12
12
  import { comparePlainRules, nameKey } from './same.mjs';
13
13
  import { readableLanguage } from './read-repo.mjs';
14
14
  import { byText } from './text-order.mjs';
15
+ import { isCoreProgram } from './core/kind.mjs';
15
16
 
16
17
  export const REVIEW_SCHEMA = 'thunder-review-v1';
17
18
  export const REVIEW_MARKER = '<!-- thunder-review -->';
18
19
 
19
20
  const SEVERITY_ORDER = ['risk', 'meaning', 'form'];
20
21
  // Within a severity, what a reviewer should read first.
21
- const KIND_ORDER = ['unreadable', 'not-read', 'infrastructure', 'stop-removed', 'stop-changed', 'address', 'effect-added', 'stop-added',
22
+ const KIND_ORDER = ['unreadable', 'test-fails', 'callers', 'not-read', 'infrastructure', 'stop-removed', 'stop-changed', 'address', 'effect-added', 'stop-added',
22
23
  'rule-limit', 'rule-answer', 'rule-new-answer', 'rule-removed-answer', 'rule-facts', 'input-added', 'input-removed',
23
24
  'gives-back-added', 'gives-back-removed', 'gives-back-changed', 'effect-removed', 'effect-changed', 'relies-on', 'hidden',
24
25
  'steps', 'outside', 'added', 'removed', 'thing', 'renamed', 'moved', 'form'];
@@ -411,7 +412,10 @@ function compareMember(o, n, items, { extracted = false } = {}) {
411
412
  if (o.m.rule && n.m.rule && !o.m.rule.partial && !n.m.rule.partial) {
412
413
  const r = comparePlainRules(o.m.rule, n.m.rule);
413
414
  if (r.same) {
414
- formOnly(`same answer on all ${r.tried} edge cases, run on both versions.`);
415
+ // Not "only the form": the code changed and the answers matched where they were tried. That is Tested evidence
416
+ // (docs/evidence-words.md), so it says how many cases, and that other inputs were not tried.
417
+ items.push(item(renamedOrMoved.length ? moveKind : 'form', 'form', subject, whereOf(n),
418
+ `${renamedOrMoved.length ? `${cap(renamedOrMoved.join(' and '))}. ` : ''}The code changed, but the answers are the same: Tested on ${r.capped ? `the first ${r.tried} of ${r.total}` : `all ${r.tried}`} edge cases, run on both versions (not every input).`));
415
419
  return 'form';
416
420
  }
417
421
  noteMove();
@@ -534,7 +538,13 @@ function mostlyIn(a, b) {
534
538
  return hit / want.length >= 0.75;
535
539
  }
536
540
 
537
- export function thunderReview(oldFiles, newFiles) {
541
+ /**
542
+ * Review two versions. Thunder Core programs are compared when `core` is given: coreChanges from
543
+ * @skillstech/thunderlang/program (it brings the Core compiler and engine, so this entry stays small without it).
544
+ * `context`: Thunder Core files that did not change but belong to a changed program's project ({ old, new }), so its
545
+ * tests can be run and what uses a change can be found (reviewGit reads them).
546
+ */
547
+ export function thunderReview(oldFiles, newFiles, { core = null, context = null } = {}) {
538
548
  detailsCache = new WeakMap();
539
549
  const A = side(oldFiles || []), B = side(newFiles || []);
540
550
  const items = [];
@@ -587,12 +597,17 @@ export function thunderReview(oldFiles, newFiles) {
587
597
  n.m.kind === 'not-read' ? "New function that Thunder cannot read yet: check the code itself." : `New ${KIND_WORD[n.m.kind] ?? 'function'}: ${subjectOf(n)}${summaryOf(n)}.`, { before: null, after: n.text }));
588
598
  compareThings(A, B, items);
589
599
 
600
+ // Thunder Core programs: rule by rule, with both versions run (core-changes.mjs).
601
+ const coreRead = core ? coreReview(core, oldFiles || [], newFiles || [], context, items) : { paths: new Set(), result: null };
602
+ const corePaths = coreRead.paths;
603
+
590
604
  // Files: code outside every action and rule, files Thunder could not read, and files it does not read.
591
605
  const paths = [...new Set([...A.sources.keys(), ...B.sources.keys()])];
592
606
  const notRead = [];
593
607
  for (const p of paths) {
594
608
  const before = A.sources.get(p), after = B.sources.get(p);
595
609
  if (before === after) continue;
610
+ if (corePaths.has(p)) continue;
596
611
  const lang = !isInfra(p) && readableLanguage(p);
597
612
  if (!lang) {
598
613
  if (isInfra(p)) items.push(item('infrastructure', 'risk', p, { file: p, line: 1 }, `${before == null ? 'New' : after == null ? 'Removed' : 'Changed'} infrastructure or pipeline file. Thunder does not read these in this version, so check it yourself.`, before != null && after != null ? lineChanges(before.split('\n'), after.split('\n')) : null));
@@ -654,7 +669,61 @@ export function thunderReview(oldFiles, newFiles) {
654
669
  const count = (s) => items.filter((x) => x.severity === s).length;
655
670
  const summary = { meaning: count('meaning'), risk: count('risk'), form: count('form'), unchanged, files: paths.filter((p) => A.sources.get(p) !== B.sources.get(p)).length };
656
671
  const onlyNotRead = !items.length && summary.files && notRead.length === summary.files;
657
- return { schema: REVIEW_SCHEMA, summary, says: onlyNotRead ? 'Only files Thunder does not read changed.' : summaryLine(summary), items, notRead };
672
+ const out = { schema: REVIEW_SCHEMA, summary, says: onlyNotRead ? 'Only files Thunder does not read changed.' : summaryLine(summary), items, notRead };
673
+ // The Thunder Core comparison itself (thunder-core-changes-v1), for callers that go on with it (review --services).
674
+ if (coreRead.result) Object.defineProperty(out, 'core', { value: coreRead.result, enumerable: false });
675
+ return out;
676
+ }
677
+
678
+ // The review kind for a Thunder Core change, so it sorts with the changes like it in other languages.
679
+ function coreKind(c) {
680
+ if (c.change === 'not-compiled') return 'unreadable';
681
+ if (c.kind === 'test' && c.severity === 'risk' && c.change !== 'removed') return 'test-fails';
682
+ if (c.change === 'added' || c.change === 'removed' || c.change === 'renamed') return c.kind === 'never' && c.change === 'removed' ? 'stop-removed' : c.change;
683
+ if (c.kind === 'keep') return 'rule-limit';
684
+ if (c.kind === 'function' && c.behaviour?.changed) return 'rule-answer';
685
+ if (c.kind === 'never') return 'stop-changed';
686
+ if (c.kind === 'record' || c.kind === 'store') return 'thing';
687
+ if (c.kind === 'main') return 'outside';
688
+ return 'steps';
689
+ }
690
+ const CORE_SUBJECT = { keep: (c) => `${c.subject} (kept value)`, main: (c) => c.subject };
691
+
692
+ /** Thunder Core changes as review items. Gives the paths it read, so they are not listed as "not read". */
693
+ function coreReview(coreChanges, oldFiles, newFiles, context, items) {
694
+ const core = (fs) => fs.filter((f) => f && isCoreProgram(f.path, f.source));
695
+ const merge = (changed, extra) => { const have = new Set(changed.map((f) => f.path)); return [...changed, ...core(extra ?? []).filter((f) => !have.has(f.path))]; };
696
+ const oldCore = core(oldFiles), newCore = core(newFiles);
697
+ if (!oldCore.length && !newCore.length) return { paths: new Set(), result: null };
698
+ const r = coreChanges(merge(oldCore, context?.old), merge(newCore, context?.new));
699
+ for (const c of r.changes) {
700
+ const look = (c.affects ?? []).slice(0, 6).map((x) => `${x.subject} (\`${x.file}:${x.line}\`${x.test ? `, ${x.test === 'fails' ? '**fails now**' : 'passes'}` : ''})`);
701
+ const more = (c.affects?.length ?? 0) > 6 ? `, and ${c.affects.length - 6} more` : '';
702
+ const says = look.length ? `${c.says} Look again at: ${look.join(', ')}${more}.` : c.says;
703
+ const evidence = c.before || c.after ? { before: c.before, after: c.after } : null;
704
+ items.push(item(coreKind(c), c.severity, (CORE_SUBJECT[c.kind] ?? ((x) => x.subject))(c), { file: c.file, line: c.line }, says, evidence));
705
+ }
706
+ return { paths: new Set([...oldCore, ...newCore].map((f) => f.path)), result: r };
707
+ }
708
+
709
+ /**
710
+ * Add other services to a review (thunder review --services): each Thunder Trace finding with callers in another
711
+ * repository becomes an item that names them, with what changes in the answers when Thunder Core said so. Mutates
712
+ * and gives back the review, with its summary counted again.
713
+ */
714
+ export function addServiceCallers(review, impact) {
715
+ for (const f of impact.findings) {
716
+ if (!f.dependents?.length) continue;
717
+ const who = f.dependents.slice(0, 6).map((d) => `${d.repo}: ${d.label} (\`${d.cite}\`)`).join(', ') + (f.dependents.length > 6 ? `, and ${f.dependents.length - 6} more` : '');
718
+ const what = (f.behaviour ?? []).map((x) => x.says).join(' ');
719
+ review.items.push(item('callers', f.risk === 'high' ? 'risk' : 'meaning', f.at.label, { file: f.at.file, line: f.at.line },
720
+ `${cap(f.says)}. Called from: ${who}.${what ? ` What changes: ${what}` : ''}`));
721
+ }
722
+ review.items.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind)
723
+ || byText(String(a.where.file), String(b.where.file)) || (a.where.line ?? 0) - (b.where.line ?? 0));
724
+ for (const s of ['meaning', 'risk', 'form']) review.summary[s] = review.items.filter((x) => x.severity === s).length;
725
+ review.says = summaryLine(review.summary);
726
+ return review;
658
727
  }
659
728
 
660
729
  const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
@@ -678,7 +747,7 @@ function evidenceBlock(ev) {
678
747
  /** The review as Markdown for a pull request comment, starting with REVIEW_MARKER so a bot can find and update it. */
679
748
  export function renderReview(r, { title = 'Thunder review', maxChars = 60000, footer = '' } = {}) {
680
749
  const out = [REVIEW_MARKER, `### ${title}`, '', `**${r.says}**`, ''];
681
- out.push('Read from the code by the Thunder compiler, with no AI. "Only the form changed" is said only when it is shown: the code is identical apart from spacing, comments, or names it declares itself, or a rule gives the same answer on every edge case.', '');
750
+ out.push('Read from the code by the Thunder compiler, with no AI. "Only the form changed" is said only when it is shown: the code is identical apart from spacing, comments, or names it declares itself. A rule whose code changed but whose answers match on every edge case tried is listed here too, marked Tested: other inputs were not tried.', '');
682
751
  const alsoIn = (x) => (x.also?.length ? [` <details><summary>Also in ${x.also.length} more</summary>`, '', ...x.also.slice(0, 50).map((a) => ` - **${a.subject}** · \`${a.where.file}:${a.where.line}\``), ...(x.also.length > 50 ? [` - and ${x.also.length - 50} more`] : []), '', ' </details>'] : []);
683
752
  const line = (x) => [`- **${x.subject}** · \`${x.where.file}:${x.where.line}\`: ${x.says}`, ...evidenceBlock(x.evidence).map((l) => (l ? ` ${l}` : '')), ...alsoIn(x)];
684
753
  const section = (sev, head) => {
@@ -691,7 +760,7 @@ export function renderReview(r, { title = 'Thunder review', maxChars = 60000, fo
691
760
  };
692
761
  section('risk', 'Needs a careful look');
693
762
  section('meaning', 'Changes in meaning');
694
- section('form', 'Only the form changed');
763
+ section('form', 'Only the form changed, or the same answers where tested');
695
764
  if (r.notRead.length) out.push(`Also changed, not read by Thunder: ${r.notRead.slice(0, 20).map((f) => `\`${f.path}\``).join(', ')}${r.notRead.length > 20 ? `, and ${r.notRead.length - 20} more` : ''}.`, '');
696
765
  if (footer) out.push(footer, '');
697
766
  let text = out.join('\n');
package/src/same.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // functions by name, and compares their Thunder. Rules are compared by RUNNING both on the same inputs (every edge
3
3
  // value either rule mentions), not by comparing text, so a rewritten condition that gives the same answers counts as
4
4
  // the same, and a changed limit is caught with a counterexample. Browser-safe: takes [{ path, source }].
5
+ import { combineEvidence, evidenceWord } from './evidence-words.mjs';
5
6
  import { readCode } from './read.mjs';
6
7
  import { readableLanguage, readingOf } from './read-repo.mjs';
7
8
  import { plainFromReading, explainPlain } from './plain-contract.mjs';
@@ -86,12 +87,14 @@ export function comparePlainRules(a, b) {
86
87
  }
87
88
  const bAsA = { ...b, inputs: b.inputs.map((i) => ({ ...i, id: toA.get(key(i)) })), rules: b.rules.map((r) => ({ ...r, conditions: r.conditions.map((c) => ({ ...c, input: toA.get(key(b.inputs.find((i) => i.id === c.input))) })) })) };
88
89
  let tried = 0;
89
- for (const values of product(caseValues([a, bAsA]))) {
90
+ const axes = caseValues([a, bAsA]);
91
+ const total = axes.reduce((n, [, vs]) => n * Math.max(1, vs.length), 1);
92
+ for (const values of product(axes)) {
90
93
  if (++tried > MAX_CASES) { tried--; break; }
91
94
  const x = explainPlain(a, values).outcome, y = explainPlain(bAsA, values).outcome;
92
95
  if (x !== y) return { same: false, tried, counterexample: { values: { ...values }, facts: a.inputs.map((i) => `${i.label} ${i.kind === 'yesno' ? (values[i.id] ? i.yes ?? 'yes' : i.no ?? 'no') : values[i.id]}`).join(', '), old: x, new: y } };
93
96
  }
94
- return { same: true, tried };
97
+ return { same: true, tried, total, ...(total > tried ? { capped: true } : {}) };
95
98
  }
96
99
 
97
100
  // Each step flattened in reading order: `sig` is what is compared (kind and wording, case- and punctuation-blind),
@@ -123,7 +126,7 @@ function compareItems(o, n) {
123
126
  if (o.kind === 'decision') {
124
127
  const r = compareRules(o, n);
125
128
  if (!r) return { status: 'cannot-check', reason: 'One rule could not be drawn as a card, so its answers could not be compared.', ...where };
126
- if (r.same) return { status: 'same', reason: `Same answer on all ${r.tried} edge cases.`, ...where };
129
+ if (r.same) return { status: 'same', reason: r.capped ? `Same answer on the first ${r.tried} of ${r.total} edge cases (the rest were not tried).` : `Same answer on all ${r.tried} edge cases.`, ...where };
127
130
  if (r.counterexample) {
128
131
  const facts = r.counterexample.facts;
129
132
  return { status: 'different', reason: `Different answer for ${facts}: ${r.counterexample.old} before, ${r.counterexample.new} after.`, counterexample: r.counterexample, ...where };
@@ -163,14 +166,21 @@ export function sameMeaning(oldFiles, newFiles) {
163
166
  }
164
167
  for (const [key, n] of B.items) if (!used.has(key)) items.push({ name: n.name, status: 'only-new', reason: 'New: not in the old code.', new: { file: n.file, line: n.line, language: n.language } });
165
168
  const counts = { same: 0, different: 0, 'only-old': 0, 'only-new': 0, 'cannot-check': 0 };
166
- for (const it of items) counts[it.status]++;
169
+ for (const it of items) {
170
+ counts[it.status]++;
171
+ // The evidence word (docs/evidence-words.md): a rule compared by running both on edge cases is Tested; steps whose
172
+ // wording and code match were not run, so only part of the claim is checked; a difference is Violated.
173
+ it.evidence = it.status === 'same' ? (/edge cases/.test(it.reason) ? 'tested' : 'partial') : it.status === 'cannot-check' ? 'unverified' : 'violated';
174
+ }
167
175
  const verdict = counts.different || counts['only-old'] || counts['only-new'] ? 'different' : counts['cannot-check'] ? 'partly-checked' : 'same';
168
- return { schema: SAME_SCHEMA, verdict, counts, items, unreadable: [...A.unreadable, ...B.unreadable] };
176
+ const evidence = combineEvidence(items.map((it) => it.evidence));
177
+ return { schema: SAME_SCHEMA, verdict, evidence, counts, items, unreadable: [...A.unreadable, ...B.unreadable] };
169
178
  }
170
179
 
171
180
  export function renderSame(r) {
172
181
  const head = r.verdict === 'same' ? 'Same meaning.' : r.verdict === 'partly-checked' ? 'No differences found, but some parts could not be checked.' : 'Different meaning.';
173
- const lines = [`${head} ${r.counts.same} same, ${r.counts.different} different, ${r.counts['only-old']} only in the old code, ${r.counts['only-new']} only in the new code, ${r.counts['cannot-check']} not checked.`];
182
+ const how = r.evidence ? ` ${evidenceWord(r.evidence)}${r.evidence === 'tested' ? ' (answers compared on edge cases, not every input)' : r.evidence === 'partial' ? ' (some parts compared by running, others only by reading)' : ''}.` : '';
183
+ const lines = [`${head}${how} ${r.counts.same} same, ${r.counts.different} different, ${r.counts['only-old']} only in the old code, ${r.counts['only-new']} only in the new code, ${r.counts['cannot-check']} not checked.`];
174
184
  const order = ['different', 'only-old', 'only-new', 'cannot-check', 'same'];
175
185
  const label = { different: 'different', 'only-old': 'only old', 'only-new': 'only new', 'cannot-check': 'not checked', same: 'same' };
176
186
  for (const st of order) for (const it of r.items.filter((x) => x.status === st)) {
@@ -54,7 +54,8 @@ export function unverifiedView(scan) {
54
54
  };
55
55
  }
56
56
 
57
- /** Verification coverage: share of guarantees + never-rules that have a verification. */
57
+ /** Verification coverage: share of guarantees + never-rules that NAME a verification. Nothing is run here, so
58
+ * `verified` counts claims with a check named (a declaration), not Tested ones (see docs/evidence-words.md). */
58
59
  export function coverageView(scan) {
59
60
  const claims = claimNodes(scan);
60
61
  const verified = verifiedIds(scan);
@@ -0,0 +1,23 @@
1
+ export interface ThunderFile { path: string; source: string }
2
+ /** A place in a file: 1-based line and column, and the length of the name as written there. */
3
+ export interface ThunderLocation { path: string; line: number; col: number; length: number }
4
+ export interface ThunderSymbol {
5
+ id: string;
6
+ kind: 'function' | 'type' | 'alternative' | 'value' | 'local' | 'input' | 'mission';
7
+ /** In words: "function", "data type", "input field", "rule", … */
8
+ what: string;
9
+ name: string;
10
+ definitions: ThunderLocation[];
11
+ references: ThunderLocation[];
12
+ }
13
+ export type ThunderRename =
14
+ | { ok: true; symbol: { id: string; kind: string; what: string; name: string }; edits: Array<ThunderLocation & { newText: string }> }
15
+ | { ok: false; problem: string };
16
+ /** The name at a position (1-based line and col), with where it is defined and used, or null. */
17
+ export function symbolAt(files: ThunderFile[], path: string, pos: { line: number; col: number }): (ThunderSymbol & { at: ThunderLocation }) | null;
18
+ export function definitionsAt(files: ThunderFile[], path: string, pos: { line: number; col: number }): ThunderLocation[];
19
+ export function referencesAt(files: ThunderFile[], path: string, pos: { line: number; col: number }, options?: { declaration?: boolean }): ThunderLocation[];
20
+ /** Every edit a rename needs, or why Thunder refuses it. Nothing is changed. */
21
+ export function renameAt(files: ThunderFile[], path: string, pos: { line: number; col: number }, newName: string): ThunderRename;
22
+ export function applyRename(files: ThunderFile[], edits: Array<ThunderLocation & { newText: string }>): ThunderFile[];
23
+ export function symbolIndex(files: ThunderFile[]): { occurrences: Array<ThunderLocation & { id: string; kind: string; name: string; def: boolean }>; results: unknown[] };