@skillstech/thunderlang 0.5.2 → 0.5.5
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 +132 -0
- package/dist/core.cjs +10204 -6621
- package/dist/index.cjs +3867 -1771
- package/package.json +1 -1
- package/src/anchor.d.mts +12 -0
- package/src/anchor.mjs +127 -0
- package/src/cli.mjs +148 -39
- package/src/codegen.mjs +27 -9
- package/src/core.d.ts +24 -0
- package/src/core.mjs +19 -1
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +26 -0
- package/src/index.mjs +14 -0
- package/src/mcp.mjs +19 -32
- package/src/model.d.mts +18 -0
- package/src/model.mjs +456 -0
- 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.d.mts +25 -1
- package/src/read.mjs +415 -23
- package/src/review-atlas.d.mts +19 -0
- package/src/review-atlas.mjs +136 -0
- package/src/same.d.mts +10 -0
- package/src/same.mjs +160 -0
- package/src/steps.d.mts +2 -0
- package/src/steps.mjs +599 -0
- package/src/target-types.mjs +39 -4
- package/src/testing.mjs +12 -9
- package/src/thunder-repo.mjs +96 -0
- package/src/thunderize.d.mts +14 -0
- package/src/thunderize.mjs +82 -0
- package/src/visual.d.mts +40 -0
- package/src/visual.mjs +304 -0
- package/src/write.d.mts +24 -0
- package/src/write.mjs +263 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { runTests } from './testing.mjs';
|
|
2
|
+
|
|
3
|
+
// One binding policy for CLI, MCP, website, and embedding products. A reference
|
|
4
|
+
// names a complete test target, not a substring, prose description, or similar name.
|
|
5
|
+
// "verified" is scoped to the declared cases; it says nothing about application code.
|
|
6
|
+
export function resolveObligations(ast) {
|
|
7
|
+
const tests = runTests(ast);
|
|
8
|
+
const byTarget = new Map();
|
|
9
|
+
for (const result of tests.results) {
|
|
10
|
+
const name = String(result.target).trim();
|
|
11
|
+
const previous = byTarget.get(name);
|
|
12
|
+
byTarget.set(name, { name, pass: (previous?.pass ?? true) && result.pass, cases: (previous?.cases ?? 0) + 1 });
|
|
13
|
+
}
|
|
14
|
+
const build = (kind, claim) => {
|
|
15
|
+
const verify = claim.verify || [];
|
|
16
|
+
const names = [...new Set(verify.map((v) => String(v).trim()))];
|
|
17
|
+
const evidence = names.map((name) => byTarget.get(name) || (name.startsWith('test ') ? byTarget.get(name.slice(5).trim()) : null) || { name, pass: null, cases: 0 });
|
|
18
|
+
const unresolved = evidence.filter((e) => e.pass === null).map((e) => e.name);
|
|
19
|
+
const status = !names.length ? 'unverified'
|
|
20
|
+
: evidence.some((e) => e.pass === false) ? 'failed'
|
|
21
|
+
: unresolved.length ? 'declared' : 'verified';
|
|
22
|
+
return {
|
|
23
|
+
kind, id: claim.id, text: claim.statement, status, verify,
|
|
24
|
+
kinds: [...new Set((claim.verifications || []).map((v) => v.kind).filter((k) => k && k !== 'unclassified'))],
|
|
25
|
+
provenBy: status === 'verified' || status === 'failed' ? evidence.filter((e) => e.pass !== null).map((e) => e.name).join(', ') : null,
|
|
26
|
+
evidence, unresolved,
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
const obligations = [
|
|
30
|
+
...(ast.guarantees || []).map((g) => build('guarantee', g)),
|
|
31
|
+
...(ast.neverRules || []).map((n) => build('prohibition', n)),
|
|
32
|
+
];
|
|
33
|
+
const count = (s) => obligations.filter((o) => o.status === s).length;
|
|
34
|
+
return { obligations, tests, verified: count('verified'), declared: count('declared'), unverified: count('unverified'), failed: count('failed') };
|
|
35
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const PLAIN_SCHEMA: 'thunder-plain-v1';
|
|
2
|
+
export const COMPARISONS: ReadonlyArray<{ op: '>=' | '<=' | '<' | '>' | '=='; words: string[] }>;
|
|
3
|
+
export type PlainInput =
|
|
4
|
+
| { id: string; kind: 'dollars' | 'number' | 'text' | 'other'; label: string }
|
|
5
|
+
| { id: string; kind: 'yesno'; label: string; yes: string; no: string; fromState?: boolean };
|
|
6
|
+
export type PlainCondition = { input: string; op: '>=' | '<=' | '<' | '>' | '==' | '!=' | 'is'; value: number | boolean | string };
|
|
7
|
+
export type PlainRule = { outcome: string; join: 'all' | 'any'; conditions: PlainCondition[] };
|
|
8
|
+
export type PlainExample = { name: string; values: Record<string, number | boolean | string>; expected: string };
|
|
9
|
+
export interface PlainModel {
|
|
10
|
+
schema: 'thunder-plain-v1';
|
|
11
|
+
title: string; why: string; question: string;
|
|
12
|
+
inputs: PlainInput[]; rules: PlainRule[]; otherwise: string; examples: PlainExample[];
|
|
13
|
+
}
|
|
14
|
+
export interface PlainCheck { text: string; ok: boolean; actual: string; input: string }
|
|
15
|
+
export interface PlainExplanation { outcome: string | null; ruleIndex: number; rules: Array<{ outcome: string; join: 'all' | 'any'; checks: PlainCheck[] }>; ok: boolean }
|
|
16
|
+
export interface PlainPreview {
|
|
17
|
+
schema: 'thunder-plain-v1'; experimental: true; model: PlainModel; canonicalSource: string; plainSource: string;
|
|
18
|
+
tests: { total: number; passed: number; failed: number; results: Array<{ name: string; values: Record<string, number | boolean | string>; expected: unknown; actual: unknown; pass: boolean }> };
|
|
19
|
+
application: 'not_checked';
|
|
20
|
+
}
|
|
21
|
+
export function parsePlainContract(source: string): PlainModel;
|
|
22
|
+
export function renderPlainContract(model: PlainModel): string;
|
|
23
|
+
export function plainToThunder(model: PlainModel): string;
|
|
24
|
+
export function compilePlainContract(source: string): string;
|
|
25
|
+
export function conditionText(model: PlainModel, condition: PlainCondition): string;
|
|
26
|
+
export function formatValue(input: PlainInput, value: number | boolean | string): string;
|
|
27
|
+
export function outcomesOf(model: PlainModel): string[];
|
|
28
|
+
export function explainPlain(model: PlainModel, values: Record<string, number | boolean | string>): PlainExplanation;
|
|
29
|
+
export function previewPlainContract(sourceOrModel: string | PlainModel): PlainPreview;
|
|
30
|
+
export function plainFromReading(item: unknown): (PlainModel & { provenance: 'inferred-from-code'; needsReview: string[]; partial?: boolean }) | null;
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// Experimental plain-English notation (`.thunder-plain`). A deliberately small,
|
|
2
|
+
// strict subset that reads like a policy. It lowers to ordinary ThunderLang, so
|
|
3
|
+
// the existing parser, runtime, tests and code generators do all the real work.
|
|
4
|
+
// Nothing is guessed: a line that does not match the grammar is an error with
|
|
5
|
+
// its line number and an example of what to write instead.
|
|
6
|
+
import { parseIntent } from './parse.mjs';
|
|
7
|
+
import { compileExpr } from './expr.mjs';
|
|
8
|
+
import { runTests } from './testing.mjs';
|
|
9
|
+
import { evaluateDecision } from './runtime.mjs';
|
|
10
|
+
|
|
11
|
+
export const PLAIN_SCHEMA = 'thunder-plain-v1';
|
|
12
|
+
|
|
13
|
+
/** Comparison phrases. The first spelling is the canonical one used when rendering. */
|
|
14
|
+
export const COMPARISONS = [
|
|
15
|
+
{ op: '>=', words: ['at least'] },
|
|
16
|
+
{ op: '<=', words: ['at most'] },
|
|
17
|
+
{ op: '<', words: ['under', 'less than', 'below'] },
|
|
18
|
+
{ op: '>', words: ['over', 'more than', 'above'] },
|
|
19
|
+
{ op: '==', words: ['exactly'] },
|
|
20
|
+
];
|
|
21
|
+
const opWord = op => COMPARISONS.find(c => c.op === op)?.words[0] ?? op;
|
|
22
|
+
|
|
23
|
+
const fail = (line, text) => { throw new Error(`Line ${line}: ${text}`); };
|
|
24
|
+
const OUTCOME = /^[A-Z][A-Za-z]*$/;
|
|
25
|
+
const NAME_TEXT = /^[A-Za-z0-9 $.,'_-]+$/;
|
|
26
|
+
const lowerFirst = s => s.charAt(0).toLowerCase() + s.slice(1);
|
|
27
|
+
const pascal = s => s.replace(/[^A-Za-z0-9 ]/g, ' ').trim().split(/\s+/).filter(Boolean)
|
|
28
|
+
.map(w => w[0].toUpperCase() + w.slice(1)).join('');
|
|
29
|
+
const camel = s => lowerFirst(pascal(s));
|
|
30
|
+
const RESERVED = new Set(['and', 'or', 'not', 'in', 'true', 'false', 'case', 'expect']);
|
|
31
|
+
|
|
32
|
+
/** Format a number for a reader: dollar inputs get a $ sign, negatives read -$1. */
|
|
33
|
+
export function formatValue(input, value) {
|
|
34
|
+
if (input.kind === 'yesno') return value ? input.yes : input.no;
|
|
35
|
+
if (input.kind === 'text') return value === '' ? 'empty' : JSON.stringify(String(value));
|
|
36
|
+
if (input.kind === 'dollars') return `${value < 0 ? '-' : ''}$${Math.abs(value)}`;
|
|
37
|
+
return String(value);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseNumber(text, input, line) {
|
|
41
|
+
const t = text.trim().replace(/,/g, '');
|
|
42
|
+
const dollars = t.match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
|
|
43
|
+
if (input.kind === 'dollars') {
|
|
44
|
+
if (!dollars) fail(line, `${input.label} is in dollars. Write an amount such as $100.`);
|
|
45
|
+
return Number(`${dollars[1] || dollars[2] ? '-' : ''}${dollars[3]}`);
|
|
46
|
+
}
|
|
47
|
+
if (dollars) fail(line, `${input.label} is a plain number, not dollars. Write it without $.`);
|
|
48
|
+
if (!/^-?\d+(?:\.\d+)?$/.test(t)) fail(line, `Write a number for ${input.label}, such as 18.`);
|
|
49
|
+
return Number(t);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function parseInputLine(text, line) {
|
|
53
|
+
let m;
|
|
54
|
+
if ((m = text.match(/^whether it is (.+?) or (.+?)\.?$/))) {
|
|
55
|
+
const [yes, no] = [m[1].trim(), m[2].trim()];
|
|
56
|
+
if (yes === no) fail(line, 'Use two different words, such as "whether it is on time or late".');
|
|
57
|
+
return { id: camel(yes), kind: 'yesno', label: `it is ${yes}`, yes, no };
|
|
58
|
+
}
|
|
59
|
+
if ((m = text.match(/^(the .+?), (in dollars|a number)\.?$/))) {
|
|
60
|
+
const label = m[1].trim();
|
|
61
|
+
return { id: camel(label.replace(/^the /, '')), kind: m[2] === 'in dollars' ? 'dollars' : 'number', label };
|
|
62
|
+
}
|
|
63
|
+
fail(line, 'Describe each input as "the amount, in dollars", "the age, a number", or "whether it is on time or late".');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function parseCondition(text, inputs, line) {
|
|
67
|
+
const t = text.replace(/^[-•]\s*/, '').replace(/\.$/, '').trim();
|
|
68
|
+
let m;
|
|
69
|
+
if ((m = t.match(/^it is (.+)$/))) {
|
|
70
|
+
const word = m[1].trim();
|
|
71
|
+
const input = inputs.find(i => i.kind === 'yesno' && (i.yes === word || i.no === word));
|
|
72
|
+
if (input) return { input: input.id, op: 'is', value: input.yes === word };
|
|
73
|
+
}
|
|
74
|
+
for (const input of inputs.filter(i => i.kind !== 'yesno')) {
|
|
75
|
+
if (!t.startsWith(`${input.label} is `)) continue;
|
|
76
|
+
const rest = t.slice(input.label.length + 4);
|
|
77
|
+
for (const c of COMPARISONS) for (const w of c.words) {
|
|
78
|
+
if (rest.startsWith(`${w} `)) return { input: input.id, op: c.op, value: parseNumber(rest.slice(w.length + 1), input, line) };
|
|
79
|
+
}
|
|
80
|
+
fail(line, `Compare ${input.label} with at least, at most, under, over, or exactly. For example: "${input.label} is at most ${formatValue(input, 100)}".`);
|
|
81
|
+
}
|
|
82
|
+
const known = inputs.map(i => (i.kind === 'yesno' ? `"it is ${i.yes}"` : `"${i.label} is …"`)).join(', ');
|
|
83
|
+
fail(line, `This condition does not name an input. Start with one of: ${known}.`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Parse plain text into the structured model the visual card edits. */
|
|
87
|
+
export function parsePlainContract(source) {
|
|
88
|
+
if (typeof source !== 'string' || source.length > 100000) throw new Error('A plain contract must be text of at most 100 KB.');
|
|
89
|
+
const rows = source.split(/\r?\n/).map((raw, i) => ({ text: raw.trim(), depth: raw.match(/^\s*/)[0].replace(/\t/g, ' ').length, line: i + 1 }))
|
|
90
|
+
.filter(r => r.text && !r.text.startsWith('#'));
|
|
91
|
+
if (!rows.length) throw new Error('Start with a title, such as "Refund approval".');
|
|
92
|
+
const model = { schema: PLAIN_SCHEMA, title: '', why: '', question: '', inputs: [], rules: [], otherwise: '', examples: [] };
|
|
93
|
+
let section = null, rule = null;
|
|
94
|
+
for (const row of rows) {
|
|
95
|
+
const { text, depth, line } = row;
|
|
96
|
+
if (depth === 0) {
|
|
97
|
+
rule = null;
|
|
98
|
+
if (!model.title) { model.title = text.replace(/\.$/, ''); if (!pascal(model.title)) fail(line, 'Give the contract a title with letters, such as "Refund approval".'); continue; }
|
|
99
|
+
if (/^why:/i.test(text)) { model.why = text.replace(/^why:\s*/i, ''); section = null; continue; }
|
|
100
|
+
if (text === 'We need') { section = 'inputs'; continue; }
|
|
101
|
+
if (text === 'Examples') { section = 'examples'; continue; }
|
|
102
|
+
if (text.endsWith('?')) {
|
|
103
|
+
if (model.question) fail(line, 'This notation holds one decision per contract. Put another decision in its own file.');
|
|
104
|
+
if (!model.inputs.length) fail(line, 'List the inputs under "We need" before the decision.');
|
|
105
|
+
model.question = text; section = 'decision'; continue;
|
|
106
|
+
}
|
|
107
|
+
fail(line, 'Expected "Why: …", "We need", a decision question ending in ?, or "Examples".');
|
|
108
|
+
}
|
|
109
|
+
if (section === 'inputs') {
|
|
110
|
+
const input = parseInputLine(text, line);
|
|
111
|
+
if (RESERVED.has(input.id) || !input.id) fail(line, 'Choose a different name for this input.');
|
|
112
|
+
if (model.inputs.some(i => i.id === input.id)) fail(line, `${input.label} is listed twice.`);
|
|
113
|
+
const words = model.inputs.flatMap(i => (i.kind === 'yesno' ? [i.yes, i.no] : []));
|
|
114
|
+
if (input.kind === 'yesno' && (words.includes(input.yes) || words.includes(input.no))) fail(line, 'Each yes/no word must be unique across inputs.');
|
|
115
|
+
model.inputs.push(input);
|
|
116
|
+
} else if (section === 'decision') {
|
|
117
|
+
let m;
|
|
118
|
+
if (rule && depth > rule.depth) { rule.conditions.push(parseCondition(text, model.inputs, line)); continue; }
|
|
119
|
+
if ((m = text.match(/^Otherwise,?\s+([A-Za-z]+)\.?$/))) {
|
|
120
|
+
if (model.otherwise) fail(line, 'Use one "Otherwise" result.');
|
|
121
|
+
if (!OUTCOME.test(m[1])) fail(line, 'Name the outcome with one capitalized word, such as Review.');
|
|
122
|
+
model.otherwise = m[1]; rule = null; continue;
|
|
123
|
+
}
|
|
124
|
+
if (model.otherwise) fail(line, 'Put every rule before "Otherwise".');
|
|
125
|
+
if ((m = text.match(/^([A-Za-z]+) when (all|any) of these (?:are|is) true:?$/))) {
|
|
126
|
+
if (!OUTCOME.test(m[1])) fail(line, 'Name the outcome with one capitalized word, such as Approve.');
|
|
127
|
+
rule = { outcome: m[1], join: m[2], conditions: [], depth, line };
|
|
128
|
+
model.rules.push(rule); continue;
|
|
129
|
+
}
|
|
130
|
+
if ((m = text.match(/^([A-Za-z]+) when (.+)$/))) {
|
|
131
|
+
if (!OUTCOME.test(m[1])) fail(line, 'Name the outcome with one capitalized word, such as Approve.');
|
|
132
|
+
model.rules.push({ outcome: m[1], join: 'all', conditions: [parseCondition(m[2], model.inputs, line)], depth, line });
|
|
133
|
+
rule = null; continue;
|
|
134
|
+
}
|
|
135
|
+
fail(line, 'Write a rule as "Approve when all of these are true:" with conditions indented below, then "Otherwise, Review."');
|
|
136
|
+
} else if (section === 'examples') {
|
|
137
|
+
const m = text.match(/^(.+?)\s+gives\s+([A-Za-z]+)\s*(?:\((.+)\))?\.?$/);
|
|
138
|
+
if (!m) fail(line, `Write an example as "${model.inputs.map(i => formatValue(i, i.kind === 'yesno' ? true : 100)).join(', ')} gives Approve (a short name)".`);
|
|
139
|
+
const parts = m[1].split(/,\s+/);
|
|
140
|
+
if (parts.length !== model.inputs.length) fail(line, `Give ${model.inputs.length} values in this order: ${model.inputs.map(i => (i.kind === 'yesno' ? `${i.yes} or ${i.no}` : i.label)).join(', ')}. A missing value is not the same as no.`);
|
|
141
|
+
const values = {};
|
|
142
|
+
model.inputs.forEach((input, i) => {
|
|
143
|
+
const part = parts[i].trim();
|
|
144
|
+
if (input.kind === 'yesno') {
|
|
145
|
+
if (part !== input.yes && part !== input.no) fail(line, `Write "${input.yes}" or "${input.no}" for value ${i + 1}.`);
|
|
146
|
+
values[input.id] = part === input.yes;
|
|
147
|
+
} else values[input.id] = parseNumber(part, input, line);
|
|
148
|
+
});
|
|
149
|
+
const name = (m[3] ?? `example ${model.examples.length + 1}`).trim();
|
|
150
|
+
if (!NAME_TEXT.test(name)) fail(line, 'Use letters, numbers, spaces, $ and simple punctuation in the example name.');
|
|
151
|
+
if (model.examples.some(e => e.name === name)) fail(line, `Two examples are named "${name}". Give each a different name.`);
|
|
152
|
+
model.examples.push({ name, values, expected: m[2], line });
|
|
153
|
+
} else fail(line, 'This indented line does not belong to "We need", a decision, or "Examples".');
|
|
154
|
+
}
|
|
155
|
+
if (!model.question) throw new Error('Add a decision question ending in ?, such as "When do we approve a refund?"');
|
|
156
|
+
for (const r of model.rules) if (!r.conditions.length) fail(r.line, 'List at least one condition under this rule, indented.');
|
|
157
|
+
if (!model.rules.length) throw new Error('Add at least one rule, such as "Approve when all of these are true:".');
|
|
158
|
+
if (!model.otherwise) throw new Error('Finish the decision with "Otherwise, <Outcome>." so every request gets an answer.');
|
|
159
|
+
if (!model.examples.length) throw new Error('Add at least one example under "Examples".');
|
|
160
|
+
const outcomes = outcomesOf(model);
|
|
161
|
+
for (const e of model.examples) if (!outcomes.includes(e.expected)) fail(e.line, `Unknown outcome ${e.expected}. Use one of: ${outcomes.join(', ')}.`);
|
|
162
|
+
// Positions are parse metadata; keep the model a pure description.
|
|
163
|
+
model.rules = model.rules.map(({ outcome, join, conditions }) => ({ outcome, join, conditions }));
|
|
164
|
+
model.examples = model.examples.map(({ name, values, expected }) => ({ name, values, expected }));
|
|
165
|
+
return model;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function outcomesOf(model) {
|
|
169
|
+
return [...new Set([...model.rules.map(r => r.outcome), model.otherwise])];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Read one condition as English, e.g. "the amount is at most $100". */
|
|
173
|
+
export function conditionText(model, c) {
|
|
174
|
+
const input = model.inputs.find(i => i.id === c.input);
|
|
175
|
+
if (!input) return '(unknown input)';
|
|
176
|
+
if (input.kind === 'yesno') return `it is ${c.value ? input.yes : input.no}`;
|
|
177
|
+
if (input.kind === 'text') return `${input.label} is ${c.op === '!=' ? 'not ' : ''}${formatValue(input, c.value)}`;
|
|
178
|
+
return `${input.label} is ${opWord(c.op)} ${formatValue(input, c.value)}`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Render the model as plain text. parsePlainContract(renderPlainContract(m)) round-trips. */
|
|
182
|
+
export function renderPlainContract(model) {
|
|
183
|
+
const out = [model.title];
|
|
184
|
+
if (model.why) out.push(`Why: ${model.why}`);
|
|
185
|
+
out.push('', 'We need');
|
|
186
|
+
for (const i of model.inputs) out.push(` ${i.kind === 'yesno' ? `whether it is ${i.yes} or ${i.no}` : `${i.label}, ${i.kind === 'dollars' ? 'in dollars' : 'a number'}`}`);
|
|
187
|
+
out.push('', model.question);
|
|
188
|
+
for (const r of model.rules) {
|
|
189
|
+
if (r.conditions.length === 1) out.push(` ${r.outcome} when ${conditionText(model, r.conditions[0])}.`);
|
|
190
|
+
else {
|
|
191
|
+
out.push(` ${r.outcome} when ${r.join} of these ${r.join === 'all' ? 'are' : 'is'} true:`);
|
|
192
|
+
for (const c of r.conditions) out.push(` ${conditionText(model, c)}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
out.push(` Otherwise, ${model.otherwise}.`, '', 'Examples');
|
|
196
|
+
const cells = model.examples.map(e => [model.inputs.map(i => formatValue(i, e.values[i.id])).join(', '), `gives ${e.expected}`, `(${e.name})`]);
|
|
197
|
+
const w0 = Math.max(...cells.map(c => c[0].length)), w1 = Math.max(...cells.map(c => c[1].length));
|
|
198
|
+
for (const c of cells) out.push(` ${c[0].padEnd(w0)} ${c[1].padEnd(w1)} ${c[2]}`);
|
|
199
|
+
return out.join('\n') + '\n';
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function conditionExpr(model, c) {
|
|
203
|
+
const input = model.inputs.find(i => i.id === c.input);
|
|
204
|
+
if (input.kind === 'yesno') return `${input.id} == ${c.value}`;
|
|
205
|
+
if (input.kind === 'text') return `${input.id} ${c.op === '!=' ? '!=' : '=='} ${JSON.stringify(String(c.value))}`;
|
|
206
|
+
return `${input.id} ${c.op} ${c.value}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Lower the model to ordinary ThunderLang source. */
|
|
210
|
+
export function plainToThunder(model) {
|
|
211
|
+
const name = pascal(model.title);
|
|
212
|
+
const lit = v => (typeof v === 'boolean' ? String(v) : String(v));
|
|
213
|
+
const out = [`# Compiled from plain ThunderLang (${PLAIN_SCHEMA}). Edit the plain file, not this one.`,
|
|
214
|
+
`mission ${name}`, '', `title ${JSON.stringify(model.title)}`, '', 'goal', ` ${model.why || model.title}`,
|
|
215
|
+
'', `# ${model.question}`, `decision ${name}`, ' inputs', ...model.inputs.map(i => ` ${i.id}${i.kind === 'yesno' ? ': boolean' : i.kind === 'number' || i.kind === 'dollars' ? ': number' : i.kind === 'text' ? ': string' : ''}`)];
|
|
216
|
+
const used = new Map();
|
|
217
|
+
for (const r of model.rules) {
|
|
218
|
+
const base = lowerFirst(r.outcome); const n = (used.get(base) ?? 0) + 1; used.set(base, n);
|
|
219
|
+
out.push(` rule ${n === 1 ? base : `${base}_${n}`}`, ` when ${r.conditions.map(c => conditionExpr(model, c)).join(r.join === 'all' ? ' and ' : ' or ')}`, ` return ${r.outcome}`);
|
|
220
|
+
}
|
|
221
|
+
out.push(' default', ` return ${model.otherwise}`, '', `test ${name}`);
|
|
222
|
+
for (const e of model.examples) {
|
|
223
|
+
out.push(` case ${e.name}`, ` given ${model.inputs.map(i => `${i.id} ${lit(e.values[i.id])}`).join(', ')}`, ` expect ${e.expected}`);
|
|
224
|
+
}
|
|
225
|
+
return out.join('\n') + '\n';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function compilePlainContract(source) {
|
|
229
|
+
return plainToThunder(parsePlainContract(source));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Decide one request with the real runtime and explain it in the reader's words.
|
|
234
|
+
* The outcome comes from evaluateDecision on the compiled contract; the per-condition
|
|
235
|
+
* check marks come from the same expression engine, condition by condition.
|
|
236
|
+
*/
|
|
237
|
+
export function explainPlain(model, values, ast = parseIntent(plainToThunder(model))) {
|
|
238
|
+
const run = evaluateDecision(ast.decisions[0], values);
|
|
239
|
+
const rules = model.rules.map(r => ({
|
|
240
|
+
outcome: r.outcome, join: r.join,
|
|
241
|
+
checks: r.conditions.map(c => ({ text: conditionText(model, c), ok: !!compileExpr(conditionExpr(model, c))(values), actual: formatValue(model.inputs.find(i => i.id === c.input), values[c.input]), input: c.input })),
|
|
242
|
+
}));
|
|
243
|
+
const index = run.matched === 'default' ? -1 : (ast.decisions[0].rules.findIndex(r => r.name === run.matched));
|
|
244
|
+
return { outcome: run.result, ruleIndex: index, rules, ok: run.ok };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Everything the reading surface needs: model, compiled source, and executed examples. */
|
|
248
|
+
export function previewPlainContract(sourceOrModel) {
|
|
249
|
+
const model = typeof sourceOrModel === 'string' ? parsePlainContract(sourceOrModel) : sourceOrModel;
|
|
250
|
+
const canonicalSource = plainToThunder(model);
|
|
251
|
+
const ast = parseIntent(canonicalSource);
|
|
252
|
+
const results = runTests(ast).results.map((r, i) => ({
|
|
253
|
+
name: model.examples[i].name, values: model.examples[i].values, expected: r.expected, actual: r.actual, pass: !!r.pass && !r.error,
|
|
254
|
+
}));
|
|
255
|
+
return {
|
|
256
|
+
schema: PLAIN_SCHEMA, experimental: true, model, canonicalSource, plainSource: renderPlainContract(model),
|
|
257
|
+
tests: { total: results.length, passed: results.filter(r => r.pass).length, failed: results.filter(r => !r.pass).length, results },
|
|
258
|
+
application: 'not_checked',
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const spaced = s => s.replace(/([a-z0-9])([A-Z])/g, (_m, a, b) => `${a} ${b.toLowerCase()}`).replace(/_/g, ' ').toLowerCase();
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* "Thunder" a decision the code reader lifted from any supported language into the visual
|
|
266
|
+
* model. Only simple shapes are accepted (comparisons with numbers, yes/no flags, joined by
|
|
267
|
+
* all-and or all-or); anything else returns null so the caller shows the reader's own sentence
|
|
268
|
+
* instead of an invented picture. Names come from the code, so the result needs human review:
|
|
269
|
+
* the code cannot say that a number is money or what a flag means in business words.
|
|
270
|
+
*/
|
|
271
|
+
export function plainFromReading(item) {
|
|
272
|
+
if (!item || item.kind !== 'decision' || !item.rules?.length || !item.otherwise) return null;
|
|
273
|
+
// Untyped languages (JavaScript, Ruby, untyped Python): infer a type only from how the rule uses the input,
|
|
274
|
+
// and say so in needsReview. Compared with a number -> number; used alone as a condition -> yes/no.
|
|
275
|
+
const inferred = [];
|
|
276
|
+
const whens = (item.rules ?? []).map(r => r.when ?? '').join(' and ');
|
|
277
|
+
const typed = (item.inputs ?? []).map(i => {
|
|
278
|
+
if (i.type) return i;
|
|
279
|
+
const esc = i.name.replace(/[$]/g, '\\$');
|
|
280
|
+
if (new RegExp(`\\b${esc}\\s*(>=|<=|<|>|==)\\s*-?\\d`).test(whens)) { inferred.push(i.name); return { ...i, type: 'number' }; }
|
|
281
|
+
if (new RegExp(`(^|\\s|not\\s+|!)${esc}(\\s|$)`).test(whens)) { inferred.push(i.name); return { ...i, type: 'boolean' }; }
|
|
282
|
+
return i;
|
|
283
|
+
});
|
|
284
|
+
const inputs = typed.map(i => (i.type === 'boolean'
|
|
285
|
+
? { id: i.name, kind: 'yesno', label: `it is ${spaced(i.name)}`, yes: spaced(i.name), no: `not ${spaced(i.name)}` }
|
|
286
|
+
: i.type === 'number' ? { id: i.name, kind: 'number', label: `the ${spaced(i.name)}` }
|
|
287
|
+
: { id: i.name, kind: 'other', label: `the ${spaced(i.name)}` }));
|
|
288
|
+
const model = { schema: PLAIN_SCHEMA, title: spaced(item.name).replace(/^./, c => c.toUpperCase()), why: '',
|
|
289
|
+
question: `How is ${spaced(item.name)} decided?`, inputs, rules: [], otherwise: '', examples: [],
|
|
290
|
+
provenance: 'inferred-from-code', needsReview: [] };
|
|
291
|
+
const outcome = t => (/^[A-Za-z_][A-Za-z0-9_]*$/.test(t) || /^-?\d+(\.\d+)?$/.test(t) ? t : null);
|
|
292
|
+
const stateFacts = [];
|
|
293
|
+
const input = id => inputs.find(i => i.id === id);
|
|
294
|
+
// A bare name or path the function reads that is not a parameter (a field, a method with no
|
|
295
|
+
// arguments): shown as a yes/no fact and flagged, because it comes from the code's state.
|
|
296
|
+
const factFor = path => {
|
|
297
|
+
const id = path.replace(/[^A-Za-z0-9_]/g, '_');
|
|
298
|
+
let f = input(id);
|
|
299
|
+
if (!f) {
|
|
300
|
+
const word = spaced(path.split('.').pop());
|
|
301
|
+
f = { id, kind: 'yesno', label: `it is ${word}`, yes: word, no: `not ${word}`, fromState: true };
|
|
302
|
+
if (inputs.some(i => i.kind === 'yesno' && (i.yes === f.yes || i.no === f.yes))) return null;
|
|
303
|
+
inputs.push(f); stateFacts.push(path);
|
|
304
|
+
}
|
|
305
|
+
return f;
|
|
306
|
+
};
|
|
307
|
+
for (const r of item.rules) {
|
|
308
|
+
const when = r.when.trim();
|
|
309
|
+
const join = / or /.test(when) ? 'any' : 'all';
|
|
310
|
+
if (/ or /.test(when) && / and /.test(when)) return null;
|
|
311
|
+
const conditions = [];
|
|
312
|
+
for (const part of when.split(join === 'all' ? ' and ' : ' or ')) {
|
|
313
|
+
const t = part.trim(); let m;
|
|
314
|
+
const input = id => inputs.find(i => i.id === id);
|
|
315
|
+
if ((m = t.match(/^(not\s+|!)?([A-Za-z_]\w*)$/)) && input(m[2])?.kind === 'yesno') conditions.push({ input: m[2], op: 'is', value: !m[1] });
|
|
316
|
+
else if ((m = t.match(/^([A-Za-z_]\w*)\s*(>=|<=|<|>|==)\s*(-?\d+(?:\.\d+)?)$/)) && input(m[1])?.kind === 'number') conditions.push({ input: m[1], op: m[2], value: Number(m[3]) });
|
|
317
|
+
else if ((m = t.match(/^([A-Za-z_][\w.]*)\s*(==|!=)\s*"([^"]*)"$/))) {
|
|
318
|
+
let f = input(m[1]);
|
|
319
|
+
if (!f) { const id = m[1].replace(/[^A-Za-z0-9_]/g, '_'); f = { id, kind: 'text', label: `the ${spaced(m[1].split('.').pop())}` }; if (m[1].includes('.')) stateFacts.push(m[1]); inputs.push(f); }
|
|
320
|
+
if (f.kind === 'yesno' || f.kind === 'number') return null;
|
|
321
|
+
f.kind = 'text'; conditions.push({ input: f.id, op: m[2], value: m[3] });
|
|
322
|
+
}
|
|
323
|
+
else if ((m = t.match(/^(not\s+|!)?([A-Za-z_][\w.]*)$/)) && !input(m[2])) { const f = factFor(m[2]); if (!f) return null; conditions.push({ input: f.id, op: 'is', value: !m[1] }); }
|
|
324
|
+
else return null;
|
|
325
|
+
}
|
|
326
|
+
if (!outcome(r.result)) return null;
|
|
327
|
+
model.rules.push({ outcome: r.result, join, conditions });
|
|
328
|
+
}
|
|
329
|
+
if (!outcome(item.otherwise.result)) return null;
|
|
330
|
+
model.otherwise = item.otherwise.result;
|
|
331
|
+
for (const i of inputs) {
|
|
332
|
+
model.needsReview.push(i.kind === 'yesno' ? `What does "${i.yes}" mean in business words?` : `Is ${i.label} money, a count, or something else?`);
|
|
333
|
+
}
|
|
334
|
+
for (const path of stateFacts) model.needsReview.push(`${spaced(path.split('.').pop())} comes from the code's own state, not from an input.`);
|
|
335
|
+
if (item.status === 'partial') { model.partial = true; model.needsReview.unshift(`Thunder could not read ${item.unread?.length || 'some'} line(s) of this function, so the picture may be incomplete.`); }
|
|
336
|
+
for (const name of inferred) model.needsReview.push(`The code does not declare a type for ${spaced(name)}; Thunder inferred it from how the rule uses it.`);
|
|
337
|
+
model.needsReview.push('Why does this rule exist? Code shows what happens, not why.', 'No examples yet: add cases before relying on it.');
|
|
338
|
+
return model;
|
|
339
|
+
}
|
package/src/promote.mjs
CHANGED
|
@@ -72,19 +72,21 @@ function assignments(inputs, values, cap = 4096) {
|
|
|
72
72
|
const lit = (v) => (typeof v === 'string' ? JSON.stringify(v) : String(v));
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
75
|
+
* The recovered rule as something that can run: plain input names, candidate values on both sides of every
|
|
76
|
+
* threshold, and an evaluator. `extraConditions` widens the candidate values (Thunder write uses the edited
|
|
77
|
+
* rule's conditions, so the before and after versions are checked on the same inputs).
|
|
78
|
+
* Returns { ok: true, notes, refs, renames, names, types, values, rules, decisionName, canonical, run, all }
|
|
79
|
+
* or { ok: false, reason }.
|
|
77
80
|
*/
|
|
78
|
-
export function
|
|
81
|
+
export function recoverModel(item, { extraConditions = [] } = {}) {
|
|
79
82
|
if (!item || item.kind !== 'decision' || !item.rules?.length || !item.otherwise) return { ok: false, reason: 'Only decisions (functions that choose between fixed answers) can become a contract.' };
|
|
80
83
|
const results = [...item.rules.map((r) => r.result), item.otherwise.result];
|
|
81
84
|
const bad = results.find((r) => !OUTCOME.test(r));
|
|
82
85
|
if (bad) return { ok: false, reason: `The answer ${bad} is not a name. Contracts answer with names such as Approve or Review.` };
|
|
83
|
-
|
|
84
86
|
// Flatten field paths (order.total -> orderTotal) so every input is a plain name.
|
|
85
87
|
const notes = [];
|
|
86
88
|
const renames = new Map();
|
|
87
|
-
const conditions = item.rules.map((r) => r.when);
|
|
89
|
+
const conditions = [...item.rules.map((r) => r.when), ...extraConditions];
|
|
88
90
|
const refs = usage(conditions, new Set((item.inputs || []).map((p) => p.name)));
|
|
89
91
|
for (const path of refs.keys()) if (path.includes('.')) { renames.set(path, flat(path)); notes.push(`${flat(path)} stands for ${path} in the code.`); }
|
|
90
92
|
const rewrite = (cond) => tokenize(cond).map((t) => {
|
|
@@ -114,6 +116,18 @@ export function promoteDecision(item, { file = item.file || '' } = {}) {
|
|
|
114
116
|
...rules.flatMap((r, i) => [` rule r${i + 1}`, ` when ${r.when}`, ` return ${r.result}`]), ' default', ` return ${item.otherwise.result}`].join('\n')).decisions[0];
|
|
115
117
|
const run = (a) => evaluateDecision(canonical, a);
|
|
116
118
|
const all = assignments(names, values).map((a) => ({ a, r: run(a) }));
|
|
119
|
+
return { ok: true, notes, refs, renames, names, types, values, rules, decisionName, canonical, run, all };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Turn a decision item from readCode/readRepo into a readable contract.
|
|
124
|
+
* Returns { ok: true, source, name, examples, notes } or { ok: false, reason }.
|
|
125
|
+
*/
|
|
126
|
+
export function promoteDecision(item, { file = item.file || '' } = {}) {
|
|
127
|
+
const model = recoverModel(item);
|
|
128
|
+
if (!model.ok) return model;
|
|
129
|
+
const { notes, refs, renames, names, types, rules, decisionName, run, all } = model;
|
|
130
|
+
const results = [...item.rules.map((r) => r.result), item.otherwise.result];
|
|
117
131
|
const chosen = [];
|
|
118
132
|
const key = (a) => names.map((n) => lit(a[n])).join('|');
|
|
119
133
|
const add = (a, label) => {
|
package/src/read.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type ReadKind = 'decision' | 'function' | 'error' | 'test';
|
|
2
|
-
export interface ReadInput { name: string; type: string | null }
|
|
2
|
+
export interface ReadInput { name: string; type: string | null; /** Framework plumbing (db, request, ctx): not something a person gives. */ plumbing?: true }
|
|
3
3
|
export interface ReadRule { when: string; result: string; line: number; says: string }
|
|
4
4
|
export interface ReadUnread { line: number; text: string; reason: string }
|
|
5
5
|
export interface ReadGuard {
|
|
@@ -13,6 +13,30 @@ export interface ReadItem {
|
|
|
13
13
|
rules?: ReadRule[]; otherwise?: { result: string; line: number } | null;
|
|
14
14
|
thunder?: string; unread?: ReadUnread[]; guards?: ReadGuard[];
|
|
15
15
|
route?: { method: string; path: string };
|
|
16
|
+
/** A display name: "Late fee". */
|
|
17
|
+
label?: string;
|
|
18
|
+
/** For functions: what it handles or takes, without notes (unlike `says`). */
|
|
19
|
+
headline?: string;
|
|
20
|
+
/** Why no rules are drawn, kept apart from `says`. */
|
|
21
|
+
note?: string;
|
|
22
|
+
/** How completely Thunder explains it, and why. */
|
|
23
|
+
completeness?: { level: 'explained' | 'partly explained' | 'found' | 'executed'; reasons: string[] };
|
|
24
|
+
/** The author's own words for what the function means (docstring or doc comment), first paragraph only. Not inferred. */
|
|
25
|
+
doc?: string;
|
|
26
|
+
steps?: ReadStep[]; stepsMore?: number;
|
|
27
|
+
/** Share of steps that explain the code: not `other` and not `restates`. */
|
|
28
|
+
stepsReadable?: number;
|
|
29
|
+
}
|
|
30
|
+
/** One plain step of a function (thunder-steps-v1). */
|
|
31
|
+
export interface ReadStep {
|
|
32
|
+
kind: 'check' | 'branch' | 'loop' | 'set' | 'call' | 'return' | 'fail' | 'try' | 'other';
|
|
33
|
+
says: string; code: string; line: number; callee?: string; children?: ReadStep[];
|
|
34
|
+
/** On a fail step: the error's name and its message, apart from `says`. */
|
|
35
|
+
error?: string; message?: string;
|
|
36
|
+
/** The other side of an If; error handlers; what always runs at the end. */
|
|
37
|
+
otherwise?: ReadStep[]; handlers?: { says: string; line: number; steps: ReadStep[] }[]; always?: { line: number; steps: ReadStep[] };
|
|
38
|
+
/** The wording only restates the code's syntax ("Works out actives"); show the code, do not count it as read. */
|
|
39
|
+
restates?: true;
|
|
16
40
|
}
|
|
17
41
|
export interface Reading {
|
|
18
42
|
schema: 'thunder-reading-v1'; language: string; detected: boolean; items: ReadItem[];
|