@skillstech/thunderlang 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/core.cjs +8381 -6614
- package/dist/index.cjs +2672 -1710
- package/package.json +1 -1
- package/src/anchor.d.mts +12 -0
- package/src/anchor.mjs +127 -0
- package/src/cli.mjs +104 -38
- package/src/codegen.mjs +27 -9
- package/src/core.d.ts +10 -0
- package/src/core.mjs +11 -0
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +23 -0
- package/src/index.mjs +11 -0
- package/src/mcp.mjs +19 -32
- package/src/obligations.d.mts +9 -0
- package/src/obligations.mjs +35 -0
- package/src/plain-contract.d.mts +30 -0
- package/src/plain-contract.mjs +339 -0
- package/src/promote.mjs +19 -5
- package/src/read.mjs +142 -7
- package/src/review-atlas.d.mts +19 -0
- package/src/review-atlas.mjs +136 -0
- package/src/steps.d.mts +2 -0
- package/src/steps.mjs +297 -0
- package/src/target-types.mjs +39 -4
- package/src/testing.mjs +12 -9
- package/src/thunder-repo.mjs +96 -0
- package/src/write.d.mts +24 -0
- package/src/write.mjs +263 -0
package/src/write.mjs
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Thunder write: change a rule in the Thunder picture and only the matching code changes.
|
|
2
|
+
//
|
|
3
|
+
// A recovered decision reads "if amount is at most 100, the answer is Approve". Thunder write lets a person
|
|
4
|
+
// change a number (100 -> 75), a comparison (at most -> under), a text value ("gold" -> "platinum"), or an
|
|
5
|
+
// answer (Approve -> Review), and writes exactly those characters back into the original file, keeping the
|
|
6
|
+
// file's own spelling (=== stays ===, 100.0 stays a decimal, 100m keeps its suffix, quotes keep their style).
|
|
7
|
+
//
|
|
8
|
+
// Every write is checked by reading the file again: the edited rule must now read exactly as intended, and
|
|
9
|
+
// every other rule, answer, and function in the file must read exactly as before. Otherwise nothing changes.
|
|
10
|
+
// It also runs the old and the new rule on boundary inputs and lists the cases whose answer changes.
|
|
11
|
+
//
|
|
12
|
+
// Deterministic and browser-safe. It edits text only; it never runs the code it edits.
|
|
13
|
+
import { readCode, sayCondition } from './read.mjs';
|
|
14
|
+
import { tokenize } from './expr.mjs';
|
|
15
|
+
import { recoverModel } from './promote.mjs';
|
|
16
|
+
|
|
17
|
+
export const WRITE_SCHEMA = 'thunder-write-v1';
|
|
18
|
+
|
|
19
|
+
const CMP = new Set(['<', '<=', '>', '>=', '==', '!=']);
|
|
20
|
+
const editable = (t) => t.t === 'num' || t.t === 'str' || (t.t === 'op' && CMP.has(t.v));
|
|
21
|
+
const category = (t) => (t.t === 'op' ? 'cmp' : t.t);
|
|
22
|
+
const sameTok = (a, b) => a.t === b.t && a.v === b.v;
|
|
23
|
+
const normWhen = (w) => tokenize(w).map((t) => (t.t === 'str' ? JSON.stringify(t.v) : String(t.v))).join(' ');
|
|
24
|
+
|
|
25
|
+
const COMMENT = { python: ['#'], ruby: ['#'], php: ['#', '//', '/*'] };
|
|
26
|
+
const commentStarts = (language) => COMMENT[language] || ['//', '/*'];
|
|
27
|
+
|
|
28
|
+
/** Numbers, comparison operators, and text literals in a slice of the original file, with exact offsets. */
|
|
29
|
+
function scanSource(source, from, to, language) {
|
|
30
|
+
const out = [];
|
|
31
|
+
const starts = commentStarts(language);
|
|
32
|
+
let i = from;
|
|
33
|
+
while (i < to) {
|
|
34
|
+
const c = source[i];
|
|
35
|
+
if (starts.some((s) => source.startsWith(s, i))) {
|
|
36
|
+
if (source.startsWith('/*', i)) { const j = source.indexOf('*/', i + 2); i = j < 0 ? to : j + 2; }
|
|
37
|
+
else { const j = source.indexOf('\n', i); i = j < 0 ? to : j; }
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
41
|
+
let j = i + 1;
|
|
42
|
+
while (j < source.length && source[j] !== c && source[j] !== '\n') j += source[j] === '\\' ? 2 : 1;
|
|
43
|
+
if (source[j] === c) out.push({ t: 'str', v: source.slice(i + 1, j), start: i, end: j + 1, raw: source.slice(i, j + 1), quote: c });
|
|
44
|
+
i = j + 1;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (/[A-Za-z_$]/.test(c)) { // identifiers (and digits inside them) are not values
|
|
48
|
+
let j = i;
|
|
49
|
+
while (j < to && /[A-Za-z0-9_$]/.test(source[j])) j++;
|
|
50
|
+
out.push({ t: 'id', v: source.slice(i, j), start: i, end: j });
|
|
51
|
+
i = j;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (/[0-9]/.test(c)) {
|
|
55
|
+
const m = source.slice(i, to).match(/^[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9]+)?(f64|f32|i32|i64|u32|u64|[fFdDmMlLuU]{0,2})/);
|
|
56
|
+
const raw = m[0];
|
|
57
|
+
const suffix = m[3] || '';
|
|
58
|
+
out.push({ t: 'num', v: Number(raw.slice(0, raw.length - suffix.length).replace(/_/g, '')), start: i, end: i + raw.length, raw, suffix, decimal: !!m[1] });
|
|
59
|
+
i += raw.length;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const op = ['===', '!==', '<=>', '==', '!=', '<=', '>=', '->', '=>', '<<', '>>', '<-', '<', '>'].find((o) => source.startsWith(o, i));
|
|
63
|
+
if (op) {
|
|
64
|
+
if (!['<=>', '->', '=>', '<<', '>>', '<-'].includes(op)) out.push({ t: 'op', v: op === '===' ? '==' : op === '!==' ? '!=' : op, start: i, end: i + op.length, raw: op });
|
|
65
|
+
i += op.length;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
i++;
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const matches = (src, t) => src.t === t.t && (t.t === 'num' ? src.v === t.v : src.v === t.v);
|
|
74
|
+
|
|
75
|
+
/** Find the source tokens that are the rule's numbers, comparisons, and text, in order. */
|
|
76
|
+
function locate(srcToks, wanted) {
|
|
77
|
+
const found = [];
|
|
78
|
+
let k = 0;
|
|
79
|
+
for (const s of srcToks) {
|
|
80
|
+
if (k < wanted.length && matches(s, wanted[k])) { found.push(s); k++; }
|
|
81
|
+
}
|
|
82
|
+
return k === wanted.length ? found : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function spell(srcTok, next) {
|
|
86
|
+
if (next.t === 'op') {
|
|
87
|
+
if (srcTok.raw === '===' || srcTok.raw === '!==') return next.v === '==' ? '===' : next.v === '!=' ? '!==' : next.v;
|
|
88
|
+
return next.v;
|
|
89
|
+
}
|
|
90
|
+
if (next.t === 'num') {
|
|
91
|
+
let s = String(next.v);
|
|
92
|
+
if (srcTok.decimal && Number.isInteger(next.v)) s += '.0';
|
|
93
|
+
return s + srcTok.suffix;
|
|
94
|
+
}
|
|
95
|
+
return srcTok.quote + next.v + srcTok.quote;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lineStartsOf = (source) => { const out = [0]; for (let i = 0; i < source.length; i++) if (source[i] === '\n') out.push(i + 1); return out; };
|
|
99
|
+
|
|
100
|
+
function findDecision(reading, name, line) {
|
|
101
|
+
const ds = reading.items.filter((i) => i.kind === 'decision' && i.name === name);
|
|
102
|
+
if (!ds.length) return null;
|
|
103
|
+
if (line == null) return ds[0];
|
|
104
|
+
return ds.reduce((best, d) => (Math.abs(d.line - line) < Math.abs(best.line - line) ? d : best));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The character range of a rule (its condition line through the line before the next rule or the fallback).
|
|
108
|
+
function ruleRegion(source, decision, index) {
|
|
109
|
+
const starts = lineStartsOf(source);
|
|
110
|
+
const lines = [...decision.rules.map((r) => r.line), decision.otherwise.line];
|
|
111
|
+
const first = index === 'otherwise' ? decision.otherwise.line : decision.rules[index].line;
|
|
112
|
+
const later = lines.filter((l) => l > first);
|
|
113
|
+
const last = index === 'otherwise' ? first : Math.max(first, (later.length ? Math.min(...later) : first + 1) - 1);
|
|
114
|
+
return [starts[first - 1] ?? source.length, starts[last] != null ? starts[last] - 1 : source.length];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const view = (it) => JSON.stringify({ kind: it.kind, name: it.name, says: it.says, thunder: it.thunder, rules: it.rules?.map((r) => [r.when, r.result]), otherwise: it.otherwise?.result, guards: it.guards?.map((g) => g.says ?? g.when) });
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Change one rule of a recovered decision and write it back to the original code.
|
|
121
|
+
*
|
|
122
|
+
* rule: 1-based rule number, or 'otherwise' for the fallback answer.
|
|
123
|
+
* when: the rule's new condition, in Thunder form (amount < 75). Numbers, comparisons, and text may change.
|
|
124
|
+
* answer: the rule's new answer (Review).
|
|
125
|
+
*
|
|
126
|
+
* Returns { schema, ok, source, problems, change, before, after, cases }. When ok is false, `source` is the
|
|
127
|
+
* original, untouched, and `problems` says why in plain words.
|
|
128
|
+
*/
|
|
129
|
+
export function writeRule({ source, language, file = '', decision: name, line = null, rule, when = null, answer = null }) {
|
|
130
|
+
const fail = (...problems) => ({ schema: WRITE_SCHEMA, ok: false, source, problems });
|
|
131
|
+
if (when == null && answer == null) return fail('Say what to change: a new condition (when) or a new answer.');
|
|
132
|
+
const reading = readCode(source, { language, file });
|
|
133
|
+
const lang = reading.language;
|
|
134
|
+
const d = findDecision(reading, name, line);
|
|
135
|
+
if (!d) return fail(`No decision named ${name} was found. Thunder write changes decisions: functions that choose between fixed answers.`);
|
|
136
|
+
const index = rule === 'otherwise' ? 'otherwise' : Number(rule) - 1;
|
|
137
|
+
if (index !== 'otherwise' && !(Number.isInteger(index) && d.rules[index])) return fail(`${name} has ${d.rules.length} rule${d.rules.length === 1 ? '' : 's'}; there is no rule ${rule}.`);
|
|
138
|
+
if (index === 'otherwise' && when != null) return fail('The fallback answer has no condition to change. Change its answer instead.');
|
|
139
|
+
const target = index === 'otherwise' ? d.otherwise : d.rules[index];
|
|
140
|
+
const [from, to] = ruleRegion(source, d, index);
|
|
141
|
+
const srcToks = scanSource(source, from, to, lang);
|
|
142
|
+
const edits = []; // { start, end, text }
|
|
143
|
+
|
|
144
|
+
// 1. The condition: only numbers, comparisons, and text values may change; the shape must stay the same.
|
|
145
|
+
let newWhen = target.when;
|
|
146
|
+
if (when != null) {
|
|
147
|
+
let oldT, newT;
|
|
148
|
+
try { oldT = tokenize(target.when); newT = tokenize(when); } catch (e) { return fail(`The new condition could not be read: ${e.message}`); }
|
|
149
|
+
const structural = oldT.length !== newT.length || oldT.some((t, i) => !sameTok(t, newT[i]) && !(editable(t) && editable(newT[i]) && category(t) === category(newT[i])));
|
|
150
|
+
if (structural) return fail(`Thunder write can change a number, a comparison, or a text value in a rule. "${when}" also changes the rule's shape (names, and/or, or parentheses). Use Propose rule change for that.`);
|
|
151
|
+
const wanted = oldT.filter(editable);
|
|
152
|
+
const found = locate(srcToks, wanted);
|
|
153
|
+
if (!found) return fail(`The values in "${sayCondition(target.when)}" could not be found exactly in the code at line ${target.line}, so it is not safe to write them back.`);
|
|
154
|
+
let k = 0;
|
|
155
|
+
oldT.forEach((t, i) => {
|
|
156
|
+
if (!editable(t)) return;
|
|
157
|
+
const s = found[k++];
|
|
158
|
+
const next = newT[i];
|
|
159
|
+
if (sameTok(t, next)) return;
|
|
160
|
+
if (next.t === 'str' && (next.v.includes(s.quote) || next.v.includes('\\'))) return edits.push({ bad: `The text ${JSON.stringify(next.v)} contains a quote or backslash; write it in the code directly.` });
|
|
161
|
+
edits.push({ start: s.start, end: s.end, text: spell(s, next), was: s.raw });
|
|
162
|
+
});
|
|
163
|
+
newWhen = normWhen(when);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// 2. The answer: reuse a spelling this function already returns, or change the text of a string answer.
|
|
167
|
+
if (answer != null && answer !== target.result) {
|
|
168
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(answer)) return fail(`The answer must be a name such as Approve or Review; "${answer}" is not.`);
|
|
169
|
+
const reads = (t, result) => (t.t === 'str' && t.v === result) || (t.t === 'id' && t.v === result);
|
|
170
|
+
const sites = srcToks.filter((t) => reads(t, target.result));
|
|
171
|
+
if (sites.length !== 1) return fail(`The answer ${target.result} could not be found exactly once near line ${target.line}, so it is not safe to change.`);
|
|
172
|
+
const site = sites[0];
|
|
173
|
+
// An answer spelled elsewhere in this decision, for example Decision.REVIEW or "Review".
|
|
174
|
+
const others = [...d.rules.map((_, i) => i), 'otherwise'].filter((i) => i !== index && (i === 'otherwise' ? d.otherwise : d.rules[i]).result === answer);
|
|
175
|
+
let text = null;
|
|
176
|
+
for (const i of others) {
|
|
177
|
+
const [a, b] = ruleRegion(source, d, i);
|
|
178
|
+
const t = scanSource(source, a, b, lang).find((x) => reads(x, answer));
|
|
179
|
+
if (t && t.t === site.t) { text = t.raw ?? t.v; break; }
|
|
180
|
+
}
|
|
181
|
+
if (text == null && site.t === 'str') text = site.quote + answer + site.quote;
|
|
182
|
+
if (text == null) return fail(`${name} does not return ${answer} anywhere yet, and its answers are code names (such as ${site.v}), so Thunder write will not invent one. Add ${answer} in the code first, or use Propose rule change.`);
|
|
183
|
+
edits.push({ start: site.start, end: site.end, text, was: site.raw ?? site.v });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const bad = edits.find((e) => e.bad);
|
|
187
|
+
if (bad) return fail(bad.bad);
|
|
188
|
+
const real = edits.filter((e) => source.slice(e.start, e.end) !== e.text).sort((a, b) => b.start - a.start);
|
|
189
|
+
if (!real.length) return fail('Nothing would change: the rule already reads that way.');
|
|
190
|
+
let next = source;
|
|
191
|
+
for (const e of real) next = next.slice(0, e.start) + e.text + next.slice(e.end);
|
|
192
|
+
|
|
193
|
+
// 3. Verify by reading the file again.
|
|
194
|
+
const problems = [];
|
|
195
|
+
let after;
|
|
196
|
+
try { after = readCode(next, { language: lang, file }); } catch (e) { return fail(`The changed file could not be read: ${e.message}`); }
|
|
197
|
+
const d2 = findDecision(after, name, d.line);
|
|
198
|
+
if (!d2) return fail(`${name} is no longer read as a decision after the change.`);
|
|
199
|
+
const wantResult = answer ?? target.result;
|
|
200
|
+
if (d2.rules.length !== d.rules.length) problems.push('The number of rules changed.');
|
|
201
|
+
d.rules.forEach((r, i) => {
|
|
202
|
+
const r2 = d2.rules[i];
|
|
203
|
+
if (!r2) return;
|
|
204
|
+
const w = i === index ? newWhen : normWhen(r.when);
|
|
205
|
+
const res = i === index ? wantResult : r.result;
|
|
206
|
+
if (normWhen(r2.when) !== w) problems.push(`Rule ${i + 1} reads "${sayCondition(r2.when)}" after the change, not "${sayCondition(w)}".`);
|
|
207
|
+
if (r2.result !== res) problems.push(`Rule ${i + 1} answers ${r2.result} after the change, not ${res}.`);
|
|
208
|
+
});
|
|
209
|
+
const wantOtherwise = index === 'otherwise' ? wantResult : d.otherwise.result;
|
|
210
|
+
if (d2.otherwise?.result !== wantOtherwise) problems.push(`The fallback answers ${d2.otherwise?.result} after the change, not ${wantOtherwise}.`);
|
|
211
|
+
const others = reading.items.filter((i) => i !== d), others2 = after.items.filter((i) => i !== d2);
|
|
212
|
+
if (others.length !== others2.length) problems.push('Another part of the file reads differently after the change.');
|
|
213
|
+
else others.forEach((o, i) => { if (view(o) !== view(others2[i])) problems.push(`${o.name} (line ${o.line}) reads differently after the change.`); });
|
|
214
|
+
if (problems.length) return fail(...problems);
|
|
215
|
+
|
|
216
|
+
const starts = lineStartsOf(source);
|
|
217
|
+
const lineOf = (off) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (starts[m] <= off) lo = m; else hi = m - 1; } return lo + 1; };
|
|
218
|
+
const change = real.slice().reverse().map((e) => ({ line: lineOf(e.start), column: e.start - starts[lineOf(e.start) - 1] + 1, before: e.was, after: e.text }));
|
|
219
|
+
const label = (r) => (r === 'otherwise' ? 'Otherwise' : `If ${sayCondition(r.when)}`);
|
|
220
|
+
const beforeRule = index === 'otherwise' ? `Otherwise, the answer is ${target.result}` : `${label(target)}, the answer is ${target.result}`;
|
|
221
|
+
const afterRule = index === 'otherwise' ? `Otherwise, the answer is ${wantResult}` : `If ${sayCondition(newWhen)}, the answer is ${wantResult}`;
|
|
222
|
+
return { schema: WRITE_SCHEMA, ok: true, source: next, problems: [], decision: name, rule: index === 'otherwise' ? 'otherwise' : index + 1, change, before: beforeRule, after: afterRule, cases: changedCases(d, d2) };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Run the old and the new decision on the same boundary inputs (both sides of every threshold, every text
|
|
227
|
+
* value) and list the inputs whose answer changes. This covers the inputs checked, not every possible input.
|
|
228
|
+
*/
|
|
229
|
+
export function changedCases(before, after) {
|
|
230
|
+
const a = recoverModel(before, { extraConditions: after.rules.map((r) => r.when) });
|
|
231
|
+
const b = recoverModel(after, { extraConditions: before.rules.map((r) => r.when) });
|
|
232
|
+
if (!a.ok || !b.ok) return { checked: 0, changed: [], note: `The cases could not be compared: ${(a.ok ? b : a).reason}` };
|
|
233
|
+
const lookup = new Map(b.all.map((x) => [JSON.stringify(x.a), x.r.result]));
|
|
234
|
+
const changed = [];
|
|
235
|
+
for (const x of a.all) {
|
|
236
|
+
const next = lookup.get(JSON.stringify(x.a));
|
|
237
|
+
if (next !== undefined && next !== x.r.result) changed.push({ inputs: x.a, before: x.r.result, after: next });
|
|
238
|
+
}
|
|
239
|
+
return { checked: a.all.length, changed, note: `Checked ${a.all.length} boundary input${a.all.length === 1 ? '' : 's'}; ${changed.length} now get${changed.length === 1 ? 's' : ''} a different answer. These are the values on each side of every limit, not every possible input.` };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const CMP_WORDS = { '<=': 'at most', '<': 'less than', '>=': 'at least', '>': 'more than', '==': 'is', '!=': 'is not' };
|
|
243
|
+
/** The comparisons a person can choose between, in plain words. */
|
|
244
|
+
export const COMPARISON_CHOICES = Object.entries(CMP_WORDS).map(([op, words]) => ({ op, words }));
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* A rule's condition split into the parts a person sees: names and words stay fixed; numbers, comparisons, and
|
|
248
|
+
* text values can change. Joining the parts back with `joinRuleParts` gives a condition `writeRule` accepts.
|
|
249
|
+
*/
|
|
250
|
+
export function ruleParts(when) {
|
|
251
|
+
return tokenize(when).map((t) => {
|
|
252
|
+
if (t.t === 'num') return { kind: 'number', value: t.v };
|
|
253
|
+
if (t.t === 'str') return { kind: 'text', value: t.v };
|
|
254
|
+
if (t.t === 'op' && CMP.has(t.v)) return { kind: 'comparison', value: t.v, words: CMP_WORDS[t.v] };
|
|
255
|
+
if (t.t === 'bool') return { kind: 'fixed', value: String(t.v), words: String(t.v) };
|
|
256
|
+
if (t.t === 'kw') return { kind: 'fixed', value: t.v, words: t.v };
|
|
257
|
+
return { kind: 'fixed', value: String(t.v), words: String(t.v) };
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function joinRuleParts(parts) {
|
|
262
|
+
return parts.map((p) => (p.kind === 'text' ? JSON.stringify(String(p.value)) : String(p.value))).join(' ').replace(/\( /g, '(').replace(/ \)/g, ')');
|
|
263
|
+
}
|