@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
package/src/read.mjs
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// return cond ? X : Y (nested ternaries) Python: return X if cond else Y
|
|
10
10
|
// Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
|
|
11
11
|
// Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
|
|
12
|
+
import { stepsFrom, braceStatements, indentStatements, plainEnums } from './steps.mjs';
|
|
12
13
|
import { compileExpr, simplifyExpr } from './expr.mjs';
|
|
13
14
|
import { extractFacts, languageForFile } from './lift.mjs';
|
|
14
15
|
|
|
@@ -35,7 +36,25 @@ export function detectLanguage(source, file = '') {
|
|
|
35
36
|
|
|
36
37
|
// ── Lexing helpers ──────────────────────────────────────────────────────────────────────────
|
|
37
38
|
|
|
38
|
-
|
|
39
|
+
// Line of a character offset. The line starts of the last few sources are kept, so each lookup is a binary search
|
|
40
|
+
// instead of counting every newline from the top (which made large files quadratic).
|
|
41
|
+
const lineStarts = new Map();
|
|
42
|
+
function startsOf(src) {
|
|
43
|
+
let starts = lineStarts.get(src);
|
|
44
|
+
if (!starts) {
|
|
45
|
+
starts = [0];
|
|
46
|
+
for (let i = src.indexOf('\n'); i >= 0; i = src.indexOf('\n', i + 1)) starts.push(i + 1);
|
|
47
|
+
if (lineStarts.size > 8) lineStarts.delete(lineStarts.keys().next().value);
|
|
48
|
+
lineStarts.set(src, starts);
|
|
49
|
+
}
|
|
50
|
+
return starts;
|
|
51
|
+
}
|
|
52
|
+
const lineAt = (src, idx) => {
|
|
53
|
+
const starts = startsOf(src);
|
|
54
|
+
let lo = 0, hi = starts.length - 1;
|
|
55
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= idx) lo = mid; else hi = mid - 1; }
|
|
56
|
+
return lo + 1;
|
|
57
|
+
};
|
|
39
58
|
|
|
40
59
|
/** Index of the bracket that closes the one at `open`, skipping strings and comments. */
|
|
41
60
|
function matchClose(src, open) {
|
|
@@ -84,6 +103,7 @@ const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:
|
|
|
84
103
|
// ── Function discovery ──────────────────────────────────────────────────────────────────────
|
|
85
104
|
|
|
86
105
|
function parseParams(raw, language) {
|
|
106
|
+
raw = String(raw).replace(/#\[[^\]]*\]\s*/g, '').replace(/\[\w+(?:\([^)]*\))?\]\s*/g, ''); // #[SensitiveParameter], [FromBody]
|
|
87
107
|
const parts = [];
|
|
88
108
|
let depth = 0, cur = '';
|
|
89
109
|
for (const ch of raw) {
|
|
@@ -121,6 +141,33 @@ function parseParams(raw, language) {
|
|
|
121
141
|
return out;
|
|
122
142
|
}
|
|
123
143
|
|
|
144
|
+
/**
|
|
145
|
+
* A TypeScript signature head after ")": `: <type>` read with balanced <>, {}, (), [] (so `Promise<{ a: 1 }>` is whole),
|
|
146
|
+
* then the body marker (=>, { or ;). Returns a match-like array [whole, type, , , marker] or null when there is no
|
|
147
|
+
* ": type" (the regular pattern handles that).
|
|
148
|
+
*/
|
|
149
|
+
function balancedReturnHead(after) {
|
|
150
|
+
const lead = after.match(/^\s*:/);
|
|
151
|
+
if (!lead) return null;
|
|
152
|
+
let i = lead[0].length, depth = 0;
|
|
153
|
+
for (; i < after.length; i++) {
|
|
154
|
+
const c = after[i];
|
|
155
|
+
if (c === '=' && after[i + 1] === '>') { if (depth === 0) break; i++; continue; } // => ends the type, or is a function type's arrow
|
|
156
|
+
if (c === '<' || c === '(' || c === '[') depth++;
|
|
157
|
+
else if (c === '>' || c === ')' || c === ']') depth--;
|
|
158
|
+
else if (c === '{') { if (depth === 0) break; depth++; }
|
|
159
|
+
else if (c === '}') depth--;
|
|
160
|
+
else if (c === ';' && depth === 0) break;
|
|
161
|
+
else if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < after.length && after[i] !== q) i++; }
|
|
162
|
+
}
|
|
163
|
+
const type = after.slice(lead[0].length, i).trim();
|
|
164
|
+
const tail = after.slice(i).match(/^\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
|
|
165
|
+
if (!type || !tail) return null;
|
|
166
|
+
const whole = after.slice(0, i) + tail[0];
|
|
167
|
+
const m = [whole, type, undefined, undefined, tail[1]];
|
|
168
|
+
return m;
|
|
169
|
+
}
|
|
170
|
+
|
|
124
171
|
function simpleType(t) {
|
|
125
172
|
if (!t) return null;
|
|
126
173
|
const s = String(t).trim().replace(/^&(mut\s+)?/, '');
|
|
@@ -135,21 +182,38 @@ function findFunctions(src, language) {
|
|
|
135
182
|
const fns = [];
|
|
136
183
|
if (language === 'python') {
|
|
137
184
|
const lines = src.split('\n');
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
185
|
+
let decorators = [];
|
|
186
|
+
for (let i = 0; i < lines.length; i++) {
|
|
187
|
+
const l = lines[i];
|
|
188
|
+
// Decorators: `@router.get(` can run over several lines (FastAPI keyword arguments); keep each one whole.
|
|
189
|
+
if (/^\s*@/.test(l)) {
|
|
190
|
+
const { text, end } = pyBalanced(lines, i, l.indexOf('@'));
|
|
191
|
+
decorators.push(text.replace(/\s+/g, ' ').trim());
|
|
192
|
+
i = end;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const start = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(/);
|
|
196
|
+
if (!start) { if (l.trim() && !/^\s*#/.test(l)) decorators = []; continue; }
|
|
197
|
+
// The header can span lines: parameters one per line (FastAPI `Depends(...)`), a wrapped return type.
|
|
198
|
+
const head = pyHeader(lines, i, start[0].length - 1);
|
|
199
|
+
if (!head) { decorators = []; continue; }
|
|
200
|
+
const indent = start[1].length;
|
|
142
201
|
const body = [];
|
|
143
|
-
|
|
144
|
-
|
|
202
|
+
const inline = pyNoComment(head.after).trim();
|
|
203
|
+
if (inline) body.push({ text: inline, line: head.endLine + 1, indent: indent + 4 });
|
|
204
|
+
for (let j = head.endLine + 1; j < lines.length; j++) {
|
|
145
205
|
const t = lines[j];
|
|
146
206
|
if (!t.trim() || /^\s*#/.test(t)) continue;
|
|
147
207
|
const ind = t.match(/^\s*/)[0].length;
|
|
148
208
|
if (ind <= indent) break;
|
|
149
|
-
|
|
209
|
+
const code = pyNoComment(t).trim();
|
|
210
|
+
if (!code) continue;
|
|
211
|
+
body.push({ text: code, line: j + 1, indent: ind });
|
|
150
212
|
}
|
|
151
|
-
|
|
152
|
-
|
|
213
|
+
const doc = inline ? null : pyDocstring(lines, head.endLine + 1);
|
|
214
|
+
fns.push({ name: start[2], line: i + 1, params: parseParams(head.params, language), returns: head.returns, pyBody: body, ...(decorators.length ? { decorators } : {}), ...(doc ? { doc } : {}) });
|
|
215
|
+
decorators = [];
|
|
216
|
+
}
|
|
153
217
|
annotateRoutes(fns, src);
|
|
154
218
|
return fns;
|
|
155
219
|
}
|
|
@@ -178,12 +242,19 @@ function findFunctions(src, language) {
|
|
|
178
242
|
if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
|
|
179
243
|
const close = matchClose(src, open);
|
|
180
244
|
if (close < 0) continue;
|
|
181
|
-
// After the parameter list: an optional return type / throws clause, then a body.
|
|
182
|
-
|
|
183
|
-
const
|
|
245
|
+
// After the parameter list: an optional return type / throws clause, then a body. A signature's head is short,
|
|
246
|
+
// so look at a window, not the rest of the file (copying the rest per function made large files slow).
|
|
247
|
+
const after = src.slice(close + 1, close + 1 + 4000);
|
|
248
|
+
// TypeScript return types can hold braces and generics (`: Promise<{ ok: boolean }>`): read them balanced, so
|
|
249
|
+
// the body's "{" is the one after the type, not a brace inside it.
|
|
250
|
+
const typed = (language === 'typescript' || language === 'javascript') ? balancedReturnHead(after) : null;
|
|
251
|
+
const head = typed ?? (language === 'kotlin'
|
|
184
252
|
? after.match(/^\s*(?::\s*([^{=]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/)
|
|
185
|
-
: after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
|
|
253
|
+
: after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/));
|
|
186
254
|
if (!head || head[4] === ';') continue;
|
|
255
|
+
// `const d = (await res.json()) as {...}` is a value, not a function: a const/let/var only declares a
|
|
256
|
+
// function when its parameter list is followed by `=>`.
|
|
257
|
+
if (/\(\?:const\|let\|var\)/.test(re.source) && head[4] !== '=>') continue;
|
|
187
258
|
if (language === 'kotlin' && head[4] === '=') {
|
|
188
259
|
// Kotlin expression body: fun f(x: Int) = when (x) { ... } / = if (...) "A" else "B" / = "A"
|
|
189
260
|
const markerAt = close + 1 + head[0].length - 1;
|
|
@@ -193,7 +264,7 @@ function findFunctions(src, language) {
|
|
|
193
264
|
const rest = src.slice(markerAt + 1);
|
|
194
265
|
const lead = rest.match(/^\s*/)[0].length;
|
|
195
266
|
const end = kotlinExprEnd(rest, lead);
|
|
196
|
-
fns.push({ key: `${name}@${m.index}`, name, line: fnLine, params: parseParams(src.slice(open + 1, close), language), returns: (head[1] || '').trim() || null, bodyStart: markerAt + 1 + lead, body: `return ${rest.slice(lead, end).trim()}
|
|
267
|
+
fns.push({ key: `${name}@${m.index}`, name, line: fnLine, params: parseParams(src.slice(open + 1, close), language), returns: (head[1] || '').trim() || null, bodyStart: markerAt + 1 + lead, body: `return ${rest.slice(lead, end).trim()}`, exprBody: rest.slice(lead, end).trim().length });
|
|
197
268
|
continue;
|
|
198
269
|
}
|
|
199
270
|
const key = `${name}@${m.index}`;
|
|
@@ -216,7 +287,7 @@ function findFunctions(src, language) {
|
|
|
216
287
|
const blank = rest.search(/\n\s*\n/);
|
|
217
288
|
const end = semi < 0 ? blank : blank < 0 ? semi : Math.min(semi, blank);
|
|
218
289
|
const expr = (end < 0 ? rest : rest.slice(0, end)).trim();
|
|
219
|
-
fns.push({ key, name, line: fnLine, params, returns, bodyStart: markerAt + 2 + lead, body: `return ${expr}
|
|
290
|
+
fns.push({ key, name, line: fnLine, params, returns, bodyStart: markerAt + 2 + lead, body: `return ${expr};`, exprBody: expr.length });
|
|
220
291
|
}
|
|
221
292
|
} else {
|
|
222
293
|
const bc = matchClose(src, markerAt);
|
|
@@ -257,17 +328,182 @@ function findFunctions(src, language) {
|
|
|
257
328
|
fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method, path: m[2] } });
|
|
258
329
|
}
|
|
259
330
|
}
|
|
331
|
+
// Fastify: fastify.route({ method: 'POST', url: '/orders', handler: async (request, reply) => { ... } })
|
|
332
|
+
if (language === 'typescript' || language === 'javascript') {
|
|
333
|
+
const re = /\b\w+\.route\(\s*\{/g;
|
|
334
|
+
let m;
|
|
335
|
+
while ((m = re.exec(src))) {
|
|
336
|
+
const objOpen = m.index + m[0].length - 1;
|
|
337
|
+
const objClose = matchClose(src, objOpen);
|
|
338
|
+
if (objClose < 0) continue;
|
|
339
|
+
const obj = src.slice(objOpen, objClose);
|
|
340
|
+
const method = (obj.match(/\bmethod\s*:\s*['"`](\w+)['"`]/) || [])[1];
|
|
341
|
+
const url = (obj.match(/\b(?:url|path)\s*:\s*['"`]([^'"`]+)['"`]/) || [])[1];
|
|
342
|
+
const h = obj.match(/\bhandler\s*:\s*(?:async\s*)?(?:function\s*\w*\s*)?\(/);
|
|
343
|
+
if (!method || !url || !h) continue;
|
|
344
|
+
const pOpen = objOpen + h.index + h[0].length - 1;
|
|
345
|
+
const pClose = matchClose(src, pOpen);
|
|
346
|
+
const brace = pClose < 0 ? -1 : src.indexOf('{', pClose);
|
|
347
|
+
if (brace < 0 || !/^\s*(=>\s*)?(:\s*[\w<>\[\]|. ]+)?\s*(=>\s*)?$/.test(src.slice(pClose + 1, brace))) continue;
|
|
348
|
+
const bc = matchClose(src, brace);
|
|
349
|
+
if (bc < 0) continue;
|
|
350
|
+
fns.push({ name: `${method.toUpperCase()} ${url}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: method.toUpperCase(), path: url } });
|
|
351
|
+
}
|
|
352
|
+
}
|
|
260
353
|
annotateRoutes(fns, src);
|
|
261
354
|
return fns.sort((a, b) => a.line - b.line);
|
|
262
355
|
}
|
|
356
|
+
// ── Labels, plumbing, and completeness: facts views need, so they never re-derive them ─────────────────
|
|
357
|
+
|
|
358
|
+
/** A display name: late_fee -> "Late fee", deliveryFee -> "Delivery fee", __init__ -> "Init". */
|
|
359
|
+
export function displayLabel(name) {
|
|
360
|
+
const w = String(name).replace(/^_+|_+$/g, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
361
|
+
return w ? w.charAt(0).toUpperCase() + w.slice(1) : String(name);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Inputs that are framework plumbing rather than something a person gives. */
|
|
365
|
+
const PLUMBING = /^(self|this|cls|db|session|conn|connection|cursor|tx|transaction|request|req|res|response|ctx|context|c|w|r|next|logger|log|deps|container|di|cancellationToken|ct|ec|app|g)$/i;
|
|
366
|
+
const PLUMBING_TYPE = /\b(Session|AsyncSession|DbContext|Connection|HttpRequest|HttpResponse|Request|Response|Context|ResponseWriter|CancellationToken|ILogger|Logger|NextFunction)\b/;
|
|
367
|
+
|
|
368
|
+
const allSteps = (steps) => (steps || []).flatMap((s) => [s, ...allSteps(s.children), ...allSteps(s.otherwise), ...(s.handlers || []).flatMap((h) => allSteps(h.steps)), ...allSteps(s.always?.steps)]);
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* How completely Thunder explains an item, with the reasons. "explained": every step says what it does and every
|
|
372
|
+
* branch is shown; "partly explained": something is shown as code or not read; "found": Thunder found the function
|
|
373
|
+
* but could not turn it into steps or rules. ("executed" is for a view that has also run it.)
|
|
374
|
+
*/
|
|
375
|
+
export function completenessOf(item) {
|
|
376
|
+
const reasons = [];
|
|
377
|
+
if (item.kind === 'decision') {
|
|
378
|
+
if (item.unread?.length) reasons.push(`${item.unread.length} line${item.unread.length === 1 ? '' : 's'} not read`);
|
|
379
|
+
return { level: reasons.length ? 'partly explained' : 'explained', reasons };
|
|
380
|
+
}
|
|
381
|
+
const steps = allSteps(item.steps);
|
|
382
|
+
if (!steps.length) return { level: 'found', reasons: ['No steps could be read; see the original code.'] };
|
|
383
|
+
const code = steps.filter((s) => s.kind === 'other').length;
|
|
384
|
+
const restated = steps.filter((s) => s.restates).length;
|
|
385
|
+
if (code) reasons.push(`${code} step${code === 1 ? '' : 's'} shown as code`);
|
|
386
|
+
if (restated) reasons.push(`${restated} step${restated === 1 ? '' : 's'} only restate the code`);
|
|
387
|
+
if (item.anchor && item.anchor.coverage < 1) reasons.push(`${item.anchor.missing.length ? `lines ${item.anchor.missing.join(', ')}` : 'some lines'} not tied to a step`);
|
|
388
|
+
return { level: reasons.length ? 'partly explained' : 'explained', reasons };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// ── Python helpers: balanced text across lines, multi-line `def` headers, docstrings ─────────────────
|
|
392
|
+
/** Text from lines[i] at column `col` until brackets balance (strings skipped). Returns { text, end } (end line index). */
|
|
393
|
+
function pyBalanced(lines, i, col) {
|
|
394
|
+
let depth = 0, text = '', quote = null;
|
|
395
|
+
for (let j = i; j < lines.length; j++) {
|
|
396
|
+
const l = j === i ? lines[j].slice(col) : lines[j];
|
|
397
|
+
for (let k = 0; k < l.length; k++) {
|
|
398
|
+
const c = l[k];
|
|
399
|
+
if (quote) { if (c === '\\') k++; else if (c === quote) quote = null; continue; }
|
|
400
|
+
if (c === '"' || c === "'") quote = c;
|
|
401
|
+
else if (c === '#') break;
|
|
402
|
+
else if ('([{'.includes(c)) depth++;
|
|
403
|
+
else if (')]}'.includes(c)) depth--;
|
|
404
|
+
}
|
|
405
|
+
text += (j === i ? '' : '\n') + l;
|
|
406
|
+
quote = null; // Python strings do not span lines without triple quotes; triple-quoted args are rare in headers
|
|
407
|
+
if (depth <= 0) return { text, end: j };
|
|
408
|
+
}
|
|
409
|
+
return { text, end: lines.length - 1 };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** A `def name(` header starting at lines[i], `open` = column of `(`. Returns { params, returns, after, endLine } or null. */
|
|
413
|
+
function pyHeader(lines, i, open) {
|
|
414
|
+
let depth = 0, quote = null, params = '', closed = false, tail = '';
|
|
415
|
+
for (let j = i; j < lines.length && j < i + 80; j++) {
|
|
416
|
+
const l = lines[j];
|
|
417
|
+
for (let k = j === i ? open : 0; k < l.length; k++) {
|
|
418
|
+
const c = l[k];
|
|
419
|
+
if (!closed) {
|
|
420
|
+
if (quote) { params += c; if (c === '\\') { params += l[k + 1] ?? ''; k++; } else if (c === quote) quote = null; continue; }
|
|
421
|
+
if (c === '#') break;
|
|
422
|
+
if (c === '"' || c === "'") { quote = c; params += c; continue; }
|
|
423
|
+
if (c === '(') { if (depth++ === 0) continue; }
|
|
424
|
+
else if (c === ')') { if (--depth === 0) { closed = true; continue; } }
|
|
425
|
+
params += c;
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
// After the parameter list: `-> type` (brackets may wrap lines), then the header's own colon.
|
|
429
|
+
if (c === '#' && depth === 0) break;
|
|
430
|
+
if ('([{'.includes(c)) depth++;
|
|
431
|
+
else if (')]}'.includes(c)) depth--;
|
|
432
|
+
if (c === ':' && depth === 0) {
|
|
433
|
+
const ret = tail.trim().replace(/^->\s*/, '').replace(/\s+/g, ' ').trim();
|
|
434
|
+
return { params: params.replace(/\s+/g, ' ').trim(), returns: ret || null, after: l.slice(k + 1), endLine: j };
|
|
435
|
+
}
|
|
436
|
+
tail += c;
|
|
437
|
+
}
|
|
438
|
+
if (!closed) params += ' ';
|
|
439
|
+
else tail += ' ';
|
|
440
|
+
}
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The function's docstring (first statement), as plain text: its first paragraph, without Args/Returns sections. */
|
|
445
|
+
function pyDocstring(lines, from) {
|
|
446
|
+
let j = from;
|
|
447
|
+
while (j < lines.length && (!lines[j].trim() || /^\s*#/.test(lines[j]))) j++;
|
|
448
|
+
const first = lines[j]?.trim();
|
|
449
|
+
const m = first?.match(/^([rRuU]?)("""|\'\'\'|"|')/);
|
|
450
|
+
if (!m) return null;
|
|
451
|
+
const q = m[2];
|
|
452
|
+
let text = first.slice(m[0].length);
|
|
453
|
+
if (text.includes(q)) text = text.slice(0, text.indexOf(q));
|
|
454
|
+
else {
|
|
455
|
+
if (q.length === 1) return null;
|
|
456
|
+
for (let k = j + 1; k < lines.length && k < j + 60; k++) {
|
|
457
|
+
const at = lines[k].indexOf(q);
|
|
458
|
+
if (at >= 0) { text += '\n' + lines[k].slice(0, at); break; }
|
|
459
|
+
text += '\n' + lines[k];
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return cleanDoc(text);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** First paragraph of a doc comment, whitespace collapsed, without parameter sections. Null when empty. */
|
|
466
|
+
function cleanDoc(text) {
|
|
467
|
+
const para = [];
|
|
468
|
+
for (const raw of String(text).split('\n')) {
|
|
469
|
+
const t = raw.replace(/^\s*(\*|\/\/\/?|#)?\s?/, '').trim();
|
|
470
|
+
if (/^(@\w+|:(param|return|rtype|raises|type)\b|(Args|Arguments|Parameters|Returns|Raises|Yields|Example|Examples|Note|Notes)\s*:|<\/?(summary|param|returns)\b)/i.test(t)) break;
|
|
471
|
+
if (!t) { if (para.length) break; continue; }
|
|
472
|
+
para.push(t.replace(/<\/?summary>/g, ''));
|
|
473
|
+
}
|
|
474
|
+
const s = para.join(' ').replace(/\s+/g, ' ').trim();
|
|
475
|
+
if (!s) return null;
|
|
476
|
+
return s.length > 300 ? `${s.slice(0, 299)}…` : s;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// A doc comment directly above a function (a /** block, /// lines, Go // lines, Ruby # lines), skipping annotations.
|
|
480
|
+
function leadingDoc(lines, fnLine, language) {
|
|
481
|
+
let k = fnLine - 2;
|
|
482
|
+
while (k >= 0 && /^\s*(@|#\[|\[[A-Z])/.test(lines[k])) k--; // annotations and attributes
|
|
483
|
+
if (k < 0) return null;
|
|
484
|
+
if (/\*\/\s*$/.test(lines[k])) {
|
|
485
|
+
const end = k;
|
|
486
|
+
while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
|
|
487
|
+
if (k < 0) return null;
|
|
488
|
+
return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*\*/, '').replace(/\*\/\s*$/, ''));
|
|
489
|
+
}
|
|
490
|
+
const lineDoc = language === 'go' ? /^\s*\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
|
|
491
|
+
const got = [];
|
|
492
|
+
while (k >= 0 && lineDoc.test(lines[k])) got.unshift(lines[k--]);
|
|
493
|
+
return got.length ? cleanDoc(got.join('\n')) : null;
|
|
494
|
+
}
|
|
495
|
+
|
|
263
496
|
/** Mark functions that a decorator or annotation binds to an HTTP route. */
|
|
264
497
|
function annotateRoutes(fns, src) {
|
|
265
498
|
// Decorated handlers: @app.get("/x") / @router.post (Python), @GetMapping (Spring), [HttpGet] (ASP.NET), @Get() (NestJS).
|
|
266
499
|
const lines = src.split('\n');
|
|
267
500
|
for (const fn of fns) {
|
|
268
501
|
if (fn.route) continue;
|
|
269
|
-
|
|
270
|
-
|
|
502
|
+
// Python collects whole decorators (they can span lines); other languages look at the few lines above.
|
|
503
|
+
const above = fn.decorators
|
|
504
|
+
? [...fn.decorators].reverse()
|
|
505
|
+
: lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
|
|
506
|
+
for (const l of above) {
|
|
271
507
|
let m;
|
|
272
508
|
if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
|
|
273
509
|
if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
|
|
@@ -879,16 +1115,45 @@ function splitStatements(body, baseLine) {
|
|
|
879
1115
|
else if (c === '{') {
|
|
880
1116
|
const close = matchClose(src, i);
|
|
881
1117
|
if (close < 0) { i = src.length; break; }
|
|
1118
|
+
// A brace after a block header (if/for/else/try/=>/a closing paren …) is a code block and ends the
|
|
1119
|
+
// statement. Any other brace is part of an expression (an object literal, destructuring, a struct
|
|
1120
|
+
// literal, JSX): keep reading to the end of the statement.
|
|
1121
|
+
const prefix = src.slice(start, i).trim();
|
|
1122
|
+
const blockHeader = !prefix
|
|
1123
|
+
|| /^(?:if|else|for|foreach|while|switch|try|catch|finally|do|function|class|fn|func|match|loop|unsafe|impl|struct|enum|trait|mod|go|defer|select|using|lock|synchronized|namespace|interface|record|object|init|when|static|async\s+function|export\s+(?:default\s+)?(?:function|class))\b/.test(prefix)
|
|
1124
|
+
|| (/(?:\)|=>|\belse|\btry|\bdo|\bfinally|\bloop|\bunsafe|\bdefer)\s*$/.test(prefix) && !/^(?:return|throw|yield)\b/.test(prefix) && !/[=:]\s*\w*\s*\(/.test(prefix.replace(/=>\s*$/, '')) )
|
|
1125
|
+
|| (/=>\s*$/.test(prefix));
|
|
1126
|
+
if (depth === 0 && !blockHeader) { i = close; continue; }
|
|
882
1127
|
i = close;
|
|
883
1128
|
if (depth === 0) {
|
|
884
1129
|
// An if/else chain continues past a closing brace.
|
|
885
1130
|
const rest = src.slice(i + 1).match(/^\s*else\b/);
|
|
886
1131
|
if (!rest) { i++; break; }
|
|
887
1132
|
}
|
|
888
|
-
} else if (c === ';' && depth === 0) {
|
|
1133
|
+
} else if (c === ';' && depth === 0) {
|
|
1134
|
+
// Go: `if err := open(); err != nil {` and `for i := 0; i < n; i++ {` keep their header together.
|
|
1135
|
+
if (/^\s*(?:if|for|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes('{') && /\{/.test(src.slice(i, src.indexOf('\n', i) < 0 ? undefined : src.indexOf('\n', i)))) continue;
|
|
1136
|
+
i++; break;
|
|
1137
|
+
}
|
|
1138
|
+
else if (c === '\n' && depth === 0) {
|
|
1139
|
+
// Newline-terminated statements (Go, Kotlin, JavaScript without semicolons): a complete line
|
|
1140
|
+
// ends the statement unless the next line continues it.
|
|
1141
|
+
const before = src.slice(start, i).trimEnd();
|
|
1142
|
+
// Only the start of the next line matters; never copy the rest of the source (that made this quadratic).
|
|
1143
|
+
let j = i + 1;
|
|
1144
|
+
while (j < src.length && (src[j] === ' ' || src[j] === '\t' || src[j] === '\n' || src[j] === '\r')) j++;
|
|
1145
|
+
const after = src.slice(j, j + 24);
|
|
1146
|
+
if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) { i++; break; }
|
|
1147
|
+
}
|
|
889
1148
|
}
|
|
890
|
-
const
|
|
891
|
-
|
|
1149
|
+
const raw = src.slice(start, i);
|
|
1150
|
+
const text = raw.trim();
|
|
1151
|
+
// Offsets are into the body as given (comments are blanked in place, so lengths are unchanged).
|
|
1152
|
+
// Trim trailing whitespace and semicolons by scanning back (the /[\s;]+$/ regex is quadratic on long bodies).
|
|
1153
|
+
let e = raw.length;
|
|
1154
|
+
while (e > 0 && /[\s;]/.test(raw[e - 1])) e--;
|
|
1155
|
+
const end = start + e;
|
|
1156
|
+
if (text) out.push({ text, line: baseLine + lineAt(src, start) - 1, endLine: baseLine + lineAt(src, Math.max(start, end - 1)) - 1, start, end });
|
|
892
1157
|
}
|
|
893
1158
|
return out;
|
|
894
1159
|
}
|
|
@@ -1163,8 +1428,18 @@ function readPythonBody(body, inputs) {
|
|
|
1163
1428
|
|
|
1164
1429
|
const RB_OPENER = /^(if|unless|while|until|case|begin|for|def|class|module)\b/;
|
|
1165
1430
|
const rbCodeOnly = (l) => l.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""').replace(/(^|\s)#.*$/, '$1');
|
|
1431
|
+
/** A Python line without its trailing # comment. Outside a string, # always starts a comment in Python. */
|
|
1432
|
+
export function pyNoComment(l) {
|
|
1433
|
+
for (let i = 0; i < l.length; i++) {
|
|
1434
|
+
const c = l[i];
|
|
1435
|
+
if (c === '"' || c === '\'') { i = skipString(l, i); continue; }
|
|
1436
|
+
if (c === '#') return l.slice(0, i).replace(/\s+$/, '');
|
|
1437
|
+
}
|
|
1438
|
+
return l;
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1166
1441
|
/** A Ruby line without its trailing # comment (strings kept as written). */
|
|
1167
|
-
function rbNoComment(l) {
|
|
1442
|
+
export function rbNoComment(l) {
|
|
1168
1443
|
for (let i = 0; i < l.length; i++) {
|
|
1169
1444
|
const c = l[i];
|
|
1170
1445
|
if (c === '"' || c === '\'') { i = skipString(l, i); continue; }
|
|
@@ -1408,6 +1683,103 @@ function decisionSource(name, inputs, rules, otherwise) {
|
|
|
1408
1683
|
* Read source code into a searchable list of items: each function, the decision rules it makes
|
|
1409
1684
|
* (as ThunderLang and plain English), the errors it raises, and the tests that exist.
|
|
1410
1685
|
*/
|
|
1686
|
+
const BOOL_RETURN = /^(bool|boolean|Boolean|bool\?|Boolean\?|kotlin\.Boolean|System\.Boolean)$/;
|
|
1687
|
+
const LOGIC_OR_COMPARE = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|^\s*!)/;
|
|
1688
|
+
/** Read a one-expression boolean body as a decision rule, or return null. Never guesses past one expression. */
|
|
1689
|
+
function readPredicate(fn, lang, names, code) {
|
|
1690
|
+
let expr = null, line = fn.line;
|
|
1691
|
+
if (lang === 'python') {
|
|
1692
|
+
const body = (fn.pyBody || []).filter((l) => !/^(?:[rbuf]{0,2})(?:"""|\'\'\'|"|')/.test(l.text)); // drop docstrings
|
|
1693
|
+
if (body.length !== 1) return null;
|
|
1694
|
+
const m = body[0].text.match(/^return\s+(.+)$/);
|
|
1695
|
+
if (!m) return null;
|
|
1696
|
+
expr = m[1]; line = body[0].line;
|
|
1697
|
+
} else if (lang === 'ruby') {
|
|
1698
|
+
const body = (fn.rbBody || []).filter((l) => l.text && !/^#/.test(l.text) && l.text !== 'end');
|
|
1699
|
+
if (body.length !== 1) return null;
|
|
1700
|
+
expr = body[0].text.replace(/^return\s+/, ''); line = body[0].line;
|
|
1701
|
+
if (/^(if|unless|case|while|until)\b|\bthen\b/.test(expr)) return null;
|
|
1702
|
+
} else {
|
|
1703
|
+
if (typeof fn.body !== 'string') return null;
|
|
1704
|
+
const body = stripComments(fn.body).trim();
|
|
1705
|
+
let m = body.match(/^return\s+([^;{}]+?);?\s*$/s);
|
|
1706
|
+
if (!m && lang === 'rust') m = body.match(/^([^;{}]+?)\s*$/s);
|
|
1707
|
+
if (!m) return null;
|
|
1708
|
+
expr = m[1].replace(/\s+/g, ' ').trim();
|
|
1709
|
+
if (fn.bodyStart != null) line = lineAt(code, fn.bodyStart + Math.max(0, fn.body.indexOf(m[1].trim().slice(0, 12))));
|
|
1710
|
+
}
|
|
1711
|
+
if (!expr || /^(true|false|True|False)$/.test(expr)) return null;
|
|
1712
|
+
if (!(BOOL_RETURN.test(String(fn.returns || '').trim()) || LOGIC_OR_COMPARE.test(expr) || /\?$/.test(fn.name))) return null;
|
|
1713
|
+
const when = toThunderCondition(expr.replace(/\?$/, ''), names);
|
|
1714
|
+
return when ? { rule: { when, result: 'true', line } } : null;
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
const TRIVIA_LINE = /^\s*(?:$|\/\/|#(?!\[)|\/\*|\*|\*\/|[{}()\[\];,]+\s*$|\}\s*else\b.*\{\s*$|else\s*:?\s*\{?\s*$|end\s*$|"""|''')/;
|
|
1718
|
+
|
|
1719
|
+
/** The original lines a function body spans: [firstLine, lastLine] (1-based, inclusive). */
|
|
1720
|
+
function bodyRange(fn, lang, code) {
|
|
1721
|
+
if (lang === 'python' && fn.pyBody?.length) return [fn.pyBody[0].line, fn.pyBody[fn.pyBody.length - 1].line];
|
|
1722
|
+
if (lang === 'ruby' && fn.rbBody?.length) return [fn.rbBody[0].line, fn.rbBody[fn.rbBody.length - 1].line];
|
|
1723
|
+
// Expression bodies (=> expr / = expr) are read through a stand-in "return expr"; measure the real expression.
|
|
1724
|
+
if (fn.exprBody != null && fn.bodyStart != null) return [lineAt(code, fn.bodyStart), lineAt(code, fn.bodyStart + Math.max(0, fn.exprBody - 1))];
|
|
1725
|
+
if (typeof fn.body === 'string' && fn.bodyStart != null) {
|
|
1726
|
+
// The body starts right after "{", usually on the signature line; start counting at the first code line.
|
|
1727
|
+
const lead = fn.body.match(/^[ \t]*\r?\n/) ? 1 : 0;
|
|
1728
|
+
return [lineAt(code, fn.bodyStart) + lead, lineAt(code, fn.bodyStart + Math.max(0, fn.body.length - 1))];
|
|
1729
|
+
}
|
|
1730
|
+
return null;
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
/** Make a step span absolute in the file. Offsets are exact except for PHP, which is read after normalizing. */
|
|
1734
|
+
function anchorSpan(span, fn, lang) {
|
|
1735
|
+
if (!span) return;
|
|
1736
|
+
if (fn.exprBody != null && span.start != null) {
|
|
1737
|
+
// Stand-in body: shift past the synthetic "return " so offsets land on the real expression.
|
|
1738
|
+
span.start = Math.max(0, span.start - 7) + fn.bodyStart; span.end = Math.min(fn.bodyStart + fn.exprBody, span.end - 7 + fn.bodyStart); span.exact = 'offset'; return;
|
|
1739
|
+
}
|
|
1740
|
+
if (span.start != null && fn.bodyStart != null && lang !== 'php') { span.start += fn.bodyStart; span.end += fn.bodyStart; span.exact = 'offset'; }
|
|
1741
|
+
else { delete span.start; delete span.end; span.exact = 'lines'; }
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
1745
|
+
let stmts = [];
|
|
1746
|
+
try {
|
|
1747
|
+
if (lang === 'python') stmts = indentStatements(fn.pyBody, { depthKey: 'indent' });
|
|
1748
|
+
// For steps, elsif / else / rescue / ensure sit beside their if or begin (the rule reader keeps the raw depth).
|
|
1749
|
+
else if (lang === 'ruby') stmts = indentStatements(fn.rbBody.map((l) => (/^(elsif|else|rescue|ensure)\b/.test(l.text) ? { ...l, depth: Math.max(0, l.depth - 1) } : l)), { depthKey: 'depth' });
|
|
1750
|
+
else if (typeof fn.body === 'string' && fn.bodyStart != null) stmts = braceStatements(splitStatements(lang === 'kotlin' ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), splitStatements);
|
|
1751
|
+
} catch { return null; }
|
|
1752
|
+
if (!stmts.length) return null;
|
|
1753
|
+
const r = stepsFrom(stmts);
|
|
1754
|
+
// Anchoring: every step (and child step) points at its exact place in the original file.
|
|
1755
|
+
const walk = (list) => { for (const st of list) { anchorSpan(st.span, fn, lang); if (st.children) walk(st.children); } };
|
|
1756
|
+
walk(r.steps);
|
|
1757
|
+
for (const sk of r.skipped) anchorSpan(sk, fn, lang);
|
|
1758
|
+
const range = bodyRange(fn, lang, code);
|
|
1759
|
+
if (range) {
|
|
1760
|
+
const covered = new Set();
|
|
1761
|
+
for (const sp of [...r.steps.map((x) => x.span), ...r.skipped]) if (sp) for (let l = sp.startLine; l <= sp.endLine; l++) covered.add(l);
|
|
1762
|
+
let real = 0, hit = 0;
|
|
1763
|
+
const missing = [];
|
|
1764
|
+
for (let l = range[0]; l <= range[1]; l++) {
|
|
1765
|
+
const t = srcLines[l - 1] ?? '';
|
|
1766
|
+
if (TRIVIA_LINE.test(t)) continue;
|
|
1767
|
+
real++;
|
|
1768
|
+
if (covered.has(l)) hit++; else if (missing.length < 5) missing.push(l);
|
|
1769
|
+
}
|
|
1770
|
+
r.anchor = { schema: 'thunder-anchor-v1', bodyLines: range, codeLines: real, coveredLines: hit, coverage: real ? Math.round((hit / real) * 1000) / 1000 : 1, missing };
|
|
1771
|
+
}
|
|
1772
|
+
for (const st of r.steps) {
|
|
1773
|
+
if (st.kind !== 'branch' || !st.cond) continue;
|
|
1774
|
+
// A bare yes/no property (`order.refunded`) already reads as a sentence from the step itself; keep it.
|
|
1775
|
+
const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ''));
|
|
1776
|
+
const cond = bareProperty ? null : toThunderCondition(st.cond, names);
|
|
1777
|
+
if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? 'not: ' : ''}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, ' is not empty').replace(/ is ""/g, ' is empty')}${inner || ''}`);
|
|
1778
|
+
delete st.cond; delete st.negate;
|
|
1779
|
+
}
|
|
1780
|
+
return r;
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1411
1783
|
export function readCode(source, { language, file = '' } = {}) {
|
|
1412
1784
|
const src = String(source ?? '');
|
|
1413
1785
|
if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
|
|
@@ -1417,6 +1789,8 @@ export function readCode(source, { language, file = '' } = {}) {
|
|
|
1417
1789
|
// PHP is read after `$name` -> `name` and `->` -> `.`; every line stays on its line.
|
|
1418
1790
|
const code = lang === 'php' ? normalizePhp(src) : src;
|
|
1419
1791
|
const items = [];
|
|
1792
|
+
const srcLines = src.split('\n');
|
|
1793
|
+
const codeLines = code.split('\n');
|
|
1420
1794
|
for (const fn of findFunctions(code, lang)) {
|
|
1421
1795
|
const inputs = fn.params;
|
|
1422
1796
|
const names = inputs.map((p) => p.name);
|
|
@@ -1425,6 +1799,12 @@ export function readCode(source, { language, file = '' } = {}) {
|
|
|
1425
1799
|
: lang === 'ruby'
|
|
1426
1800
|
? readRubyBody(fn.rbBody, names)
|
|
1427
1801
|
: readBraceStatements(splitStatements(lang === 'kotlin' ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), lang, names);
|
|
1802
|
+
// Predicates: a body that is only `return <true/false expression>` (Rust: a tail expression; Ruby:
|
|
1803
|
+
// an implicit last value) reads as "true when <expression>, otherwise false".
|
|
1804
|
+
if (!read.rules.length && !read.otherwise) {
|
|
1805
|
+
const pred = readPredicate(fn, lang, names, code);
|
|
1806
|
+
if (pred) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; }
|
|
1807
|
+
}
|
|
1428
1808
|
const isDecision = read.rules.length > 0 && !!read.otherwise;
|
|
1429
1809
|
const guards = read.guards || [];
|
|
1430
1810
|
// In a function that is not a pure decision, early fixed returns are still rules worth reading.
|
|
@@ -1433,9 +1813,15 @@ export function readCode(source, { language, file = '' } = {}) {
|
|
|
1433
1813
|
guards.sort((a, b) => a.line - b.line);
|
|
1434
1814
|
}
|
|
1435
1815
|
const guardNote = guards.length ? ` It checks ${guards.length} condition${guards.length === 1 ? '' : 's'} first: ${guards.map((g) => g.says.replace(/\.$/, '')).join('; ')}.` : '';
|
|
1816
|
+
// The author's own words for what the function means (docstring or doc comment), kept apart from the
|
|
1817
|
+
// reading inferred from the code so a view can show both and say which is which.
|
|
1818
|
+
const doc = fn.doc ?? (lang === 'python' ? null : leadingDoc(codeLines, fn.line, lang));
|
|
1436
1819
|
const base = {
|
|
1437
|
-
id: `${fn.name}:${fn.line}`, name: fn.name,
|
|
1820
|
+
id: `${fn.name}:${fn.line}`, name: fn.name, label: displayLabel(fn.name), line: fn.line,
|
|
1821
|
+
// Framework plumbing (a database session, the request, a context) is marked so views can leave it out of "You give it".
|
|
1822
|
+
inputs: inputs.map((p) => (PLUMBING.test(p.name) || PLUMBING_TYPE.test(String(p.type ?? '')) ? { ...p, plumbing: true } : p)), returns: simpleType(fn.returns),
|
|
1438
1823
|
...(fn.route ? { route: fn.route } : {}),
|
|
1824
|
+
...(doc ? { doc } : {}),
|
|
1439
1825
|
provenance: 'inferred-from-code',
|
|
1440
1826
|
};
|
|
1441
1827
|
if (isDecision) {
|
|
@@ -1447,9 +1833,14 @@ export function readCode(source, { language, file = '' } = {}) {
|
|
|
1447
1833
|
unread: read.unread,
|
|
1448
1834
|
});
|
|
1449
1835
|
} else {
|
|
1836
|
+
const st = functionSteps(fn, lang, code, names, srcLines);
|
|
1450
1837
|
items.push({
|
|
1451
1838
|
...base, kind: 'function', status: 'signature-only',
|
|
1839
|
+
...(st ? { steps: st.steps, stepsMore: st.more, stepsReadable: Math.round(st.readable * 100) / 100, ...(st.anchor ? { anchor: st.anchor } : {}) } : {}),
|
|
1452
1840
|
says: fn.route ? `Handles ${fn.route.method} ${fn.route.path || '(this controller\'s path)'}.${guardNote}` : `${fn.name} takes ${inputs.length ? inputs.map((p) => p.type && !/[<>\[\]]/.test(p.type) ? `${p.name} (${p.type})` : p.name).join(', ') : 'no inputs'}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ''}. ${guards.length ? '' : ' Its body does more than choose between fixed answers, so no rules are shown.'}${guardNote}`,
|
|
1841
|
+
// The same facts as separate fields, so a view never has to cut sentences out of `says`.
|
|
1842
|
+
headline: fn.route ? `Handles ${fn.route.method} ${fn.route.path || "(this controller's path)"}.` : `${displayLabel(fn.name)} takes ${inputs.length ? inputs.map((p) => p.name).join(', ') : 'no inputs'}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ''}.`,
|
|
1843
|
+
...(guards.length ? {} : { note: 'Its body does more than choose between fixed answers, so no rules are shown.' }),
|
|
1453
1844
|
guards, unread: read.unread,
|
|
1454
1845
|
});
|
|
1455
1846
|
}
|
|
@@ -1459,6 +1850,7 @@ export function readCode(source, { language, file = '' } = {}) {
|
|
|
1459
1850
|
for (const e of facts?.errors || []) items.push({ id: `error:${e.name}:${e.line}`, kind: 'error', name: e.name, line: e.line, status: 'read', says: /\s/.test(e.name) ? `Can fail with the error "${e.name}".` : `Raises ${e.name}.`, provenance: 'inferred-from-code' });
|
|
1460
1851
|
for (const t of facts?.tests || []) items.push({ id: `test:${t.name}:${t.line}`, kind: 'test', name: t.name, line: t.line, status: 'read', says: `A test named "${t.name}".`, provenance: 'inferred-from-code' });
|
|
1461
1852
|
items.sort((a, b) => a.line - b.line);
|
|
1853
|
+
for (const it of items) if (it.kind === 'function' || it.kind === 'decision') it.completeness = completenessOf(it);
|
|
1462
1854
|
const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
|
|
1463
1855
|
for (const it of items) { counts[it.kind]++; if (it.status === 'partial') counts.partial++; if (it.guards?.length) counts.guarded++; if (it.route) counts.route++; }
|
|
1464
1856
|
return {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Diagnostic, ObligationResolution, TestReport } from './index.js';
|
|
2
|
+
export const REVIEW_ATLAS_SCHEMA: 'intent-review-atlas-v1';
|
|
3
|
+
export type ReviewFile = { path: string; source: string };
|
|
4
|
+
export type ReviewStatus = 'invalid' | 'failed' | 'needs-evidence' | 'checked';
|
|
5
|
+
export interface ReviewAtlasRow {
|
|
6
|
+
file: string; sourceHash: string; missionId: string | null; mission: string; goal: string;
|
|
7
|
+
risk: 'high' | 'medium' | 'low'; riskFactors: string[];
|
|
8
|
+
claims: ObligationResolution[]; diagnostics: Diagnostic[]; tests: TestReport;
|
|
9
|
+
issues: string[]; status: ReviewStatus; nextActions: string[];
|
|
10
|
+
snapshot: { status: 'not-imported' | 'ambiguous' | 'missing' | 'unavailable' | 'stale' | 'reported-failure' | 'matched'; reason: string; file?: string; sourceHash?: string | null; compilerVersion?: string | null };
|
|
11
|
+
}
|
|
12
|
+
export interface ReviewAtlas {
|
|
13
|
+
schema: typeof REVIEW_ATLAS_SCHEMA; compilerVersion: string; product: string | null; scope: string;
|
|
14
|
+
files: ReviewAtlasRow[];
|
|
15
|
+
summary: { files: number; checked: number; failed: number; invalid: number; needsEvidence: number; tests: number; testsPassed: number; testsFailed: number; claims: number; verifiedClaims: number; staleSnapshots: number };
|
|
16
|
+
}
|
|
17
|
+
export function buildReviewAtlas(files: ReviewFile[], opts?: { product?: string; evidence?: unknown }): ReviewAtlas;
|
|
18
|
+
export function renderReviewBrief(atlas: ReviewAtlas, opts?: { limit?: number }): string;
|
|
19
|
+
export function reviewAtlasExitCode(atlas: ReviewAtlas, opts?: { strict?: boolean }): number;
|