@skillstech/thunderlang 1.0.3 → 1.1.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.
- package/CHANGELOG.md +207 -0
- package/dist/core.cjs +13779 -10043
- package/dist/index.cjs +28500 -24392
- package/dist/learn.cjs +12853 -9579
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli.mjs +141 -58
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +133 -0
- package/src/core/diagnostics.mjs +81 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +38 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +167 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/target-python.mjs +486 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/libraries.mjs +2 -2
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +47 -7
- package/src/model.d.mts +7 -3
- package/src/model.mjs +30 -9
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/powershell.mjs +24 -5
- package/src/read-repo.mjs +1 -0
- package/src/read.d.mts +11 -0
- package/src/read.mjs +121 -13
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/rlang.mjs +10 -3
- package/src/say-less.mjs +1432 -0
- package/src/shell.mjs +45 -8
- package/src/sql-proc.mjs +1198 -0
- package/src/sql.mjs +87 -119
- package/src/steps.mjs +188 -37
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/why-cli.mjs +31 -0
- package/src/why.d.mts +28 -0
- package/src/why.mjs +532 -0
- package/src/write-steps.mjs +22 -5
package/src/trace-fs.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Thunder Trace, the Node side: read repository folders and their git state, and the lines a change touched.
|
|
2
|
+
// The linking itself is in trace.mjs (browser-safe).
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { basename, resolve } from 'node:path';
|
|
5
|
+
import { statSync } from 'node:fs';
|
|
6
|
+
import { collectReadableFiles } from './read-repo-fs.mjs';
|
|
7
|
+
import { thunderModel } from './model.mjs';
|
|
8
|
+
import { serviceFacts } from './system.mjs';
|
|
9
|
+
|
|
10
|
+
const git = (dir, args) => {
|
|
11
|
+
try { return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 }); } catch { return null; }
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** A folder as a repository for buildTrace: { name, files, sha, dirty, root }. */
|
|
15
|
+
export function readRepoDir(dir, { maxFiles = 5000 } = {}) {
|
|
16
|
+
const root = resolve(dir);
|
|
17
|
+
let ok = false;
|
|
18
|
+
try { ok = statSync(root).isDirectory(); } catch { /* missing */ }
|
|
19
|
+
if (!ok) throw new Error(`${dir} is not a folder.`);
|
|
20
|
+
const top = git(root, ['rev-parse', '--show-toplevel'])?.trim();
|
|
21
|
+
const sha = top ? git(root, ['rev-parse', 'HEAD'])?.trim() || null : null;
|
|
22
|
+
const dirty = top ? !!git(root, ['status', '--porcelain'])?.trim() : false;
|
|
23
|
+
return { name: basename(root), root, sha, dirty, files: collectReadableFiles(root, { maxFiles }) };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The commit a branch started from: --base if given, else where HEAD left main/master (origin first), else HEAD. */
|
|
27
|
+
export function baseOf(dir, base) {
|
|
28
|
+
if (base) return git(dir, ['rev-parse', '--verify', `${base}^{commit}`])?.trim() ? base : null;
|
|
29
|
+
for (const b of ['origin/main', 'origin/master', 'main', 'master']) {
|
|
30
|
+
const mb = git(dir, ['merge-base', 'HEAD', b])?.trim();
|
|
31
|
+
if (mb) return mb;
|
|
32
|
+
}
|
|
33
|
+
return git(dir, ['rev-parse', '--verify', 'HEAD'])?.trim() ? 'HEAD' : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* What changed in one repository since `base`, including uncommitted and new files, as traceImpact changes.
|
|
38
|
+
* For a changed or removed file, `before` holds what it offered at the base commit (routes, listeners, events).
|
|
39
|
+
*/
|
|
40
|
+
export function gitChanges(repo, base) {
|
|
41
|
+
const dir = repo.root;
|
|
42
|
+
const b = baseOf(dir, base);
|
|
43
|
+
if (!b) return { base: null, changes: [], why: base ? `${repo.name} has no commit ${base}` : `${repo.name} is not a git repository with commits` };
|
|
44
|
+
const prefix = (git(dir, ['rev-parse', '--show-prefix'])?.trim() ?? '');
|
|
45
|
+
const diff = git(dir, ['diff', '--unified=0', '--no-color', '--no-renames', b, '--', '.']) ?? '';
|
|
46
|
+
const byFile = new Map();
|
|
47
|
+
let cur = null;
|
|
48
|
+
for (const line of diff.split('\n')) {
|
|
49
|
+
let m;
|
|
50
|
+
if ((m = line.match(/^diff --git a\/(.+) b\/(.+)$/))) { cur = { file: m[2], ranges: [], status: 'changed' }; byFile.set(cur.file, cur); }
|
|
51
|
+
else if (cur && line.startsWith('new file mode')) cur.status = 'added';
|
|
52
|
+
else if (cur && line.startsWith('deleted file mode')) cur.status = 'removed';
|
|
53
|
+
else if (cur && (m = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/))) {
|
|
54
|
+
const start = Number(m[1]), n = m[2] === undefined ? 1 : Number(m[2]);
|
|
55
|
+
cur.ranges.push(n === 0 ? [Math.max(1, start), Math.max(1, start)] : [start, start + n - 1]);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const f of (git(dir, ['ls-files', '--others', '--exclude-standard', '--', '.']) ?? '').split('\n').filter(Boolean)) {
|
|
59
|
+
const file = prefix + f;
|
|
60
|
+
if (!byFile.has(file)) byFile.set(file, { file, ranges: [], status: 'added' });
|
|
61
|
+
}
|
|
62
|
+
const changes = [];
|
|
63
|
+
for (const c of byFile.values()) {
|
|
64
|
+
if (!c.file.startsWith(prefix)) continue;
|
|
65
|
+
const file = c.file.slice(prefix.length); // paths relative to the folder that was traced
|
|
66
|
+
let before = null;
|
|
67
|
+
if (c.status !== 'added') {
|
|
68
|
+
const old = git(dir, ['show', `${b}:${c.file}`]);
|
|
69
|
+
if (old != null) {
|
|
70
|
+
try { const files = [{ path: file, source: old }]; const f = serviceFacts(thunderModel(files), files); before = { routes: f.routes, listeners: f.listeners, publishes: f.publishes }; } catch { before = null; }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
changes.push({ repo: repo.name, file, ranges: c.ranges, status: c.status, ...(before ? { before } : {}) });
|
|
74
|
+
}
|
|
75
|
+
return { base: b, changes };
|
|
76
|
+
}
|
package/src/trace.mjs
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// Thunder Trace: how several repositories depend on each other, and what a change can affect. Browser-safe, no
|
|
2
|
+
// Node APIs (folders and git are read by trace-fs.mjs).
|
|
3
|
+
//
|
|
4
|
+
// repos ──thunderModel + serviceFacts──▶ per repo: routes, listeners (what it offers)
|
|
5
|
+
// requests, publishes (what it asks of others)
|
|
6
|
+
// ──buildTrace──▶ thunder-trace-v1: cross-repo links, each end cited repo@sha:file:line
|
|
7
|
+
// ──traceImpact──▶ what a change can affect, one hop out, ranked by risk
|
|
8
|
+
//
|
|
9
|
+
// The rules (each one keeps an answer from turning into noise or a guess):
|
|
10
|
+
// - Linked only on a fact: an HTTP request whose method and path match exactly one route in another repository,
|
|
11
|
+
// or an event published under the same name another repository listens for.
|
|
12
|
+
// - Paths every service has (/health, /metrics, …) and paths with no fixed part (/:id) are never linked across
|
|
13
|
+
// repositories; they are listed in notLinked with the reason. Two routes that match equally are not chosen
|
|
14
|
+
// between: both are named and nothing is linked.
|
|
15
|
+
// - Impact stops at the first hop. The callers of a changed route are listed; their own callers are not, or one
|
|
16
|
+
// shared service would list the whole estate.
|
|
17
|
+
// - Every finding cites repo@sha:file:line. No citation, no finding.
|
|
18
|
+
|
|
19
|
+
import { thunderModel } from './model.mjs';
|
|
20
|
+
import { serviceFacts, segsMatch, GENERIC_PATHS } from './system.mjs';
|
|
21
|
+
import { sha256 } from './hash.mjs';
|
|
22
|
+
|
|
23
|
+
export const TRACE_SCHEMA = 'thunder-trace-v1';
|
|
24
|
+
export const TRACE_IMPACT_SCHEMA = 'thunder-trace-impact-v1';
|
|
25
|
+
export const TRACE_RULES_VERSION = '1';
|
|
26
|
+
|
|
27
|
+
/** Test and fixture files: what they declare or call is pretend, so it is left out of the links. */
|
|
28
|
+
export function isTestFile(file) {
|
|
29
|
+
return /(^|\/)(tests?|__tests__|specs?|__mocks__|mocks?|fixtures?|__fixtures__|e2e|testdata|test-data)\//i.test(file)
|
|
30
|
+
|| /\.(test|spec|e2e)\.[a-z0-9]+$/i.test(file) || /(^|\/)test_[^/]+\.py$/.test(file) || /_test\.(go|py|rb|exs?)$/.test(file)
|
|
31
|
+
|| /(Tests?|Spec|IT)\.(cs|java|kt|scala)$/.test(file);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const short = (sha) => (sha ? String(sha).slice(0, 7) : 'working-tree');
|
|
35
|
+
/** repo@sha:file:line, the citation every finding carries. */
|
|
36
|
+
export function cite(repo, at) {
|
|
37
|
+
return `${repo.name}@${short(repo.sha)}${repo.dirty ? '+changes' : ''}:${at.file}${at.line ? `:${at.line}` : ''}`;
|
|
38
|
+
}
|
|
39
|
+
const end = (repo, at, extra = {}) => ({ repo: repo.name, member: at.member, label: at.label, file: at.file, line: at.line, cite: cite(repo, at), ...extra });
|
|
40
|
+
const distinctive = (segs) => segs.some((s) => s !== '*');
|
|
41
|
+
// Across repositories, fixed path parts match whatever their case: ASP.NET routes ignore it, and /api/Items is
|
|
42
|
+
// the same route as /api/items there. (Inside one repository the linker's own rules apply.)
|
|
43
|
+
const lower = (segs) => segs.map((s) => s.toLowerCase());
|
|
44
|
+
const pathMatch = (a, b) => segsMatch(lower(a), lower(b));
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read each repository and link them. repos: [{ name, files: [{ path, source }], sha?, dirty? }].
|
|
48
|
+
* Gives back thunder-trace-v1: { repos, links, notLinked, rules, fingerprint }.
|
|
49
|
+
*/
|
|
50
|
+
export function buildTrace(repos) {
|
|
51
|
+
const names = new Set();
|
|
52
|
+
const read = repos.map((r) => {
|
|
53
|
+
if (!r.name || names.has(r.name)) throw new Error(`Each repository needs its own name; "${r.name}" is used twice.`);
|
|
54
|
+
names.add(r.name);
|
|
55
|
+
const model = thunderModel(r.files, { name: r.name });
|
|
56
|
+
const facts = serviceFacts(model, r.files);
|
|
57
|
+
// Test code is not how services talk to each other: a test's fake route or request is never a link.
|
|
58
|
+
const real = (x) => !isTestFile(x.file);
|
|
59
|
+
const testItems = ['routes', 'listeners', 'requests', 'publishes'].reduce((n, k) => n + facts[k].filter((x) => !real(x)).length, 0);
|
|
60
|
+
return { name: r.name, sha: r.sha ?? null, dirty: !!r.dirty, files: model.files.length, languages: [...new Set(model.files.map((f) => f.language))].sort(),
|
|
61
|
+
routes: facts.routes.filter(real), listeners: facts.listeners.filter(real), requests: facts.requests.filter(real), publishes: facts.publishes.filter(real), unknown: facts.unknown.filter(real), testItems };
|
|
62
|
+
});
|
|
63
|
+
return linkRepos(read);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Link already-read repositories (each with routes, listeners, requests, publishes). Pure and deterministic. */
|
|
67
|
+
export function linkRepos(read) {
|
|
68
|
+
const links = [], notLinked = [];
|
|
69
|
+
for (const repo of read) {
|
|
70
|
+
for (const q of repo.requests) {
|
|
71
|
+
// A request this repository answers itself is not a link between repositories.
|
|
72
|
+
if (q.base === 'this app' && repo.routes.some((r) => methodOk(r.method, q.method) && pathMatch(r.segs, q.segs) >= 0)) continue;
|
|
73
|
+
const from = end(repo, q);
|
|
74
|
+
const call = `${q.method} ${q.path}`;
|
|
75
|
+
if (GENERIC_PATHS.has(q.path) || !distinctive(q.segs)) {
|
|
76
|
+
notLinked.push({ kind: 'http', call, from, why: GENERIC_PATHS.has(q.path) ? `every service has ${q.path}, so matching it to one repository would be a guess` : `${q.path} has no fixed part to match on` });
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const matches = [];
|
|
80
|
+
for (const other of read) {
|
|
81
|
+
if (other === repo) continue;
|
|
82
|
+
for (const r of other.routes) {
|
|
83
|
+
const score = methodOk(r.method, q.method) ? pathMatch(r.segs, q.segs) : -1;
|
|
84
|
+
if (score >= 0) matches.push({ other, r, score });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const best = Math.max(-1, ...matches.map((x) => x.score));
|
|
88
|
+
const top = matches.filter((x) => x.score === best);
|
|
89
|
+
if (top.length === 1) {
|
|
90
|
+
const { other, r } = top[0];
|
|
91
|
+
links.push({ kind: 'http', method: q.method, path: q.path, route: `${r.method} ${r.path}`, base: q.base, from, to: end(other, r) });
|
|
92
|
+
} else if (top.length > 1) {
|
|
93
|
+
notLinked.push({ kind: 'http', call, from, why: `${top.length} routes match equally (${top.map((x) => `${x.other.name}: ${x.r.method} ${x.r.path}`).join('; ')}), so none is chosen` });
|
|
94
|
+
} else notLinked.push({ kind: 'http', call, from, why: q.base === 'this app' ? `no route Thunder read, in this repository or the others traced, handles ${call}` : `no route Thunder read in the traced repositories handles ${call}` });
|
|
95
|
+
}
|
|
96
|
+
for (const p of repo.publishes) {
|
|
97
|
+
const from = end(repo, p);
|
|
98
|
+
let found = repo.listeners.some((l) => l.event === p.event);
|
|
99
|
+
for (const other of read) {
|
|
100
|
+
if (other === repo) continue;
|
|
101
|
+
for (const l of other.listeners) if (l.event === p.event) { links.push({ kind: 'event', event: p.event, from, to: end(other, l) }); found = true; }
|
|
102
|
+
}
|
|
103
|
+
if (!found) notLinked.push({ kind: 'event', call: `event ${p.event}`, from, why: `no listener Thunder read in the traced repositories waits for ${p.event}` });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const sortKey = (l) => `${l.from.cite}|${l.to?.cite ?? ''}|${l.kind}|${l.call ?? l.event ?? l.path ?? ''}`;
|
|
107
|
+
// (A step inside a callback is read for the callback and for the function around it: the same call, once.)
|
|
108
|
+
const once = (xs) => { const seen = new Set(); return xs.filter((x) => { const k = sortKey(x); if (seen.has(k)) return false; seen.add(k); return true; }); };
|
|
109
|
+
links.splice(0, links.length, ...once(links).sort((a, b) => sortKey(a).localeCompare(sortKey(b))));
|
|
110
|
+
notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => sortKey(a).localeCompare(sortKey(b))));
|
|
111
|
+
const repos = read.map(({ unknown, ...r }) => ({ ...r, unknown: unknown ?? [] }));
|
|
112
|
+
const body = { schema: TRACE_SCHEMA, rulesVersion: TRACE_RULES_VERSION, repos, links, notLinked };
|
|
113
|
+
return { ...body, fingerprint: sha256(JSON.stringify(body)) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const methodOk = (route, req) => route === req || route === 'ANY' || route === 'ALL';
|
|
117
|
+
const within = (line, ranges) => line != null && ranges.some(([a, b]) => line >= a && line <= b);
|
|
118
|
+
const overlaps = (lines, ranges) => !!lines && ranges.some(([a, b]) => a <= lines[1] && b >= lines[0]);
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* What a change can affect, one hop out.
|
|
122
|
+
* changes: [{ repo, file, ranges: [[from, to], …] (lines changed in the new file; [] for a removed file),
|
|
123
|
+
* status: 'added' | 'changed' | 'removed', before?: { routes, listeners, publishes } }]
|
|
124
|
+
* `before` is what the file offered before the change (read from the base commit); with it, a route or an event
|
|
125
|
+
* that was REMOVED is checked too: its callers in other repositories now reach nothing.
|
|
126
|
+
* Gives back thunder-trace-impact-v1: { findings (high first), changed, stopsAt: 1 }.
|
|
127
|
+
*/
|
|
128
|
+
export function traceImpact(trace, changes) {
|
|
129
|
+
const byName = new Map(trace.repos.map((r) => [r.name, r]));
|
|
130
|
+
const findings = [];
|
|
131
|
+
const touched = [];
|
|
132
|
+
for (const c of changes) {
|
|
133
|
+
const repo = byName.get(c.repo);
|
|
134
|
+
if (!repo) continue;
|
|
135
|
+
const hit = (x) => x.file === c.file && (c.status === 'added' || overlaps(x.lines, c.ranges) || within(x.line, c.ranges));
|
|
136
|
+
const routes = repo.routes.filter(hit), listeners = repo.listeners.filter(hit);
|
|
137
|
+
const requests = repo.requests.filter((x) => x.file === c.file && (c.status === 'added' || within(x.line, c.ranges) || overlaps(x.lines, c.ranges)));
|
|
138
|
+
const publishes = repo.publishes.filter((x) => x.file === c.file && (c.status === 'added' || within(x.line, c.ranges) || overlaps(x.lines, c.ranges)));
|
|
139
|
+
if (routes.length || listeners.length || requests.length || publishes.length || c.before) touched.push({ repo: c.repo, file: c.file, status: c.status });
|
|
140
|
+
|
|
141
|
+
for (const r of routes) {
|
|
142
|
+
const callers = trace.links.filter((l) => l.kind === 'http' && l.to.repo === repo.name && l.to.member === r.member);
|
|
143
|
+
findings.push({ risk: callers.length ? 'high' : 'low', kind: 'route-changed', says: callers.length ? `${r.method} ${r.path} changed, and ${count(callers.length, 'caller')} in other repositories ${callers.length === 1 ? 'depends' : 'depend'} on it` : `${r.method} ${r.path} changed; no traced repository calls it`, at: end(repo, r), dependents: callers.map((l) => ({ ...l.from, how: l.base === 'computed' ? 'matched by path; the base address is set when it runs' : l.base === 'this app' ? 'same path from another app' : `through ${l.base}` })) });
|
|
144
|
+
}
|
|
145
|
+
for (const p of publishes) {
|
|
146
|
+
const ls = trace.links.filter((l) => l.kind === 'event' && l.from.repo === repo.name && l.from.member === p.member && l.event === p.event);
|
|
147
|
+
findings.push({ risk: ls.length ? 'high' : 'low', kind: 'event-published', says: ls.length ? `publishes ${p.event}, which ${count(ls.length, 'listener')} in other repositories ${ls.length === 1 ? 'handles' : 'handle'}; a change to what it sends reaches them` : `publishes ${p.event}; nothing in the traced repositories listens for it`, at: end(repo, p), dependents: ls.map((l) => ({ ...l.to, how: `listens for ${p.event}` })) });
|
|
148
|
+
}
|
|
149
|
+
for (const q of requests) {
|
|
150
|
+
const l = trace.links.find((x) => x.kind === 'http' && x.from.repo === repo.name && x.from.member === q.member && x.from.line === q.line);
|
|
151
|
+
if (l) findings.push({ risk: 'medium', kind: 'request-changed', says: `a ${q.method} request to ${q.path} changed; it is handled in ${l.to.repo}`, at: end(repo, q), dependents: [{ ...l.to, how: `handles ${l.route}` }] });
|
|
152
|
+
}
|
|
153
|
+
for (const x of listeners) {
|
|
154
|
+
const senders = trace.links.filter((l) => l.kind === 'event' && l.to.repo === repo.name && l.to.member === x.member);
|
|
155
|
+
findings.push({ risk: 'low', kind: 'listener-changed', says: `the handler for ${x.event} changed${senders.length ? `; ${count(senders.length, 'publisher')} in other repositories ${senders.length === 1 ? 'sends' : 'send'} it` : ''}`, at: end(repo, x), dependents: senders.map((l) => ({ ...l.from, how: `publishes ${x.event}` })) });
|
|
156
|
+
}
|
|
157
|
+
// Removed: what the file offered before and no longer offers.
|
|
158
|
+
if (c.before) {
|
|
159
|
+
const nowRoutes = new Set(repo.routes.filter((r) => r.file === c.file).map((r) => `${r.method} ${r.path}`));
|
|
160
|
+
for (const r of c.before.routes || []) {
|
|
161
|
+
if (nowRoutes.has(`${r.method} ${r.path}`)) continue;
|
|
162
|
+
const callers = [];
|
|
163
|
+
for (const other of trace.repos) {
|
|
164
|
+
if (other.name === repo.name) continue;
|
|
165
|
+
for (const q of other.requests) if (methodOk(r.method, q.method) && pathMatch(r.segs, q.segs) >= 0 && distinctive(q.segs) && !GENERIC_PATHS.has(q.path)) callers.push({ ...end(other, q), how: `still sends ${q.method} ${q.path}` });
|
|
166
|
+
}
|
|
167
|
+
findings.push({ risk: callers.length ? 'high' : 'low', kind: 'route-removed', says: callers.length ? `${r.method} ${r.path} was removed, but ${count(callers.length, 'caller')} in other repositories still ${callers.length === 1 ? 'sends' : 'send'} it` : `${r.method} ${r.path} was removed; no traced repository calls it`, at: { repo: repo.name, file: c.file, line: r.line, label: r.label, cite: `${cite(repo, r)} (before the change)` }, dependents: callers });
|
|
168
|
+
}
|
|
169
|
+
const nowEvents = new Set(repo.publishes.map((p) => p.event));
|
|
170
|
+
for (const p of c.before.publishes || []) {
|
|
171
|
+
if (nowEvents.has(p.event)) continue;
|
|
172
|
+
const ls = [];
|
|
173
|
+
for (const other of trace.repos) if (other.name !== repo.name) for (const l of other.listeners) if (l.event === p.event) ls.push({ ...end(other, l), how: `waits for ${p.event}` });
|
|
174
|
+
findings.push({ risk: ls.length ? 'high' : 'low', kind: 'event-removed', says: ls.length ? `${p.event} is no longer published here, but ${count(ls.length, 'listener')} in other repositories ${ls.length === 1 ? 'waits' : 'wait'} for it` : `${p.event} is no longer published here; nothing else listens for it`, at: { repo: repo.name, file: c.file, line: p.line, label: p.label, cite: `${cite(repo, p)} (before the change)` }, dependents: ls });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const rank = { high: 0, medium: 1, low: 2 };
|
|
179
|
+
findings.sort((a, b) => rank[a.risk] - rank[b.risk] || a.at.cite.localeCompare(b.at.cite));
|
|
180
|
+
return { schema: TRACE_IMPACT_SCHEMA, traceFingerprint: trace.fingerprint, findings, changed: touched, stopsAt: 1, note: 'Stops at the first hop: callers of the callers are not listed. Links are facts read from code (no code was run); a call whose address is worked out when it runs is not linked.' };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const count = (n, w) => `${n} ${n === 1 ? w : w.endsWith('y') ? `${w.slice(0, -1)}ies` : `${w}s`}`;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Impact of one named thing: "POST /api/orders", "/api/orders/:id", an event name, "repo:file" or "repo:file:line".
|
|
187
|
+
* Gives back the same shape as traceImpact, plus `matched` (what the term was read as), so a surprising answer
|
|
188
|
+
* can be checked.
|
|
189
|
+
*/
|
|
190
|
+
export function traceImpactOf(trace, term) {
|
|
191
|
+
const t = String(term).trim();
|
|
192
|
+
const changes = [];
|
|
193
|
+
const matched = [];
|
|
194
|
+
const http = t.match(/^(?:(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ANY)\s+)?(\/\S*)$/i);
|
|
195
|
+
const place = t.match(/^([^:\s]+):([^:\s]+?)(?::(\d+))?$/);
|
|
196
|
+
for (const repo of trace.repos) {
|
|
197
|
+
if (http) {
|
|
198
|
+
const segs = http[2].split('/').filter(Boolean).map((s) => (/^(:\w+|\{[^}]+\}|\*)$/.test(s) ? '*' : s));
|
|
199
|
+
for (const r of repo.routes) if ((!http[1] || methodOk(r.method, http[1].toUpperCase())) && pathMatch(r.segs, segs) >= 0 && r.segs.length === segs.length) { changes.push({ repo: repo.name, file: r.file, ranges: [r.lines ?? [r.line, r.line]], status: 'changed' }); matched.push(`${repo.name}: route ${r.method} ${r.path}`); }
|
|
200
|
+
} else if (place && byNameOf(trace, place[1])) {
|
|
201
|
+
if (repo.name !== place[1]) continue;
|
|
202
|
+
const line = place[3] ? Number(place[3]) : null;
|
|
203
|
+
changes.push({ repo: repo.name, file: place[2], ranges: line ? [[line, line]] : [[1, Number.MAX_SAFE_INTEGER]], status: 'changed' });
|
|
204
|
+
matched.push(`${repo.name}: ${place[2]}${line ? ` line ${line}` : ' (the whole file)'}`);
|
|
205
|
+
} else {
|
|
206
|
+
for (const p of repo.publishes) if (p.event === t) { changes.push({ repo: repo.name, file: p.file, ranges: [[p.line, p.line]], status: 'changed' }); matched.push(`${repo.name}: publishes ${p.event}`); }
|
|
207
|
+
for (const l of repo.listeners) if (l.event === t) { changes.push({ repo: repo.name, file: l.file, ranges: [l.lines ?? [l.line, l.line]], status: 'changed' }); matched.push(`${repo.name}: listens for ${l.event}`); }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const r = traceImpact(trace, changes);
|
|
211
|
+
// An event name asks about that event only, not the route whose handler happens to publish it.
|
|
212
|
+
if (!http && !(place && byNameOf(trace, place[1]))) r.findings = r.findings.filter((f) => /^(event-|listener-)/.test(f.kind) && f.says.includes(t));
|
|
213
|
+
return { ...r, term: t, matched };
|
|
214
|
+
}
|
|
215
|
+
const byNameOf = (trace, name) => trace.repos.some((r) => r.name === name);
|
|
216
|
+
|
|
217
|
+
/** The trace as text, for the terminal. */
|
|
218
|
+
export function renderTrace(trace, { limit = 15 } = {}) {
|
|
219
|
+
const out = [];
|
|
220
|
+
out.push(`Thunder Trace: ${count(trace.repos.length, 'repository')}, ${count(trace.links.length, 'link')} between them`);
|
|
221
|
+
out.push('');
|
|
222
|
+
for (const r of trace.repos) {
|
|
223
|
+
out.push(`${r.name} @ ${short(r.sha)}${r.dirty ? ' (with uncommitted changes)' : ''}: ${r.files} files${r.languages.length ? ` (${r.languages.join(', ')})` : ''}`);
|
|
224
|
+
out.push(` offers ${count(r.routes.length, 'route')} and listens for ${count(new Set(r.listeners.map((l) => l.event)).size, 'event')}; sends ${count(r.requests.length, 'request')} and publishes ${count(new Set(r.publishes.map((p) => p.event)).size, 'event')}`);
|
|
225
|
+
}
|
|
226
|
+
if (trace.links.length) {
|
|
227
|
+
out.push('', 'Links between repositories');
|
|
228
|
+
for (const l of trace.links) {
|
|
229
|
+
out.push(l.kind === 'http'
|
|
230
|
+
? ` ${l.from.repo} → ${l.to.repo}: ${l.from.label} sends ${l.method} ${l.path}, handled by ${l.to.label}${l.base === 'computed' ? ' (matched by path; the base address is set when it runs)' : ''}`
|
|
231
|
+
: ` ${l.from.repo} → ${l.to.repo}: ${l.from.label} publishes ${l.event}, handled by ${l.to.label}`);
|
|
232
|
+
out.push(` ${l.from.cite} → ${l.to.cite}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (trace.notLinked.length) {
|
|
236
|
+
const shown = trace.notLinked.slice(0, limit);
|
|
237
|
+
out.push('', `Not linked: ${count(trace.notLinked.length, 'call')} worth knowing about, but not a fact`);
|
|
238
|
+
for (const n of shown) out.push(` ${n.from.repo}: ${n.call}: ${n.why} (${n.from.cite})`);
|
|
239
|
+
if (trace.notLinked.length > shown.length) out.push(` … and ${trace.notLinked.length - shown.length} more (all of them with --json)`);
|
|
240
|
+
}
|
|
241
|
+
const tests = trace.repos.reduce((n, r) => n + (r.testItems || 0), 0);
|
|
242
|
+
if (tests) out.push('', `Left out: ${count(tests, 'route, request, or event')} in test and fixture files.`.replace('route, request, or events', 'routes, requests, and events'));
|
|
243
|
+
out.push('', `Fingerprint ${trace.fingerprint.slice(0, 19)}… (rules v${trace.rulesVersion}). Read from code; nothing was run.`);
|
|
244
|
+
return out.join('\n');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** An impact result as text: high risk first, each finding with its citation and who depends on it. */
|
|
248
|
+
export function renderImpact(r) {
|
|
249
|
+
const out = [];
|
|
250
|
+
if (r.matched && !r.matched.length) return `"${r.term}" matched nothing: no route, event, or file by that name in the traced repositories.`;
|
|
251
|
+
const high = r.findings.filter((f) => f.risk === 'high').length;
|
|
252
|
+
out.push(r.findings.length
|
|
253
|
+
? `Thunder Trace impact: ${count(r.findings.length, 'finding')}, ${high} high risk. Stops at the first hop.`
|
|
254
|
+
: `Thunder Trace impact: nothing this change touches is called from, or calls into, another traced repository.`);
|
|
255
|
+
if (r.matched) out.push(`Read "${r.term}" as: ${r.matched.join('; ')}`);
|
|
256
|
+
for (const f of r.findings) {
|
|
257
|
+
out.push('', `${f.risk.toUpperCase().padEnd(6)} ${f.at.repo}: ${f.says}`, ` ${f.at.cite}`);
|
|
258
|
+
for (const d of f.dependents) out.push(` ← ${d.repo}: ${d.label} (${d.how}) ${d.cite}`);
|
|
259
|
+
}
|
|
260
|
+
return out.join('\n');
|
|
261
|
+
}
|
package/src/translate.d.mts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { IntentAst } from './index.js';
|
|
2
|
+
import type { GenerationDiagnostic } from './target-result.mjs';
|
|
2
3
|
export type TranslateLanguage = 'typescript' | 'python' | 'go' | 'rust' | 'csharp' | 'java';
|
|
3
4
|
export const TRANSLATE_LANGUAGES: Array<{ key: TranslateLanguage; label: string }>;
|
|
4
5
|
/** Translate every decision in a parsed ThunderLang AST into readable, typed source. Deterministic. */
|
|
5
6
|
export function translateDecisions(ast: IntentAst, lang: TranslateLanguage): string;
|
|
7
|
+
/** Same source plus one IL-GEN-001 diagnostic per rule condition the language cannot express (that rule throws). */
|
|
8
|
+
export function translateDecisionsWithDiagnostics(ast: IntentAst, lang: TranslateLanguage): { code: string; diagnostics: GenerationDiagnostic[] };
|
package/src/translate.mjs
CHANGED
|
@@ -3,8 +3,13 @@
|
|
|
3
3
|
// inference as the executable target adapters (target-*.mjs), minus their test harness, so what
|
|
4
4
|
// a reader sees here matches what `thunder test <file> --target <lang>` compiles and runs.
|
|
5
5
|
// Deterministic, no AI, no Node imports.
|
|
6
|
+
//
|
|
7
|
+
// A rule condition a language cannot express is never shown as `false`: the rule calls a helper
|
|
8
|
+
// that throws with the IL-GEN-001 message, and translateDecisionsWithDiagnostics() reports it.
|
|
9
|
+
// Money inputs render with each language's exact type (bigint minor units, Decimal, BigDecimal,
|
|
10
|
+
// decimal, int64/i64 minor units), never a float.
|
|
6
11
|
import { exprToJs, exprToPython, exprToGo, exprToRust, exprToCSharp, exprToJava } from './expr.mjs';
|
|
7
|
-
import { inputNames, inferInputTypes, strLit } from './target-types.mjs';
|
|
12
|
+
import { inputNames, inferInputTypes, strLit, planDecision } from './target-types.mjs';
|
|
8
13
|
|
|
9
14
|
const RELATIONAL = /^(<=|>=|<|>)$/;
|
|
10
15
|
|
|
@@ -25,6 +30,7 @@ function typesFor(ast, dec) {
|
|
|
25
30
|
}
|
|
26
31
|
for (const n of names) {
|
|
27
32
|
if (declared[n]) { types[n] = declared[n]; continue; }
|
|
33
|
+
if (types[n] === 'money') continue; // a declared Money input keeps its exact type
|
|
28
34
|
if (hasExample(n)) continue;
|
|
29
35
|
let guess = 'string';
|
|
30
36
|
for (const r of dec.rules || []) {
|
|
@@ -40,71 +46,82 @@ function typesFor(ast, dec) {
|
|
|
40
46
|
return types;
|
|
41
47
|
}
|
|
42
48
|
|
|
43
|
-
const tryExpr = (fn, when, inputs, fallback) => { try { return fn(when, { inputs }); } catch { return fallback; } };
|
|
44
|
-
|
|
45
49
|
const LANGS = {
|
|
46
50
|
typescript: {
|
|
47
|
-
label: 'TypeScript',
|
|
48
|
-
types: { number: 'number', bool: 'boolean', string: 'string' },
|
|
49
|
-
|
|
51
|
+
label: 'TypeScript', translate: exprToJs,
|
|
52
|
+
types: { number: 'number', bool: 'boolean', string: 'string', money: 'bigint' },
|
|
53
|
+
helper: ['function thunderUntranslated(message: string): boolean { throw new Error(message); }'],
|
|
54
|
+
untranslated: (m) => `thunderUntranslated(${strLit(m)})`,
|
|
55
|
+
emit(d, names, types, conds) {
|
|
50
56
|
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
|
|
51
57
|
const L = [`export function ${d.name}(${params}): string {`];
|
|
52
|
-
|
|
58
|
+
(d.rules || []).forEach((r, i) => L.push(` if (${conds[i]}) return ${strLit(r.result)};`));
|
|
53
59
|
L.push(` return ${strLit(d.default ?? '')};`, '}');
|
|
54
60
|
return L;
|
|
55
61
|
},
|
|
56
62
|
},
|
|
57
63
|
python: {
|
|
58
|
-
label: 'Python',
|
|
59
|
-
types: { number: 'float', bool: 'bool', string: 'str' },
|
|
60
|
-
|
|
64
|
+
label: 'Python', translate: exprToPython,
|
|
65
|
+
types: { number: 'float', bool: 'bool', string: 'str', money: 'Decimal' },
|
|
66
|
+
moneyImport: 'from decimal import Decimal',
|
|
67
|
+
helper: ['def _thunder_untranslated(message: str) -> bool:', ' raise NotImplementedError(message)'],
|
|
68
|
+
untranslated: (m) => `_thunder_untranslated(${strLit(m)})`,
|
|
69
|
+
emit(d, names, types, conds) {
|
|
61
70
|
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
|
|
62
71
|
const L = [`def ${d.name}(${params}) -> str:`];
|
|
63
|
-
|
|
72
|
+
(d.rules || []).forEach((r, i) => L.push(` if ${conds[i]}:`, ` return ${strLit(r.result)}`));
|
|
64
73
|
L.push(` return ${strLit(d.default ?? '')}`);
|
|
65
74
|
return L;
|
|
66
75
|
},
|
|
67
76
|
},
|
|
68
77
|
go: {
|
|
69
|
-
label: 'Go',
|
|
70
|
-
types: { number: 'float64', bool: 'bool', string: 'string' },
|
|
71
|
-
|
|
78
|
+
label: 'Go', translate: exprToGo,
|
|
79
|
+
types: { number: 'float64', bool: 'bool', string: 'string', money: 'int64' },
|
|
80
|
+
helper: ['func thunderUntranslated(message string) bool {', '\tpanic(message)', '}'],
|
|
81
|
+
untranslated: (m) => `thunderUntranslated(${strLit(m)})`,
|
|
82
|
+
emit(d, names, types, conds) {
|
|
72
83
|
const params = names.map((n) => `${n} ${this.types[types[n]]}`).join(', ');
|
|
73
84
|
const L = [`func ${d.name}(${params}) string {`];
|
|
74
|
-
|
|
85
|
+
(d.rules || []).forEach((r, i) => L.push(`\tif ${conds[i]} {`, `\t\treturn ${strLit(r.result)}`, '\t}'));
|
|
75
86
|
L.push(`\treturn ${strLit(d.default ?? '')}`, '}');
|
|
76
87
|
return L;
|
|
77
88
|
},
|
|
78
89
|
},
|
|
79
90
|
rust: {
|
|
80
|
-
label: 'Rust',
|
|
81
|
-
types: { number: 'f64', bool: 'bool', string: '&str' },
|
|
82
|
-
|
|
91
|
+
label: 'Rust', translate: exprToRust,
|
|
92
|
+
types: { number: 'f64', bool: 'bool', string: '&str', money: 'i64' },
|
|
93
|
+
helper: ['fn thunder_untranslated(message: &str) -> bool {', ' panic!("{}", message)', '}'],
|
|
94
|
+
untranslated: (m) => `thunder_untranslated(${strLit(m)})`,
|
|
95
|
+
emit(d, names, types, conds) {
|
|
83
96
|
const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
|
|
84
97
|
const L = [`fn ${d.name}(${params}) -> &'static str {`];
|
|
85
|
-
|
|
98
|
+
(d.rules || []).forEach((r, i) => L.push(` if ${conds[i]} {`, ` return ${strLit(r.result)};`, ' }'));
|
|
86
99
|
L.push(` ${strLit(d.default ?? '')}`, '}');
|
|
87
100
|
return L;
|
|
88
101
|
},
|
|
89
102
|
},
|
|
90
103
|
csharp: {
|
|
91
|
-
label: 'C#',
|
|
92
|
-
types: { number: 'double', bool: 'bool', string: 'string' },
|
|
93
|
-
|
|
104
|
+
label: 'C#', translate: exprToCSharp,
|
|
105
|
+
types: { number: 'double', bool: 'bool', string: 'string', money: 'decimal' },
|
|
106
|
+
helper: ['public static bool ThunderUntranslated(string message) => throw new NotImplementedException(message);'],
|
|
107
|
+
untranslated: (m) => `ThunderUntranslated(${strLit(m)})`,
|
|
108
|
+
emit(d, names, types, conds) {
|
|
94
109
|
const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(', ');
|
|
95
110
|
const L = [`public static string ${d.name}(${params})`, '{'];
|
|
96
|
-
|
|
111
|
+
(d.rules || []).forEach((r, i) => L.push(` if (${conds[i]}) return ${strLit(r.result)};`));
|
|
97
112
|
L.push(` return ${strLit(d.default ?? '')};`, '}');
|
|
98
113
|
return L;
|
|
99
114
|
},
|
|
100
115
|
},
|
|
101
116
|
java: {
|
|
102
|
-
label: 'Java',
|
|
103
|
-
types: { number: 'double', bool: 'boolean', string: 'String' },
|
|
104
|
-
|
|
117
|
+
label: 'Java', translate: exprToJava,
|
|
118
|
+
types: { number: 'double', bool: 'boolean', string: 'String', money: 'java.math.BigDecimal' },
|
|
119
|
+
helper: ['public static boolean thunderUntranslated(String message) { throw new UnsupportedOperationException(message); }'],
|
|
120
|
+
untranslated: (m) => `thunderUntranslated(${strLit(m)})`,
|
|
121
|
+
emit(d, names, types, conds) {
|
|
105
122
|
const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(', ');
|
|
106
123
|
const L = [`public static String ${d.name}(${params}) {`];
|
|
107
|
-
|
|
124
|
+
(d.rules || []).forEach((r, i) => L.push(` if (${conds[i]}) return ${strLit(r.result)};`));
|
|
108
125
|
L.push(` return ${strLit(d.default ?? '')};`, '}');
|
|
109
126
|
return L;
|
|
110
127
|
},
|
|
@@ -113,14 +130,27 @@ const LANGS = {
|
|
|
113
130
|
|
|
114
131
|
export const TRANSLATE_LANGUAGES = Object.entries(LANGS).map(([key, l]) => ({ key, label: l.label }));
|
|
115
132
|
|
|
116
|
-
/**
|
|
117
|
-
|
|
133
|
+
/**
|
|
134
|
+
* Translate every decision into `lang` and report generation diagnostics: one IL-GEN-001 error per
|
|
135
|
+
* rule condition the language cannot express (that rule throws in the output instead of guessing).
|
|
136
|
+
*/
|
|
137
|
+
export function translateDecisionsWithDiagnostics(ast, lang) {
|
|
118
138
|
const L = LANGS[lang];
|
|
119
139
|
if (!L) throw new Error(`Unknown language ${lang}. Use one of: ${Object.keys(LANGS).join(', ')}.`);
|
|
120
140
|
const comment = lang === 'python' ? '#' : '//';
|
|
141
|
+
const plans = (ast.decisions || []).map((d) => planDecision(ast, d, { translate: L.translate, target: L.label }));
|
|
142
|
+
const diagnostics = plans.flatMap((p) => p.diagnostics);
|
|
121
143
|
const out = [`${comment} Generated from ThunderLang. Deterministic, no AI. The first matching rule wins.`];
|
|
122
|
-
|
|
123
|
-
|
|
144
|
+
if (L.moneyImport && plans.some((p) => Object.keys(p.money).length)) out.push(L.moneyImport);
|
|
145
|
+
if (diagnostics.length) out.push('', `${comment} IL-GEN-001: Thunder could not translate some rule conditions. Those rules throw instead of guessing.`, ...L.helper);
|
|
146
|
+
for (const p of plans) {
|
|
147
|
+
const conds = p.rules.map(({ code, message }) => code ?? L.untranslated(message));
|
|
148
|
+
out.push('', ...L.emit(p.decision, p.names, typesFor(ast, p.decision), conds));
|
|
124
149
|
}
|
|
125
|
-
return out.join('\n');
|
|
150
|
+
return { code: out.join('\n'), diagnostics };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Translate every decision in a parsed ThunderLang AST into `lang`. Returns source text. */
|
|
154
|
+
export function translateDecisions(ast, lang) {
|
|
155
|
+
return translateDecisionsWithDiagnostics(ast, lang).code;
|
|
126
156
|
}
|
package/src/why-cli.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// thunder why: an AI agent's run explained in plain words (src/why.mjs, docs/why.md).
|
|
2
|
+
// thunder why <run.json> [--step n] [--run id] [--json]
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { explainRun, renderWhy, renderStep } from './why.mjs';
|
|
5
|
+
|
|
6
|
+
const USAGE = `usage: thunder why <run.json> [--step n] [--run id] [--json]
|
|
7
|
+
Explains what an AI agent did, from its OpenTelemetry record: what it was asked, each step, what it changed,
|
|
8
|
+
and what went wrong. Nothing is run and no AI is used. Read "-" for standard input.`;
|
|
9
|
+
|
|
10
|
+
export function whyMain(argv) {
|
|
11
|
+
const a = { _: [], json: false, step: null, run: null };
|
|
12
|
+
for (let i = 0; i < argv.length; i++) {
|
|
13
|
+
const x = argv[i];
|
|
14
|
+
if (x === '--json') a.json = true;
|
|
15
|
+
else if (x === '--step') a.step = argv[++i];
|
|
16
|
+
else if (x === '--run') a.run = argv[++i];
|
|
17
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
|
|
18
|
+
else if (x.startsWith('--')) { console.error(`thunder why: there is no option ${x}.\n${USAGE}`); return 2; }
|
|
19
|
+
else a._.push(x);
|
|
20
|
+
}
|
|
21
|
+
if (a._.length !== 1) { console.error(`thunder why: name one file with the agent's record.\n${USAGE}`); return 2; }
|
|
22
|
+
if (a.step != null && !/^\d+$/.test(String(a.step))) { console.error('thunder why: --step needs a step number, like --step 3.'); return 2; }
|
|
23
|
+
let text;
|
|
24
|
+
try { text = readFileSync(a._[0] === '-' ? 0 : a._[0], 'utf8'); }
|
|
25
|
+
catch (e) { console.error(`thunder why: couldn't open ${a._[0]}${e.code === 'ENOENT' ? ': there is no such file' : `: ${e.message}`}.`); return 2; }
|
|
26
|
+
const r = explainRun(text, { run: a.run });
|
|
27
|
+
if (!r.ok) { console.error(`thunder why: ${r.why}`); return 2; }
|
|
28
|
+
if (a.json) console.log(JSON.stringify(a.step != null ? r.steps.find((s) => s.n === Number(a.step)) ?? null : r, null, 2));
|
|
29
|
+
else console.log(a.step != null ? renderStep(r, a.step) : renderWhy(r));
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
package/src/why.d.mts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Thunder Why: an AI agent's run explained in plain words (docs/why.md).
|
|
2
|
+
export interface WhyStep {
|
|
3
|
+
n: number; depth: number;
|
|
4
|
+
kind: 'agent' | 'model' | 'tool' | 'http' | 'db' | 'retrieve' | 'other';
|
|
5
|
+
text: string; outcome: string; sentence: string; failed: boolean;
|
|
6
|
+
effect: 'read' | 'change' | 'unknown' | 'none';
|
|
7
|
+
tries: number; atMs: number | null; durationMs: number | null; span: string;
|
|
8
|
+
details: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface WhyRun {
|
|
11
|
+
ok: true; run: string; otherRuns: string[];
|
|
12
|
+
status: 'finished' | 'finished-with-problems' | 'stopped';
|
|
13
|
+
headline: string; asked: string | null; answered: string | null;
|
|
14
|
+
problem: null | {
|
|
15
|
+
step: number; inside: { step: number; text: string } | null; what: string; tries: number;
|
|
16
|
+
before: { step: number; text: string } | null; wouldHaveChanged: string; next: string | null;
|
|
17
|
+
details: Record<string, unknown>;
|
|
18
|
+
};
|
|
19
|
+
recovered: Array<{ step: number; text: string }>;
|
|
20
|
+
warnings: Array<{ step: number; text: string }>;
|
|
21
|
+
changes: Array<{ step: number; text: string; worked: boolean; basis: string; tries: number }>;
|
|
22
|
+
unknown: Array<{ step: number; text: string }>;
|
|
23
|
+
durationMs: number | null; steps: WhyStep[]; spanCount: number;
|
|
24
|
+
}
|
|
25
|
+
export function explainRun(input: string | object, options?: { run?: string }): WhyRun | { ok: false; why: string };
|
|
26
|
+
export function renderWhy(run: WhyRun | { ok: false; why: string }): string;
|
|
27
|
+
export function renderStep(run: WhyRun | { ok: false; why: string }, n: number | string): string;
|
|
28
|
+
export function plainError(error?: { type?: string | null; message?: string | null; status?: number | string | null; finish?: string | null }): { what: string; next: string | null };
|