@skillstech/thunderlang 1.1.0 → 1.2.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 +81 -0
- package/README.md +4 -1
- package/dist/core.cjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/learn.cjs +7510 -503
- package/package.json +2 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +107 -38
- package/src/core/cli.mjs +65 -14
- package/src/core/diagnostics.mjs +1 -0
- package/src/core/engine-core.mjs +572 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/index.mjs +1 -0
- package/src/core/project.mjs +16 -6
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/target-python.mjs +2 -1
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/emit.mjs +1 -1
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/read-level.mjs +146 -0
- package/src/term.mjs +89 -0
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +17 -7
- package/src/why.d.mts +17 -7
- package/src/why.mjs +114 -33
package/src/try-cli.mjs
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// thunder try: try a rule with your own situations and see the answer and why ("What if?").
|
|
2
|
+
// thunder try <file> [--focus "<rule>"] [--with "days late=10, member=yes"] [--json]
|
|
3
|
+
// Only rules: a rule decides and changes nothing, so trying one is safe. The answer comes from the same engine as
|
|
4
|
+
// the web editor (plainFromReading + explainPlain): the rule as the reader understood it from the code, run on the
|
|
5
|
+
// values you give. Rules too complex for it are refused with the reason, never approximated.
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { paint, useColor } from './term.mjs';
|
|
8
|
+
import { basename } from 'node:path';
|
|
9
|
+
import { createInterface } from 'node:readline';
|
|
10
|
+
import { readCode } from './read.mjs';
|
|
11
|
+
import { plainFromReading, explainPlain } from './plain-contract.mjs';
|
|
12
|
+
import { parseIntent } from './parse.mjs';
|
|
13
|
+
import { evaluateDecision } from './runtime.mjs';
|
|
14
|
+
|
|
15
|
+
const USAGE = `usage: thunder try <file> [--focus "<rule>"] [--with "name=value, name=value"] [--json]
|
|
16
|
+
Try a rule from your code with your own values, and see the answer and why. Without --with, Thunder asks.
|
|
17
|
+
Only rules can be tried: they decide and change nothing.`;
|
|
18
|
+
|
|
19
|
+
const squash = (s) => String(s ?? '').toLowerCase().replace(/^(the|it is|is)\s+/, '').replace(/[^a-z0-9]/g, '');
|
|
20
|
+
const human = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase();
|
|
21
|
+
const outcomeText = (o) => { const h = human(o); return h.charAt(0).toUpperCase() + h.slice(1); };
|
|
22
|
+
const inputName = (i) => String(i.label).replace(/^(the|it is)\s+/, '');
|
|
23
|
+
const kindText = { number: 'a number', yesno: 'yes or no', text: 'some text', any: 'a value' };
|
|
24
|
+
|
|
25
|
+
/** A typed value from what a person wrote, or { error } saying what to write instead. */
|
|
26
|
+
export function parseValue(input, raw) {
|
|
27
|
+
const t = String(raw ?? '').trim();
|
|
28
|
+
if (input.kind === 'number') {
|
|
29
|
+
const n = Number(t.replace(/[$,%\s]/g, ''));
|
|
30
|
+
return t !== '' && Number.isFinite(n) ? { value: n } : { error: `"${t}" isn't a number. Write one like 10 or 2.5.` };
|
|
31
|
+
}
|
|
32
|
+
if (input.kind === 'yesno') {
|
|
33
|
+
if (/^(y|yes|true|1)$/i.test(t)) return { value: true };
|
|
34
|
+
if (/^(n|no|false|0)$/i.test(t)) return { value: false };
|
|
35
|
+
return { error: `"${t}" isn't yes or no. Write yes or no.` };
|
|
36
|
+
}
|
|
37
|
+
if (input.kind === 'any') {
|
|
38
|
+
if (/^-?[$]?[\d,]*\.?\d+%?$/.test(t)) return { value: Number(t.replace(/[$,%]/g, '')) };
|
|
39
|
+
if (/^(yes|true)$/i.test(t)) return { value: true };
|
|
40
|
+
if (/^(no|false)$/i.test(t)) return { value: false };
|
|
41
|
+
}
|
|
42
|
+
return { value: t };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ── Rules in a mission file (ThunderLang™ decisions) ───────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
/** The decisions in a mission file, or null when the file is not one. */
|
|
48
|
+
export function missionRules(source) {
|
|
49
|
+
let ast;
|
|
50
|
+
try { ast = parseIntent(source); } catch { return null; }
|
|
51
|
+
if (!ast?.decisions?.length) return null;
|
|
52
|
+
return ast.decisions.map((dec) => ({
|
|
53
|
+
name: outcomeText(dec.name), dec,
|
|
54
|
+
plain: { inputs: (dec.inputs || []).map((x) => {
|
|
55
|
+
const id = String(x?.name ?? x).split(/[\s:]/)[0];
|
|
56
|
+
// The kind, from how the rules use it: compared with a number, or used as a yes/no on its own.
|
|
57
|
+
const whens = (dec.rules || []).map((r) => r.when || '').join(' ; ');
|
|
58
|
+
const num = new RegExp(`\\b${id}\\s*(>=|<=|>|<|==|!=)\\s*-?\\d|-?\\d\\s*(>=|<=|>|<|==|!=)\\s*${id}\\b`).test(whens);
|
|
59
|
+
const yesno = !num && new RegExp(`(^|[!(&|;]\\s*)${id}\\s*($|[)&|;])|\\b${id}\\s*==\\s*(true|false)\\b`).test(whens);
|
|
60
|
+
return { id, label: human(id), kind: num ? 'number' : yesno ? 'yesno' : 'any' };
|
|
61
|
+
}) },
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A mission condition in words: "age >= 18" -> "age is at least 18". */
|
|
66
|
+
export function conditionWords(expr) {
|
|
67
|
+
return String(expr)
|
|
68
|
+
.replace(/\s*>=\s*/g, ' is at least ').replace(/\s*<=\s*/g, ' is at most ')
|
|
69
|
+
.replace(/\s*!=\s*/g, ' is not ').replace(/\s*==\s*/g, ' is ')
|
|
70
|
+
.replace(/\s*>\s*/g, ' is more than ').replace(/\s*<\s*/g, ' is less than ')
|
|
71
|
+
.replace(/\s*&&\s*/g, ' and ').replace(/\s*\|\|\s*/g, ' or ').replace(/!\s*(?=\w)/g, 'not ')
|
|
72
|
+
.replace(/\b([a-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+|[a-z]+[A-Z][A-Za-z0-9]*)\b/g, (w) => human(w))
|
|
73
|
+
.replace(/\s+/g, ' ').trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Try a mission decision: the same answer and reasons shape as tryRule. */
|
|
77
|
+
export function tryMission(rule, values) {
|
|
78
|
+
const run = evaluateDecision(rule.dec, values);
|
|
79
|
+
const ids = rule.plain.inputs.map((i) => i.id);
|
|
80
|
+
const seen = (when) => ids.filter((id) => new RegExp(`\\b${id}\\b`).test(when)).map((id) => `${human(id)} is ${typeof values[id] === 'boolean' ? (values[id] ? 'yes' : 'no') : values[id]}`).join(', ');
|
|
81
|
+
const why = [];
|
|
82
|
+
for (const t of run.trace) {
|
|
83
|
+
if (!t.when) continue;
|
|
84
|
+
const result = rule.dec.rules.find((r) => r.name === t.rule)?.result;
|
|
85
|
+
if (t.error) { why.push({ ok: false, text: conditionWords(t.when), actual: `could not be worked out: ${t.error}`, yesno: true }); continue; }
|
|
86
|
+
if (t.matched && t.rule === run.matched) { why.push({ ok: true, text: conditionWords(t.when), actual: seen(t.when), yesno: true }); why.push({ answer: true, text: `so: ${outcomeText(result)}` }); break; }
|
|
87
|
+
why.push({ ok: false, text: conditionWords(t.when), actual: seen(t.when), yesno: true, skipped: outcomeText(result) });
|
|
88
|
+
}
|
|
89
|
+
if (run.matched === 'default') why.push({ answer: true, text: `none of the rules matched, so: ${outcomeText(run.result)} (otherwise)` });
|
|
90
|
+
if (run.undecided) why.push({ answer: true, text: 'no rule matched and there is no "otherwise" answer, so the rule gives no answer' });
|
|
91
|
+
return { answer: run.undecided ? 'No answer' : outcomeText(run.result), outcome: run.result, ruleIndex: run.matched === 'default' ? -1 : rule.dec.rules.findIndex((r) => r.name === run.matched), why, values };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Parse --with "a=1, b=yes" into { inputId: value }, or { error }. */
|
|
95
|
+
export function parseWith(plain, specs) {
|
|
96
|
+
const values = {};
|
|
97
|
+
for (const part of specs.flatMap((s) => s.split(/,(?![^"]*"\s*$)/)).map((x) => x.trim()).filter(Boolean)) {
|
|
98
|
+
const eq = part.indexOf('=');
|
|
99
|
+
if (eq < 0) return { error: `"${part}" needs a value: write it as name=value, like "${inputName(plain.inputs[0])}=10".` };
|
|
100
|
+
const name = part.slice(0, eq), raw = part.slice(eq + 1);
|
|
101
|
+
const input = plain.inputs.find((i) => squash(i.label) === squash(name) || squash(i.id) === squash(name));
|
|
102
|
+
if (!input) return { error: `This rule has no "${name.trim()}". It takes: ${plain.inputs.map(inputName).join(', ')}.` };
|
|
103
|
+
const v = parseValue(input, raw.replace(/^"|"$/g, ''));
|
|
104
|
+
if (v.error) return { error: `${inputName(input)}: ${v.error}` };
|
|
105
|
+
values[input.id] = v.value;
|
|
106
|
+
}
|
|
107
|
+
const missing = plain.inputs.filter((i) => !(i.id in values));
|
|
108
|
+
if (missing.length) return { error: `Give a value for ${missing.map(inputName).join(' and ')}, like --with "${missing.map((i) => `${inputName(i)}=${i.kind === 'yesno' ? 'yes' : i.kind === 'number' ? '10' : 'text'}`).join(', ')}".` };
|
|
109
|
+
return { values };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The answer and why, from the engine's explanation. */
|
|
113
|
+
export function tryRule(plain, values) {
|
|
114
|
+
const ex = explainPlain(plain, values);
|
|
115
|
+
const kindOf = (id) => plain.inputs.find((i) => i.id === id)?.kind;
|
|
116
|
+
const shown = (c) => (kindOf(c.input) === 'yesno' ? (values[c.input] ? 'yes' : 'no') : c.actual);
|
|
117
|
+
const why = [];
|
|
118
|
+
ex.rules.forEach((r, i) => {
|
|
119
|
+
if (i === ex.ruleIndex) {
|
|
120
|
+
for (const c of r.checks) why.push({ ok: true, text: c.text, actual: shown(c), yesno: kindOf(c.input) === 'yesno' });
|
|
121
|
+
why.push({ answer: true, text: `so: ${outcomeText(r.outcome)}` });
|
|
122
|
+
} else if (ex.ruleIndex === -1 || i < ex.ruleIndex) {
|
|
123
|
+
const miss = r.checks.find((c) => !c.ok);
|
|
124
|
+
if (miss) why.push({ ok: false, text: miss.text, actual: shown(miss), yesno: kindOf(miss.input) === 'yesno', skipped: outcomeText(r.outcome) });
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
if (ex.ruleIndex === -1) why.push({ answer: true, text: `none of the rules matched, so: ${outcomeText(ex.outcome)} (otherwise)` });
|
|
128
|
+
return { answer: outcomeText(ex.outcome), outcome: ex.outcome, ruleIndex: ex.ruleIndex, why, values };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function renderTry(t) {
|
|
132
|
+
const L = [`Answer: ${t.answer}`, 'Why:'];
|
|
133
|
+
for (const w of t.why) {
|
|
134
|
+
if (w.answer) L.push(` → ${w.text}`);
|
|
135
|
+
else L.push(` ${w.ok ? '✓' : '✗'} ${w.text}${w.actual != null && w.actual !== '' ? ` (${w.yesno ? w.actual : `it is ${w.actual}`})` : ''}${w.skipped ? `, so not ${w.skipped}` : ''}`);
|
|
136
|
+
}
|
|
137
|
+
return L.join('\n');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The rules in a file that Try can run, and the ones it cannot (with why). */
|
|
141
|
+
export function rulesIn(source, file) {
|
|
142
|
+
const all = readCode(source, { file: basename(file) }).items;
|
|
143
|
+
const items = all.filter((i) => i.kind === 'decision');
|
|
144
|
+
const rules = items.map((item) => {
|
|
145
|
+
const plain = plainFromReading(item);
|
|
146
|
+
return { name: outcomeText(item.name), item, plain, line: item.line ?? item.lines?.[0] ?? null, why: plain ? null : 'it is more than simple comparisons and yes/no checks, so Thunder cannot try it yet' };
|
|
147
|
+
});
|
|
148
|
+
rules.others = all.filter((i) => i.kind === 'function').map((i) => ({ name: outcomeText(i.name), raw: i.name }));
|
|
149
|
+
return rules;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function tryMain(argv, { input = process.stdin, output = process.stdout } = {}) {
|
|
153
|
+
const a = { _: [], focus: null, with: [], json: false };
|
|
154
|
+
for (let i = 0; i < argv.length; i++) {
|
|
155
|
+
const x = argv[i];
|
|
156
|
+
if (x === '--focus') a.focus = argv[++i];
|
|
157
|
+
else if (x === '--with') a.with.push(argv[++i] ?? '');
|
|
158
|
+
else if (x === '--json') a.json = true;
|
|
159
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
|
|
160
|
+
else if (x.startsWith('--')) { console.error(`thunder try: there is no option ${x}.\n${USAGE}`); return 2; }
|
|
161
|
+
else a._.push(x);
|
|
162
|
+
}
|
|
163
|
+
if (a._.length !== 1) { console.error(`thunder try: name one code file.\n${USAGE}`); return 2; }
|
|
164
|
+
const file = a._[0];
|
|
165
|
+
let source;
|
|
166
|
+
try { source = readFileSync(file, 'utf8'); } catch (e) { console.error(`thunder try: couldn't open ${file}${e.code === 'ENOENT' ? ': there is no such file' : `: ${e.message}`}.`); return 2; }
|
|
167
|
+
const mission = /\.(thunder|intent)$/i.test(file) ? missionRules(source) : null;
|
|
168
|
+
const rules = mission ?? rulesIn(source, file);
|
|
169
|
+
if (!rules.length) { console.error(`thunder try: Thunder found no rules in ${file}. A rule decides between answers, like "if days late <= 7: return SmallFee". See what it does find: thunder read ${file}`); return 2; }
|
|
170
|
+
|
|
171
|
+
let rule;
|
|
172
|
+
if (a.focus) {
|
|
173
|
+
rule = rules.find((r) => squash(r.name) === squash(a.focus) || squash(r.item.name) === squash(a.focus));
|
|
174
|
+
if (!rule) {
|
|
175
|
+
const other = (rules.others || []).find((o) => squash(o.name) === squash(a.focus) || squash(o.raw) === squash(a.focus));
|
|
176
|
+
if (other) { console.error(`thunder try: "${other.name}" is not a rule: it does things (it may change data or call other code), so Thunder won't run it to try it. Try works on rules: ${rules.map((r) => `"${r.name}"`).join(', ')}. See what "${other.name}" does: thunder read ${file} --level flow --focus "${other.name}"`); return 2; }
|
|
177
|
+
console.error(`thunder try: there is no rule "${a.focus}" in ${file}. The rules: ${rules.map((r) => `"${r.name}"`).join(', ')}.`);
|
|
178
|
+
return 2;
|
|
179
|
+
}
|
|
180
|
+
} else if (rules.length === 1) rule = rules[0];
|
|
181
|
+
else {
|
|
182
|
+
console.error(`thunder try: ${file} has ${rules.length} rules. Pick one:\n${rules.map((r) => ` thunder try ${file} --focus "${r.name}"`).join('\n')}`);
|
|
183
|
+
return 2;
|
|
184
|
+
}
|
|
185
|
+
const run = (values) => (mission ? tryMission(rule, values) : tryRule(rule.plain, values));
|
|
186
|
+
if (!rule.plain) { console.error(`thunder try: "${rule.name}" can't be tried: ${rule.why}. Read it instead: thunder read ${file} --level flow --focus "${rule.name}"`); return 2; }
|
|
187
|
+
const plain = rule.plain;
|
|
188
|
+
const note = plain.needsReview?.some((n) => /inferred/.test(n)) ? 'Note: the code does not say what kind some values are; Thunder worked it out from how the rule uses them.' : null;
|
|
189
|
+
|
|
190
|
+
if (a.with.length) {
|
|
191
|
+
const w = parseWith(plain, a.with);
|
|
192
|
+
if (w.error) { console.error(`thunder try: ${w.error}`); return 2; }
|
|
193
|
+
const t = run(w.values);
|
|
194
|
+
console.log(a.json ? JSON.stringify({ rule: rule.name, file, ...t }, null, 2) : paint(renderTry(t)));
|
|
195
|
+
return 0;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Ask, one value at a time; read answers from the terminal (or from piped lines).
|
|
199
|
+
const rl = createInterface({ input, terminal: false });
|
|
200
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
201
|
+
const ask = async (q) => { output.write(q); const r = await lines.next(); if (r.done) return null; if (!input.isTTY) output.write(`${r.value}\n`); return r.value; };
|
|
202
|
+
const say = (s = '') => output.write(`${paint(s, useColor(output))}\n`);
|
|
203
|
+
say(`⚡ Let's try "${rule.name}" from ${basename(file)}.`);
|
|
204
|
+
say(`It takes: ${plain.inputs.map((i) => `${inputName(i)} (${kindText[i.kind] ?? i.kind})`).join(', ')}`);
|
|
205
|
+
if (note) say(note);
|
|
206
|
+
for (;;) {
|
|
207
|
+
say('');
|
|
208
|
+
const values = {};
|
|
209
|
+
for (const i of plain.inputs) {
|
|
210
|
+
for (;;) {
|
|
211
|
+
const raw = await ask(`${inputName(i).charAt(0).toUpperCase()}${inputName(i).slice(1)}? > `);
|
|
212
|
+
if (raw == null) { rl.close(); say(''); return 0; }
|
|
213
|
+
const v = parseValue(i, raw);
|
|
214
|
+
if (v.error) { say(v.error); continue; }
|
|
215
|
+
values[i.id] = v.value;
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
say('');
|
|
220
|
+
say(renderTry(run(values)));
|
|
221
|
+
say('');
|
|
222
|
+
const again = await ask('Try another? (y/n) > ');
|
|
223
|
+
if (again == null || !/^y/i.test(again.trim())) { rl.close(); return 0; }
|
|
224
|
+
}
|
|
225
|
+
}
|
package/src/why-cli.mjs
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
// thunder why: an AI agent's run explained in plain words (src/why.mjs, docs/why.md).
|
|
2
2
|
// thunder why <run.json> [--step n] [--run id] [--json]
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
|
-
import {
|
|
4
|
+
import { paint } from './term.mjs';
|
|
5
|
+
import { explainRun, renderWhy, renderFull, renderStep, toolAnnotations, EFFECT_KINDS } from './why.mjs';
|
|
5
6
|
|
|
6
|
-
const USAGE = `usage: thunder why <run.json> [--step n] [--run id] [--json]
|
|
7
|
+
const USAGE = `usage: thunder why <run.json> [--steps] [--step n] [--tools tools.json] [--allow read,send] [--run id] [--json]
|
|
7
8
|
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
|
+
and what went wrong. Nothing is run and no AI is used. Read "-" for standard input.
|
|
10
|
+
--steps every step, with what happened just before the problem
|
|
11
|
+
--tools tools.json the agent's MCP tool list: what each tool declares it does beats guessing from its name
|
|
12
|
+
--allow read,send flag anything else (kinds: ${EFFECT_KINDS.join(', ')}); exits 1 if the run went beyond it`;
|
|
9
13
|
|
|
10
14
|
export function whyMain(argv) {
|
|
11
|
-
const a = { _: [], json: false, step: null, run: null };
|
|
15
|
+
const a = { _: [], json: false, step: null, run: null, steps: false, tools: null, allow: null };
|
|
12
16
|
for (let i = 0; i < argv.length; i++) {
|
|
13
17
|
const x = argv[i];
|
|
14
18
|
if (x === '--json') a.json = true;
|
|
15
19
|
else if (x === '--step') a.step = argv[++i];
|
|
16
20
|
else if (x === '--run') a.run = argv[++i];
|
|
21
|
+
else if (x === '--steps') a.steps = true;
|
|
22
|
+
else if (x === '--tools') a.tools = argv[++i];
|
|
23
|
+
else if (x === '--allow') a.allow = String(argv[++i] ?? '').split(',').map((k) => k.trim().toLowerCase()).filter(Boolean);
|
|
17
24
|
else if (x === '--help' || x === '-h') { console.log(USAGE); return 0; }
|
|
18
25
|
else if (x.startsWith('--')) { console.error(`thunder why: there is no option ${x}.\n${USAGE}`); return 2; }
|
|
19
26
|
else a._.push(x);
|
|
@@ -23,9 +30,12 @@ export function whyMain(argv) {
|
|
|
23
30
|
let text;
|
|
24
31
|
try { text = readFileSync(a._[0] === '-' ? 0 : a._[0], 'utf8'); }
|
|
25
32
|
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
|
|
33
|
+
if (a.allow) { const bad = a.allow.filter((k) => !EFFECT_KINDS.includes(k)); if (bad.length || !a.allow.length) { console.error(`thunder why: --allow takes kinds from: ${EFFECT_KINDS.join(', ')}.${bad.length ? ` There is no "${bad[0]}".` : ''}`); return 2; } }
|
|
34
|
+
let tools = null;
|
|
35
|
+
if (a.tools) { try { tools = toolAnnotations(readFileSync(a.tools, 'utf8')); } catch (e) { console.error(`thunder why: couldn't read the tool list ${a.tools}: ${e.code === 'ENOENT' ? 'there is no such file' : e.message}.`); return 2; } }
|
|
36
|
+
const r = explainRun(text, { run: a.run, tools, allow: a.allow });
|
|
27
37
|
if (!r.ok) { console.error(`thunder why: ${r.why}`); return 2; }
|
|
28
38
|
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;
|
|
39
|
+
else console.log(paint(a.step != null ? renderStep(r, a.step) : a.steps ? renderFull(r) : renderWhy(r, { file: a._[0] === '-' ? '-' : a._[0] })));
|
|
40
|
+
return r.notAllowed?.length ? 1 : 0;
|
|
31
41
|
}
|
package/src/why.d.mts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
// Thunder Why: an AI agent's run explained in plain words (docs/why.md).
|
|
2
|
+
export type EffectKind = 'money' | 'delete' | 'send' | 'create' | 'change' | 'read';
|
|
3
|
+
export const EFFECT_KINDS: EffectKind[];
|
|
4
|
+
export interface WhyEffect { step: number; kind: EffectKind; basis: 'declared' | 'method' | 'operation' | 'name' | 'kind'; text: string; name: string; worked: boolean; tries: number }
|
|
2
5
|
export interface WhyStep {
|
|
3
6
|
n: number; depth: number;
|
|
4
7
|
kind: 'agent' | 'model' | 'tool' | 'http' | 'db' | 'retrieve' | 'other';
|
|
5
8
|
text: string; outcome: string; sentence: string; failed: boolean;
|
|
6
|
-
effect:
|
|
9
|
+
effect: EffectKind | 'unknown' | 'none';
|
|
7
10
|
tries: number; atMs: number | null; durationMs: number | null; span: string;
|
|
8
11
|
details: Record<string, unknown>;
|
|
9
12
|
}
|
|
@@ -12,17 +15,24 @@ export interface WhyRun {
|
|
|
12
15
|
status: 'finished' | 'finished-with-problems' | 'stopped';
|
|
13
16
|
headline: string; asked: string | null; answered: string | null;
|
|
14
17
|
problem: null | {
|
|
15
|
-
step: number; inside: { step: number; text: string } | null; what: string; tries: number;
|
|
18
|
+
step: number; short: string; inside: { step: number; text: string } | null; what: string; tries: number;
|
|
16
19
|
before: { step: number; text: string } | null; wouldHaveChanged: string; next: string | null;
|
|
17
20
|
details: Record<string, unknown>;
|
|
18
21
|
};
|
|
19
|
-
recovered: Array<{ step: number; text: string }>;
|
|
20
|
-
warnings: Array<{ step: number; text: string }>;
|
|
21
|
-
|
|
22
|
+
recovered: Array<{ step: number; text: string; short: string }>;
|
|
23
|
+
warnings: Array<{ step: number; text: string; short: string }>;
|
|
24
|
+
/** Everything the run did to the world (outermost steps only). */
|
|
25
|
+
effects: WhyEffect[];
|
|
26
|
+
/** The effects that are not reads. */
|
|
27
|
+
changes: WhyEffect[];
|
|
28
|
+
allowed?: EffectKind[];
|
|
29
|
+
notAllowed?: WhyEffect[];
|
|
22
30
|
unknown: Array<{ step: number; text: string }>;
|
|
23
31
|
durationMs: number | null; steps: WhyStep[]; spanCount: number;
|
|
24
32
|
}
|
|
25
|
-
export function explainRun(input: string | object, options?: { run?: string }): WhyRun | { ok: false; why: string };
|
|
26
|
-
export function
|
|
33
|
+
export function explainRun(input: string | object, options?: { run?: string; tools?: Map<string, object | null> | null; allow?: EffectKind[] | null }): WhyRun | { ok: false; why: string };
|
|
34
|
+
export function toolAnnotations(input: string | object): Map<string, object | null>;
|
|
35
|
+
export function renderWhy(run: WhyRun | { ok: false; why: string }, options?: { file?: string }): string;
|
|
36
|
+
export function renderFull(run: WhyRun | { ok: false; why: string }): string;
|
|
27
37
|
export function renderStep(run: WhyRun | { ok: false; why: string }, n: number | string): string;
|
|
28
38
|
export function plainError(error?: { type?: string | null; message?: string | null; status?: number | string | null; finish?: string | null }): { what: string; next: string | null };
|
package/src/why.mjs
CHANGED
|
@@ -142,38 +142,64 @@ function messagesOf(a, which) {
|
|
|
142
142
|
return out;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
-
|
|
146
|
-
|
|
145
|
+
// ── What a step does to the world ─────────────────────────────────────────────────────────────────────────────
|
|
146
|
+
// Kinds, most serious first. A step's effect comes from the strongest evidence the record has:
|
|
147
|
+
// declared the tool says so (MCP annotations from --tools, or a thunder.effect attribute on the span)
|
|
148
|
+
// method the HTTP request method operation the database operation
|
|
149
|
+
// name the tool's name: every word counts, and the most serious one wins (get_and_delete deletes)
|
|
150
|
+
export const EFFECT_KINDS = ['money', 'delete', 'send', 'create', 'change', 'read'];
|
|
151
|
+
const VERBS = {
|
|
152
|
+
money: 'charge pay payment refund transfer payout withdraw deposit purchase buy checkout bill',
|
|
153
|
+
delete: 'delete remove drop purge destroy erase truncate wipe unlink rm del',
|
|
154
|
+
send: 'send email mail notify message sms text tweet reply publish broadcast page post dm alert',
|
|
155
|
+
create: 'create add insert new make book reserve schedule upload register submit open issue generate',
|
|
156
|
+
change: 'update set edit modify change write save store cancel approve reject close assign grant revoke rename move archive restore reset deploy merge push apply patch enable disable mark replace upsert',
|
|
157
|
+
read: 'get list search find lookup look fetch read query retrieve check view show describe count load browse inspect peek verify validate calculate compute estimate summarize download scan',
|
|
158
|
+
};
|
|
159
|
+
const VERB_KIND = new Map();
|
|
160
|
+
for (const k of [...EFFECT_KINDS].reverse()) for (const v of VERBS[k].split(' ')) VERB_KIND.set(v, k);
|
|
161
|
+
|
|
162
|
+
/** MCP tool annotations (from --tools) as an effect kind, or null when they say nothing. */
|
|
163
|
+
function declaredFromAnnotations(ann) {
|
|
164
|
+
if (!ann || typeof ann !== 'object') return null;
|
|
165
|
+
if (ann.readOnlyHint === true) return 'read';
|
|
166
|
+
if (ann.readOnlyHint === false || ann.destructiveHint != null) return ann.destructiveHint === false ? 'change' : 'delete'; // the MCP default for a tool that writes is "may be destructive"
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
147
169
|
|
|
148
|
-
/**
|
|
149
|
-
function effectOf(s) {
|
|
170
|
+
/** What this step does to the world: { effect, basis, resource }. */
|
|
171
|
+
function effectOf(s, tools) {
|
|
150
172
|
if (s.kind === 'model' || s.kind === 'agent') return { effect: 'none', basis: 'kind' };
|
|
173
|
+
if (s.declared && EFFECT_KINDS.includes(s.declared)) return { effect: s.declared, basis: 'declared' };
|
|
174
|
+
if (s.kind === 'tool') {
|
|
175
|
+
const d = declaredFromAnnotations(tools?.get(s.tool));
|
|
176
|
+
if (d) return { effect: d, basis: 'declared' };
|
|
177
|
+
}
|
|
151
178
|
if (s.kind === 'retrieve') return { effect: 'read', basis: 'kind' };
|
|
152
179
|
if (s.kind === 'http') {
|
|
153
180
|
const m = String(s.method).toUpperCase();
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
return { effect: 'unknown', basis: 'method' };
|
|
181
|
+
const kind = { GET: 'read', HEAD: 'read', OPTIONS: 'read', POST: 'change', PUT: 'change', PATCH: 'change', DELETE: 'delete' }[m];
|
|
182
|
+
return { effect: kind ?? 'unknown', basis: 'method' };
|
|
157
183
|
}
|
|
158
184
|
if (s.kind === 'db') {
|
|
159
185
|
const op = String(s.dbOp || '').toUpperCase();
|
|
160
186
|
if (/^(SELECT|FIND|GET|SCAN|QUERY|COUNT|AGGREGATE|SHOW|DESCRIBE|EXPLAIN|MGET|HGET|HGETALL|EXISTS)/.test(op)) return { effect: 'read', basis: 'operation' };
|
|
161
|
-
if (/^(
|
|
187
|
+
if (/^(DELETE|DROP|TRUNCATE|DEL\b|DEL$|HDEL|UNLINK)/.test(op)) return { effect: 'delete', basis: 'operation' };
|
|
188
|
+
if (/^(INSERT|CREATE|LPUSH|RPUSH|SADD|XADD)/.test(op)) return { effect: 'create', basis: 'operation' };
|
|
189
|
+
if (/^(UPDATE|UPSERT|MERGE|REPLACE|ALTER|SET|HSET|PUT|INCR|DECR)/.test(op)) return { effect: 'change', basis: 'operation' };
|
|
162
190
|
return { effect: 'unknown', basis: 'operation' };
|
|
163
191
|
}
|
|
164
192
|
if (s.kind === 'tool') {
|
|
165
193
|
const words = String(s.tool).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
return { effect: 'unknown', basis: 'name' };
|
|
194
|
+
const kinds = words.map((w) => VERB_KIND.get(w)).filter(Boolean);
|
|
195
|
+
const worst = EFFECT_KINDS.find((k) => kinds.includes(k));
|
|
196
|
+
return { effect: worst ?? 'unknown', basis: 'name' };
|
|
171
197
|
}
|
|
172
198
|
return { effect: 'unknown', basis: 'kind' };
|
|
173
199
|
}
|
|
174
200
|
|
|
175
201
|
/** A raw span as a step: what kind of thing happened, with the facts the story needs. */
|
|
176
|
-
function stepOf(r) {
|
|
202
|
+
function stepOf(r, tools) {
|
|
177
203
|
const a = r.attrs;
|
|
178
204
|
const op = String(a['gen_ai.operation.name'] ?? '').toLowerCase();
|
|
179
205
|
const oi = String(a['openinference.span.kind'] ?? '').toUpperCase();
|
|
@@ -192,6 +218,7 @@ function stepOf(r) {
|
|
|
192
218
|
durationMs: r.start != null && r.end != null && r.end >= r.start ? (r.end - r.start) / 1e6 : null,
|
|
193
219
|
kind,
|
|
194
220
|
};
|
|
221
|
+
if (a['thunder.effect'] != null) s.declared = String(a['thunder.effect']).toLowerCase();
|
|
195
222
|
if (kind === 'agent') s.agent = a['gen_ai.agent.name'] ?? (r.name.replace(/^invoke_agent\s*/i, '') || r.name);
|
|
196
223
|
if (kind === 'tool') { s.tool = String(tool ?? r.name.replace(/^execute_tool\s*/i, '')); s.args = a['gen_ai.tool.call.arguments'] ?? a['tool.parameters'] ?? a['input.value']; s.result = a['gen_ai.tool.call.result'] ?? a['output.value']; }
|
|
197
224
|
if (kind === 'model') {
|
|
@@ -228,7 +255,7 @@ function stepOf(r) {
|
|
|
228
255
|
};
|
|
229
256
|
}
|
|
230
257
|
if (kind === 'model' && !s.failed && ['length', 'max_tokens', 'content_filter'].includes(String(s.finish))) s.warning = String(s.finish);
|
|
231
|
-
Object.assign(s, effectOf(s));
|
|
258
|
+
Object.assign(s, effectOf(s, tools));
|
|
232
259
|
return s;
|
|
233
260
|
}
|
|
234
261
|
|
|
@@ -300,6 +327,15 @@ function outcome(s) {
|
|
|
300
327
|
if (s.kind === 'model' || s.kind === 'agent') return '';
|
|
301
328
|
return 'it worked';
|
|
302
329
|
}
|
|
330
|
+
/** A step's name, for short lines: "refund_payment", pay.example.com, the database. */
|
|
331
|
+
const nameOf = (s) => s.kind === 'tool' ? `"${s.tool}"` : s.kind === 'http' ? (() => { try { return new URL(s.url).host; } catch { return s.url || s.name; } })() : s.kind === 'db' ? `the database${s.table ? ` (${s.table})` : ''}` : s.kind === 'model' ? 'the AI' : `"${s.name}"`;
|
|
332
|
+
/** One short line for a step that had trouble but carried on, or a problem: "\"search_web\" worked on the second try; …". */
|
|
333
|
+
function shortTrouble(s) {
|
|
334
|
+
const first = (s.tries || []).find((t) => t.failed);
|
|
335
|
+
if (!s.failed && first) return `${nameOf(s)} worked on the ${ordinal(s.tries.length)} try; the first time, ${lower(plainError(first.error).what)}`;
|
|
336
|
+
return `${nameOf(s)}: ${lower(plainError({ ...s.error, finish: s.finish ?? s.warning }).what)}`;
|
|
337
|
+
}
|
|
338
|
+
|
|
303
339
|
const sentence = (s) => {
|
|
304
340
|
const o = outcome(s);
|
|
305
341
|
const tries = s.tries?.length > 1 && !(s.tries || []).every((t, i, xs) => i === xs.length - 1 || t.failed) ? '' : s.tries?.length > 1 && s.failed ? ` (${s.tries.length} tries)` : '';
|
|
@@ -353,7 +389,14 @@ const flatten = (steps, depth = 0, out = []) => { for (const s of steps) { out.p
|
|
|
353
389
|
* Explain one agent run. `input` is the record's text (or parsed JSON). Options: { run } picks a trace id when the
|
|
354
390
|
* record holds several runs (default: the latest).
|
|
355
391
|
*/
|
|
356
|
-
|
|
392
|
+
/** MCP tool definitions (a tools/list result, or an array of tools) as name -> annotations. */
|
|
393
|
+
export function toolAnnotations(input) {
|
|
394
|
+
const v = typeof input === 'string' ? JSON.parse(input) : input;
|
|
395
|
+
const list = Array.isArray(v) ? v : v?.tools ?? v?.result?.tools ?? [];
|
|
396
|
+
return new Map(list.filter((t) => t && t.name).map((t) => [String(t.name), t.annotations ?? null]));
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function explainRun(input, { run, tools = null, allow = null } = {}) {
|
|
357
400
|
const raw = collectSpans(parseInput(input)).filter((r) => r.id);
|
|
358
401
|
if (!raw.length) {
|
|
359
402
|
return { ok: false, why: 'Thunder found no steps in this file. It reads OpenTelemetry traces: an OTLP JSON export, the collector\'s file exporter, or the Python console exporter.' };
|
|
@@ -367,7 +410,7 @@ export function explainRun(input, { run } = {}) {
|
|
|
367
410
|
chosen = runs.find((r) => r.id.startsWith(String(run).toLowerCase()));
|
|
368
411
|
if (!chosen) return { ok: false, why: `No run in this file starts with ${run}. The runs are: ${runs.map((r) => r.id.slice(0, 8)).join(', ')}.` };
|
|
369
412
|
}
|
|
370
|
-
const all = chosen.spans.map(stepOf);
|
|
413
|
+
const all = chosen.spans.map((r) => stepOf(r, tools));
|
|
371
414
|
const t0 = Number.isFinite(chosen.start) ? chosen.start : null;
|
|
372
415
|
const tree = arrange(all);
|
|
373
416
|
const flat = flatten(tree);
|
|
@@ -397,6 +440,7 @@ export function explainRun(input, { run } = {}) {
|
|
|
397
440
|
const parentStep = flat.map((f) => f.step).find((s) => s.id === problemStep.parent && MEANINGFUL.has(s.kind) && s.kind !== 'agent');
|
|
398
441
|
problem = {
|
|
399
442
|
step: problemStep.n,
|
|
443
|
+
short: `${lower(plain.what).replace(/\.$/, '')}${problemStep.kind === 'http' ? ` (${nameOf(problemStep)})` : ''}${parentStep?.kind === 'tool' ? `, while using "${parentStep.tool}"` : problemStep.kind === 'tool' ? `, in ${nameOf(problemStep)}` : ''}${tries > 1 ? `. It tried ${tries} times` : ''}.`,
|
|
400
444
|
inside: parentStep ? { step: parentStep.n, text: parentStep.kind === 'tool' ? `"${parentStep.tool}"` : doing(parentStep) } : null,
|
|
401
445
|
what: `${doing(problemStep)}: ${lower(plain.what)}`.replace(/\.?$/, '.'),
|
|
402
446
|
tries,
|
|
@@ -410,14 +454,19 @@ export function explainRun(input, { run } = {}) {
|
|
|
410
454
|
}
|
|
411
455
|
|
|
412
456
|
const stepById = new Map(flat.map((f) => [f.step.id, f.step]));
|
|
413
|
-
const underChange = (s) => { for (let p = stepById.get(s.parent); p; p = stepById.get(p.parent)) if (p.effect
|
|
414
|
-
|
|
415
|
-
|
|
457
|
+
const underChange = (s) => { for (let p = stepById.get(s.parent); p; p = stepById.get(p.parent)) if ((EFFECT_KINDS.includes(p.effect) && p.effect !== 'read') || p.effect === 'unknown') return true; return false; };
|
|
458
|
+
// Effects: what the run did to the world, outermost step only (a tool's own request is not counted again).
|
|
459
|
+
const effects = flat.map((f) => f.step).filter((s) => EFFECT_KINDS.includes(s.effect) && !underChange(s)).map((s) => ({
|
|
460
|
+
step: s.n, kind: s.effect, basis: s.basis, text: doing(s), name: s.tool ?? (s.kind === 'http' ? `${s.method} ${hostPath(s.url)}` : s.kind === 'db' ? `${s.db} ${s.table ?? ''}`.trim() : s.name),
|
|
461
|
+
worked: !s.failed, tries: s.tries?.length ?? 1,
|
|
416
462
|
}));
|
|
463
|
+
const changes = effects.filter((e) => e.kind !== 'read');
|
|
464
|
+
const allowed = allow ? new Set(allow) : null;
|
|
465
|
+
const notAllowed = allowed ? effects.filter((e) => !allowed.has(e.kind)) : [];
|
|
417
466
|
const unknown = flat.map((f) => f.step).filter((s) => s.effect === 'unknown' && !underChange(s)).map((s) => ({ step: s.n, text: doing(s) }));
|
|
418
467
|
const recovered = stopped ? [] : [...failedSteps, ...flat.map((f) => f.step).filter((s) => !s.failed && (s.tries || []).some((t) => t.failed))]
|
|
419
|
-
.sort((x, y) => x.n - y.n).map((s) => ({ step: s.n, text: sentence(s) }));
|
|
420
|
-
const warnings = flat.map((f) => f.step).filter((s) => s.warning).map((s) => ({ step: s.n, text: plainError({ finish: s.warning }).what }));
|
|
468
|
+
.sort((x, y) => x.n - y.n).map((s) => ({ step: s.n, text: sentence(s), short: shortTrouble(s) }));
|
|
469
|
+
const warnings = flat.map((f) => f.step).filter((s) => s.warning).map((s) => ({ step: s.n, text: plainError({ finish: s.warning }).what, short: plainError({ finish: s.warning }).what }));
|
|
421
470
|
|
|
422
471
|
const status = stopped ? 'stopped' : recovered.length || warnings.length ? 'finished-with-problems' : 'finished';
|
|
423
472
|
const who = agentName ? `The agent "${agentName}"` : 'The agent';
|
|
@@ -433,7 +482,8 @@ export function explainRun(input, { run } = {}) {
|
|
|
433
482
|
status, headline,
|
|
434
483
|
asked: ask ? short(hide(ask), 200) : null,
|
|
435
484
|
answered: !stopped && lastFinal ? short(hide(lastFinal.said), 200) : null,
|
|
436
|
-
problem, recovered, warnings, changes, unknown,
|
|
485
|
+
problem, recovered, warnings, effects, changes, unknown,
|
|
486
|
+
...(allowed ? { allowed: [...allowed], notAllowed } : {}),
|
|
437
487
|
durationMs,
|
|
438
488
|
steps: flat.map(({ step: s, depth }) => ({
|
|
439
489
|
n: s.n, depth, kind: s.kind, text: doing(s), outcome: outcome(s), sentence: sentence(s), failed: !!s.failed, effect: s.effect,
|
|
@@ -460,10 +510,44 @@ function detailsOf(s) {
|
|
|
460
510
|
// ── Printing ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
461
511
|
|
|
462
512
|
const at = (ms) => (ms == null ? '' : `+${(ms / 1000).toFixed(1)}s`);
|
|
463
|
-
const basisNote = { name:
|
|
513
|
+
const basisNote = { name: 'guessed from its name', declared: 'the tool says so', method: 'from the request method', operation: 'from the database operation' };
|
|
514
|
+
// What each kind of effect is called, as a past action and as an attempt.
|
|
515
|
+
const DID = { money: 'Moved money', delete: 'Deleted something', send: 'Sent something', create: 'Created something', change: 'Changed something', read: 'Read' };
|
|
516
|
+
const TRIED = { money: 'Tried to move money', delete: 'Tried to delete something', send: 'Tried to send something', create: 'Tried to create something', change: 'Tried to change something', read: 'Tried to read' };
|
|
517
|
+
const effectName = (e) => (/^[A-Z]+ /.test(e.name) ? e.name : `"${e.name}"`);
|
|
518
|
+
const effectLine = (e) => `${e.worked ? DID[e.kind] : TRIED[e.kind]} with ${effectName(e)}${e.basis === 'name' || e.basis === 'declared' ? ` (${basisNote[e.basis]})` : ''}.${e.worked ? '' : ' It did not go through, but may have partly happened.'}`;
|
|
519
|
+
const andList = (xs) => (xs.length > 1 ? `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}` : xs.join(''));
|
|
520
|
+
|
|
521
|
+
/** The short story: a few lines anyone can read. Every step is one flag away (--steps). */
|
|
522
|
+
export function renderWhy(r, { file = 'run.json' } = {}) {
|
|
523
|
+
if (!r.ok) return r.why;
|
|
524
|
+
const who = r.headline.match(/^The agent( "[^"]+")?/)[0];
|
|
525
|
+
const took = r.durationMs != null ? ` ${r.status === 'stopped' ? 'after' : 'in'} ${secs(r.durationMs)}` : '';
|
|
526
|
+
const head = r.status === 'stopped' ? `✗ ${who} stopped${took}.`
|
|
527
|
+
: r.status === 'finished-with-problems' ? `✓ ${who} finished${took}, with ${r.recovered.length + r.warnings.length === 1 ? 'one problem' : `${r.recovered.length + r.warnings.length} problems`} along the way.`
|
|
528
|
+
: `✓ ${who} finished${took}.`;
|
|
529
|
+
const L = [head];
|
|
530
|
+
if (r.asked) L.push(` Asked: ${quote(r.asked, 100)}`);
|
|
531
|
+
if (r.answered) L.push(` Answered: ${quote(r.answered, 100)}`);
|
|
532
|
+
L.push('');
|
|
533
|
+
const row = (label, text) => L.push(` ${label.padEnd(9)} ${text}`);
|
|
534
|
+
if (r.problem) {
|
|
535
|
+
const p = r.problem;
|
|
536
|
+
row('Why:', p.short.charAt(0).toUpperCase() + p.short.slice(1));
|
|
537
|
+
}
|
|
538
|
+
for (const x of [...r.recovered, ...r.warnings]) row('Problem:', `${x.short.charAt(0).toUpperCase()}${x.short.slice(1)}`.replace(/\.?$/, '.'));
|
|
539
|
+
const did = r.changes.length ? r.changes.map(effectLine) : [r.effects.length ? 'Only read things.' : 'Nothing that changes anything.'];
|
|
540
|
+
did.forEach((t, i) => row(i ? '' : 'Did:', t));
|
|
541
|
+
if (r.unknown.length) row('Unclear:', `can't tell what ${r.unknown.map((u) => u.text.replace(/^Used /, '').split(' with ')[0]).join(', ')} does.`);
|
|
542
|
+
for (const e of r.notAllowed ?? []) row('Not OK:', `${effectName(e)} ${e.worked ? DID[e.kind].toLowerCase() : TRIED[e.kind].toLowerCase()}. Only ${andList(r.allowed)} ${r.allowed.length === 1 ? 'is' : 'are'} allowed.`);
|
|
543
|
+
if (r.problem?.next) row('Next:', r.problem.next);
|
|
544
|
+
L.push('', ` Every step: thunder why ${file} --steps`);
|
|
545
|
+
if (r.otherRuns.length) L.push(` This file has ${r.otherRuns.length + 1} runs; this is the latest. Others: --run ${r.otherRuns.map((x) => x.slice(0, 8)).join(', ')}`);
|
|
546
|
+
return L.join('\n');
|
|
547
|
+
}
|
|
464
548
|
|
|
465
|
-
/** The story
|
|
466
|
-
export function
|
|
549
|
+
/** The whole story: what happened, what went wrong, what changed, step by step, how sure. */
|
|
550
|
+
export function renderFull(r) {
|
|
467
551
|
if (!r.ok) return r.why;
|
|
468
552
|
const L = [];
|
|
469
553
|
L.push('What happened');
|
|
@@ -488,13 +572,10 @@ export function renderWhy(r) {
|
|
|
488
572
|
L.push('');
|
|
489
573
|
}
|
|
490
574
|
|
|
491
|
-
L.push('What it
|
|
492
|
-
if (!r.changes.length) L.push(` Nothing
|
|
493
|
-
for (const c of r.changes) {
|
|
494
|
-
|
|
495
|
-
L.push(c.worked ? ` Step ${c.step}. Changed: ${c.text}${how}.`
|
|
496
|
-
: ` Step ${c.step}. Tried to change, but it did not work: ${c.text}${how}. The record can't show whether anything was partly done.`);
|
|
497
|
-
}
|
|
575
|
+
L.push('What it did');
|
|
576
|
+
if (!r.changes.length) L.push(` Nothing that changes anything${r.unknown.length ? ', but some steps could not be judged (below)' : ''}.`);
|
|
577
|
+
for (const c of r.changes) L.push(` Step ${c.step}. ${effectLine(c)}`);
|
|
578
|
+
for (const e of r.notAllowed ?? []) L.push(` Not allowed: step ${e.step} ${DID[e.kind].toLowerCase()}${e.worked ? '' : ' (tried)'}. Allowed: ${r.allowed.join(', ')}.`);
|
|
498
579
|
if (r.unknown.length) L.push(` Could not judge whether ${r.unknown.length === 1 ? 'this step changes' : 'these steps change'} anything: ${r.unknown.map((u) => `step ${u.step} (${u.text})`).join('; ')}.`);
|
|
499
580
|
L.push('');
|
|
500
581
|
|