@skillstech/thunderlang 1.0.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2568 -462
  4. package/dist/index.cjs +7562 -5084
  5. package/dist/learn.cjs +16994 -8339
  6. package/intent-graph.schema.json +11 -0
  7. package/package.json +6 -2
  8. package/src/cli-home.mjs +242 -0
  9. package/src/cli.mjs +241 -89
  10. package/src/codegen.mjs +145 -55
  11. package/src/conformance.mjs +15 -6
  12. package/src/core/check.mjs +725 -0
  13. package/src/core/cli.mjs +184 -0
  14. package/src/core/diagnostics.mjs +82 -0
  15. package/src/core/engine-core.mjs +572 -0
  16. package/src/core/engine-values.mjs +1054 -0
  17. package/src/core/engine-worker.mjs +15 -0
  18. package/src/core/engine.mjs +63 -0
  19. package/src/core/format.mjs +20 -0
  20. package/src/core/from-python.mjs +645 -0
  21. package/src/core/index.mjs +39 -0
  22. package/src/core/lexer.mjs +115 -0
  23. package/src/core/parser.mjs +742 -0
  24. package/src/core/project.mjs +177 -0
  25. package/src/core/round-trip.mjs +150 -0
  26. package/src/core/runtime-python.mjs +801 -0
  27. package/src/core/runtime-typescript.mjs +119 -0
  28. package/src/core/target-python.mjs +487 -0
  29. package/src/core/target-typescript.mjs +466 -0
  30. package/src/core/typescript-run.mjs +114 -0
  31. package/src/core.d.ts +5 -2
  32. package/src/core.mjs +5 -2
  33. package/src/data-schema.mjs +8 -1
  34. package/src/emit.mjs +1 -1
  35. package/src/evidence.mjs +1 -1
  36. package/src/expr.mjs +81 -4
  37. package/src/form-words.mjs +2 -0
  38. package/src/index.d.ts +8 -1
  39. package/src/index.mjs +5 -1
  40. package/src/intent-schema.mjs +1 -0
  41. package/src/learn-lessons.mjs +245 -1
  42. package/src/learn.d.mts +8 -0
  43. package/src/learn.mjs +40 -4
  44. package/src/mcp.mjs +23 -0
  45. package/src/meaning.mjs +45 -6
  46. package/src/model.d.mts +7 -3
  47. package/src/model.mjs +19 -6
  48. package/src/money.d.mts +18 -0
  49. package/src/money.mjs +124 -0
  50. package/src/plain-contract.mjs +18 -2
  51. package/src/read-level.mjs +146 -0
  52. package/src/read.d.mts +11 -0
  53. package/src/read.mjs +40 -6
  54. package/src/review-comment.d.mts +16 -0
  55. package/src/review-comment.mjs +145 -0
  56. package/src/say-less.mjs +1432 -0
  57. package/src/system.mjs +153 -44
  58. package/src/target-cs.mjs +39 -34
  59. package/src/target-elixir.mjs +40 -30
  60. package/src/target-go.mjs +41 -36
  61. package/src/target-java.mjs +34 -27
  62. package/src/target-kotlin.mjs +43 -35
  63. package/src/target-py.mjs +57 -55
  64. package/src/target-result.d.mts +48 -0
  65. package/src/target-result.mjs +112 -0
  66. package/src/target-rust.mjs +42 -38
  67. package/src/target-scala.mjs +45 -35
  68. package/src/target-ts.mjs +37 -45
  69. package/src/target-types.mjs +41 -5
  70. package/src/target-util.mjs +55 -2
  71. package/src/term.mjs +89 -0
  72. package/src/trace-cli.mjs +58 -0
  73. package/src/trace-fs.mjs +76 -0
  74. package/src/trace.mjs +261 -0
  75. package/src/translate.d.mts +3 -0
  76. package/src/translate.mjs +62 -32
  77. package/src/try-cli.mjs +225 -0
  78. package/src/why-cli.mjs +41 -0
  79. package/src/why.d.mts +38 -0
  80. package/src/why.mjs +613 -0
  81. package/src/write-steps.mjs +22 -5
@@ -0,0 +1,146 @@
1
+ // thunder read --level: the five reading levels in the terminal (big-picture, flow, details, text, original).
2
+ // Every level comes from readLevel() in model.mjs, the same compiler model OpenThunder's "Read in Thunder" shows, so
3
+ // the terminal never says something the picture doesn't. This file only lays it out as text. A step Thunder could
4
+ // not explain is marked, never smoothed over.
5
+ import { LEVELS } from './visual.mjs';
6
+ import { readLevel } from './model.mjs';
7
+
8
+ const squash = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
9
+ const at = (file, lines) => (file ? `${file}${lines?.[0] ? `:${lines[0]}` : ''}` : '');
10
+ const lineNote = (n) => (n?.line ? ` (line ${n.line})` : '');
11
+ const list = (xs) => xs.filter(Boolean).join(', ');
12
+
13
+ /** Find an action, rule, or Thing by its label (forgiving: case, spaces, and _ do not matter) or by its id. */
14
+ /** The level closest to a mistyped one, or null. */
15
+ export function nearestLevel(word) {
16
+ const d = (a, b) => { const m = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]); for (let j = 1; j <= b.length; j++) m[0][j] = j; for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); return m[a.length][b.length]; };
17
+ const best = LEVELS.map((l) => [l.id, d(String(word).toLowerCase(), l.id)]).sort((x, y) => x[1] - y[1])[0];
18
+ return best && best[1] <= 2 ? best[0] : null;
19
+ }
20
+
21
+ export function findFocus(model, name) {
22
+ if (!name) return { id: null };
23
+ const want = squash(name);
24
+ const pool = [...model.members.filter((m) => m.kind !== 'setup'), ...model.things];
25
+ const exact = pool.filter((x) => x.id === name || squash(x.label) === want || squash(x.name) === want);
26
+ if (exact.length === 1) return { id: exact[0].id };
27
+ if (exact.length > 1) return { error: `"${name}" names ${exact.length} things: ${exact.map((x) => `${x.label} (${at(x.file, x.lines)})`).join(', ')}. Use one of their ids with --focus: ${exact.map((x) => x.id).join(', ')}.` };
28
+ const near = pool.filter((x) => squash(x.label).includes(want)).slice(0, 5);
29
+ return { error: `Nothing here is called "${name}".${near.length ? ` Did you mean: ${near.map((x) => `"${x.label}"`).join(', ')}?` : ''}` };
30
+ }
31
+
32
+ const MARK = { start: '▶', decision: '◆', stop: '✗', end: '■', loop: '↻', step: '•' };
33
+
34
+ /** A flow as an indented tree: questions with their yes and no branches, repeats, error handlers, and "always". */
35
+ function flowLines(flow) {
36
+ const byId = new Map(flow.nodes.map((n) => [n.id, n]));
37
+ const L = [];
38
+ const text = (n) => {
39
+ const unexplained = n.explained === false || n.does === 'code';
40
+ return `${MARK[n.kind] ?? '•'} ${n.text}${unexplained ? ' [not read: shown as code]' : ''}`;
41
+ };
42
+ const start = flow.nodes.find((n) => n.kind === 'start');
43
+ if (start) L.push(` ${text(start)}`);
44
+ const walk = (blocks, pad) => {
45
+ for (const b of blocks || []) {
46
+ const n = byId.get(b.id);
47
+ if (!n) continue;
48
+ L.push(`${pad}${text(n)}${lineNote(n)}`);
49
+ const branch = (label, xs) => {
50
+ if (!xs) return;
51
+ if (!xs.length) { L.push(`${pad} ${label} → carry on`); return; }
52
+ L.push(`${pad} ${label} →`);
53
+ walk(xs, `${pad} `);
54
+ };
55
+ if (b.yes || b.no) { branch('yes', b.yes); branch('no', b.no); }
56
+ if (b.each) walk(b.each, `${pad} `);
57
+ if (b.body) walk(b.body, `${pad} `);
58
+ for (const h of b.handlers || []) { const hn = byId.get(h.id); L.push(`${pad} ${hn ? hn.text.replace(/\?$/, '') : 'if something goes wrong'} →`); walk(h.blocks, `${pad} `); }
59
+ if (b.always) { L.push(`${pad} always, at the end →`); walk(b.always.blocks, `${pad} `); }
60
+ }
61
+ };
62
+ walk(flow.blocks, ' ');
63
+ // The end, when the tree does not already show it.
64
+ const shown = new Set(L.join('\n').match(/■ [^\n]*/g) ?? []);
65
+ for (const n of flow.nodes.filter((x) => x.kind === 'end' && !(flow.blocks || []).some((b) => b.id === x.id))) if (!shown.has(`■ ${n.text}`) && !L.some((l) => l.includes(`■ ${n.text}`))) L.push(` ${text(n)}`);
66
+ return L;
67
+ }
68
+
69
+ const whenText = (when) => (when?.length ? ` when ${when.map((w) => w.says ?? (/^if /i.test(w.question) && /^yes$/i.test(w.answer) ? w.question.replace(/^if /i, '').replace(/\?$/, '') : `${w.question.replace(/\?$/, '')}: ${w.answer}`)).join(' and ')}` : '');
70
+
71
+ /** One level as terminal text. `sources` maps a file path to its text (for the original level). */
72
+ export function renderLevel(r, { sources = {}, file = 'file' } = {}) {
73
+ const L = [`${r.name} · ${r.title}${r.file && r.scope !== 'app' ? ` (${at(r.file, r.lines)})` : ''}`, r.question, ''];
74
+ const next = (lv, focus) => `thunder read ${file} --level ${lv}${focus ? ` --focus "${focus}"` : ''}`;
75
+
76
+ if (r.needsFocus) {
77
+ L.push(r.says, '');
78
+ for (const c of r.choose.slice(0, 20)) L.push(` ${next(r.level, c.label.replace(/\?$/, ''))}`);
79
+ if (r.choose.length > 20) L.push(` …and ${r.choose.length - 20} more`);
80
+ return L.join('\n');
81
+ }
82
+
83
+ if (r.level === 'big-picture' && r.scope !== 'member') {
84
+ if (r.purpose) L.push(r.purpose, '');
85
+ for (const t of r.things) {
86
+ L.push(`${t.label}${t.doc ? `: ${t.doc}` : ''}`);
87
+ if (t.knows.length) L.push(` Knows: ${list(t.knows.map((k) => `${k.label}${k.start ? ` (${k.start})` : ''}`))}`);
88
+ if (t.can.length) L.push(` Can do: ${list(t.can.map((c) => `${c.label}${c.symbol === 'rule' ? ' (rule)' : ''}`))}`);
89
+ }
90
+ for (const x of r.resources) L.push(`${x.label} (${x.resourceType})${x.address ? `: ${x.address}` : ''}`);
91
+ const loose = [...r.actions.filter((a) => !r.things.some((t) => t.can.some((c) => c.id === a.id))), ...r.rules.filter((a) => !r.things.some((t) => t.can.some((c) => c.id === a.id))), ...r.loose];
92
+ if (loose.length) L.push(`Actions and rules: ${list(loose.map((c) => `${c.label}${c.symbol === 'rule' ? ' (rule)' : ''}`))}`);
93
+ if (r.data.length) { L.push('Data'); for (const d of r.data) L.push(` ${d.label}: ${d.choices ? d.choices.join(' | ') : list(d.knows) || '(nothing it knows)'}`); }
94
+ if (r.permissions?.length) L.push(`Permissions: ${r.permissions.length}`);
95
+ if (r.unknowns?.length) L.push(`Not read: ${r.unknowns.length} part${r.unknowns.length === 1 ? '' : 's'} Thunder could not explain (see --level details)`);
96
+ const first = r.things[0]?.can[0] ?? loose[0];
97
+ if (first) L.push('', `Next: ${next('flow', first.label.replace(/\?$/, ''))}`);
98
+ return L.join('\n').trimEnd();
99
+ }
100
+
101
+ if (r.level === 'big-picture') {
102
+ if (r.doc) L.push(r.doc, '');
103
+ if (r.owner) L.push(`Part of: ${r.owner.label}`);
104
+ if (r.route) L.push(`Reached at: ${r.route.method ?? ''} ${r.route.path ?? ''}`.trimEnd());
105
+ L.push(`You give it: ${list((r.youGive || []).map((g) => g.label ?? g)) || 'nothing'}`);
106
+ if (r.youGetBack) L.push(`You get back: ${typeof r.youGetBack === 'string' ? r.youGetBack : r.youGetBack.label ?? JSON.stringify(r.youGetBack)}`);
107
+ if (r.uses?.length) L.push(`Uses: ${list(r.uses.map((u) => u.label))}`);
108
+ if (r.usedBy?.length) L.push(`Used by: ${list(r.usedBy.map((u) => u.label))}`);
109
+ L.push('', `Next: ${next('flow', r.title.replace(/\?$/, ''))}`);
110
+ return L.join('\n');
111
+ }
112
+
113
+ if (r.level === 'flow') {
114
+ L.push(...flowLines(r.flow));
115
+ L.push('', `Next: ${next('details', r.title.replace(/\?$/, ''))}`);
116
+ return L.join('\n');
117
+ }
118
+
119
+ if (r.level === 'details') {
120
+ L.push(`You give it: ${list((r.inputs || []).map((i) => `${i.label}${i.kind ? ` (${i.kind})` : ''}`)) || 'nothing'}`);
121
+ // A rule's answers say it best ("Small fee when the days late is at most 7"); otherwise what it gives back.
122
+ if (r.answers?.length) { L.push('Answers:'); for (const x of r.answers) L.push(` ■ ${x.answer ?? x.value ?? x.text}${x.when && x.when !== 'otherwise' ? ` when ${x.when}` : x.when === 'otherwise' ? ' otherwise' : ''}`); }
123
+ else if (r.givesBack?.length) { L.push('Gives back:'); for (const g of r.givesBack) L.push(` ■ ${g.text ?? g.value ?? g.label}${whenText(g.when)}${lineNote(g)}`); }
124
+ if (r.stops?.length) { L.push('Stops:'); for (const s of r.stops) L.push(` ✗ ${s.error}${s.message ? ` "${s.message}"` : ''}${whenText(s.when)}${lineNote(s)}`); }
125
+ if (r.changes?.length) { L.push('Changes:'); for (const c of r.changes) L.push(` • ${c.text}${whenText(c.when)}${lineNote(c)}`); }
126
+ if (r.reliesOn?.length) L.push(`Relies on: ${list(r.reliesOn.map((x) => x.label ?? x.text ?? x))}`);
127
+ const open = [...(r.openQuestions || []).map((q) => q.text ?? q.says ?? q), ...(r.notLinked || []).map((x) => `${x.call ?? x.import ?? 'a call'}: ${x.why}`)];
128
+ if (r.notExplained) open.unshift(`${r.notExplained} step${r.notExplained === 1 ? '' : 's'} not read (shown as code; see --level original)`);
129
+ if (open.length) { L.push("Can't tell from the code:"); for (const q of open) L.push(` ? ${q}`); }
130
+ L.push('', r.source);
131
+ return L.join('\n');
132
+ }
133
+
134
+ if (r.level === 'text') return [...L, r.text.trimEnd()].join('\n');
135
+
136
+ // original: the exact lines Thunder read.
137
+ const src = sources[r.file];
138
+ if (!src) return [...L, `(The text of ${r.file ?? 'this file'} is not available.)`].join('\n');
139
+ const all = src.split('\n');
140
+ const [a, b] = r.lines ?? [1, all.length];
141
+ const width = String(b).length;
142
+ for (let i = a; i <= Math.min(b, all.length); i++) L.push(`${String(i).padStart(width)} │ ${all[i - 1]}`);
143
+ return L.join('\n');
144
+ }
145
+
146
+ export { LEVELS, readLevel };
package/src/read.d.mts CHANGED
@@ -33,6 +33,10 @@ export interface ReadItem {
33
33
  steps?: ReadStep[]; stepsMore?: number;
34
34
  /** Share of steps that explain the code: not `other` and not `restates`. */
35
35
  stepsReadable?: number;
36
+ /** How sure: steps put into words (`explained: true`), of every step at every depth (`totalSteps`). */
37
+ explainedSteps?: number; totalSteps?: number;
38
+ /** Inputs left out because they were not written as parameters in the signature (a macro, a type, a lifetime). */
39
+ inputsDropped?: number;
36
40
  }
37
41
  /** One plain step of a function (thunder-steps-v1). */
38
42
  export interface ReadStep {
@@ -51,6 +55,13 @@ export interface ReadStep {
51
55
  * of the statement, or `{ kind: 'code', text }` when it is not fully understood. Never guessed.
52
56
  */
53
57
  expr?: Expr;
58
+ /**
59
+ * Say less (say-less.mjs): true when the words are Thunder's own and account for the code; false when the step is
60
+ * shown as code, "code, not explained" (its `says` is then the code in backticks). Set on every step.
61
+ */
62
+ explained?: boolean;
63
+ /** When `explained` is false: why, in a few plain words ("the reader did not recognize this form", "block structure uncertain"). */
64
+ notExplainedWhy?: string;
54
65
  }
55
66
  export interface Reading {
56
67
  schema: 'thunder-reading-v1'; language: string; detected: boolean; items: ReadItem[];
package/src/read.mjs CHANGED
@@ -10,6 +10,7 @@
10
10
  // return cond ? X : Y (nested ternaries) Python: return X if cond else Y
11
11
  // Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
12
12
  // Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
13
+ import { sayLess, certainlyYesNo } from './say-less.mjs';
13
14
  import { sqlItems, sqlTemplateReason } from './sql.mjs';
14
15
  import { readDockerfile } from './infra-docker.mjs';
15
16
  import { readWorkflow } from './infra-gha.mjs';
@@ -1110,8 +1111,10 @@ function leadingDoc(lines, fnLine, language) {
1110
1111
  }
1111
1112
  if (/\*\/\s*$/.test(lines[k])) {
1112
1113
  const end = k;
1113
- while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
1114
- if (k < 0) return null;
1114
+ // (The block that ends here starts at the nearest /*; a plain /* … */ such as /*#__PURE__*/ is not a doc, and
1115
+ // a doc comment further up belongs to something else.)
1116
+ while (k >= 0 && !/\/\*/.test(lines[k])) k--;
1117
+ if (k < 0 || !/^\s*\/\*\*(?!\/)/.test(lines[k])) return null;
1115
1118
  return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*\*/, '').replace(/\*\/\s*$/, ''));
1116
1119
  }
1117
1120
  const lineDoc = language === 'go' || language === 'c' || language === 'cpp' ? /^\s*\/\/(?!\/)|^\s*\/\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
@@ -1120,6 +1123,29 @@ function leadingDoc(lines, fnLine, language) {
1120
1123
  return got.length ? cleanDoc(got.join('\n')) : null;
1121
1124
  }
1122
1125
 
1126
+ /**
1127
+ * A controller's route prefix joined to a method's path: ASP.NET `[Route("api/[controller]")]` on the class (with
1128
+ * [controller] the class name less "Controller") or Spring `@RequestMapping("/api")` on the class. A method path
1129
+ * that starts at the root (`/x`, or `~/x` in ASP.NET) keeps no prefix. With neither, the method's own path, from "/".
1130
+ */
1131
+ function withClassPrefix(lines, fnLine, path, style) {
1132
+ // ASP.NET: a method template starting at the root (/x or ~/x) replaces the controller's. Spring always joins them.
1133
+ if (style === 'aspnet' && /^~?\//.test(path)) return '/' + path.replace(/^~?\/+/, '');
1134
+ let prefix = '';
1135
+ for (let i = fnLine - 2; i >= 0; i--) {
1136
+ const c = lines[i].match(/\bclass\s+(\w+)/);
1137
+ if (!c) continue;
1138
+ for (let j = i - 1; j >= Math.max(0, i - 6); j--) {
1139
+ const t = lines[j].trim();
1140
+ const r = style === 'aspnet' ? t.match(/^\[(?:Route|RoutePrefix)\(\s*"([^"]*)"/) : t.match(/^@RequestMapping\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["']/);
1141
+ if (r) { prefix = r[1].replace(/\[controller\]/gi, c[1].replace(/Controller$/, '')); break; }
1142
+ if (t && !/^(\[|@|\/\/|\*|\/\*)/.test(t)) break;
1143
+ }
1144
+ break;
1145
+ }
1146
+ return '/' + [prefix, path].map((x) => x.replace(/^\/+|\/+$/g, '')).filter(Boolean).join('/');
1147
+ }
1148
+
1123
1149
  /** Mark functions that a decorator or annotation binds to an HTTP route. */
1124
1150
  function annotateRoutes(fns, src) {
1125
1151
  // Decorated handlers: @app.get("/x") / @router.post (Python), @GetMapping (Spring), [HttpGet] (ASP.NET), @Get() (NestJS).
@@ -1134,9 +1160,9 @@ function annotateRoutes(fns, src) {
1134
1160
  let m;
1135
1161
  if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
1136
1162
  if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
1137
- if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: m[2] || '/' }; break; }
1163
+ if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: withClassPrefix(lines, fn.line, m[2] || '', 'spring') }; break; }
1138
1164
  if ((m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'ANY').toUpperCase(), path: m[1] }; break; }
1139
- if ((m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
1165
+ if ((m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/))) { fn.route = { method: m[1].toUpperCase(), path: withClassPrefix(lines, fn.line, m[2] || '', 'aspnet') }; break; }
1140
1166
  if ((m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
1141
1167
  if (!/^(@|\[|\/\/|#|\*|\/\*)/.test(l) && l) break;
1142
1168
  }
@@ -2678,7 +2704,13 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
2678
2704
  return r;
2679
2705
  }
2680
2706
 
2681
- export function readCode(source, { language, file = '', allSteps = false } = {}) {
2707
+ export function readCode(source, opts = {}) {
2708
+ const reading = readCodeAsIs(source, opts);
2709
+ // Say less (say-less.mjs): a step stays in words only when the words account for its code; the rest is code.
2710
+ return opts.sayEverything ? reading : sayLess(reading, String(source ?? ''));
2711
+ }
2712
+
2713
+ function readCodeAsIs(source, { language, file = '', allSteps = false } = {}) {
2682
2714
  const src = String(source ?? '');
2683
2715
  if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
2684
2716
  const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, 'typescript').replace(/^js$/, 'javascript').replace(/^py$/, 'python').replace(/^(cs|c#)$/, 'csharp').replace(/^rs$/, 'rust').replace(/^golang$/, 'go').replace(/^kts?$/, 'kotlin').replace(/^rb$/, 'ruby').replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, 'sql').replace(/^(docker|containerfile)$/, 'dockerfile').replace(/^(gha|github[ -]?actions?|workflow)$/, 'github-actions').replace(/^(tf|hcl|opentofu|tofu)$/, 'terraform').replace(/^(k8s|kube|kubectl)$/, 'kubernetes').replace(/^(compose|docker[ -]?compose)$/, 'docker-compose').replace(/^(c\+\+|cxx|cc|hpp|hxx|hh)$/, 'cpp').replace(/^h$/, 'c')
@@ -2709,7 +2741,9 @@ export function readCode(source, { language, file = '', allSteps = false } = {})
2709
2741
  // an implicit last value) reads as "true when <expression>, otherwise false".
2710
2742
  if (!read.rules.length && !read.otherwise) {
2711
2743
  const pred = readPredicate(fn, lang, names, code);
2712
- if (pred) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; read.unread = []; }
2744
+ // (Only when the answer is certainly yes or no: a declared boolean result, a name asked as a question, or an
2745
+ // expression that is a comparison; `state.copy_ || state.base_` gives back an object.)
2746
+ if (pred && (certainlyYesNo(pred.rule.when, lang) || /^(?:bool|boolean|Bool|Boolean|BOOL|_Bool)$/.test(String(simpleType(fn.returns) ?? '').trim()) || /\?$/.test(fn.name))) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; read.unread = []; }
2713
2747
  }
2714
2748
  // A rule is drawn only when every statement was read into it; a body with other steps (a loop, an assignment, a
2715
2749
  // later check) is read as steps instead, so no check is silently left out of the picture.
@@ -0,0 +1,16 @@
1
+ // The pull request comment for a Thunder review (see src/review-comment.mjs).
2
+ import type { Review, ReviewItem } from './review.mjs';
3
+ export const REVIEW_MARKER: '<!-- thunder-review -->';
4
+ export const GITHUB_COMMENT_LIMIT: 65536;
5
+ export const COMMENT_TITLE: string;
6
+ /** explained: put into sentences; code: shown as the code before and after; person: Thunder cannot check it. */
7
+ export function itemHow(item: ReviewItem): 'explained' | 'code' | 'person';
8
+ export function reviewCounts(review: Review): { explained: number; code: number; person: number; notRead: number };
9
+ export function countsLine(counts: { explained: number; code: number; person: number; notRead: number }): string;
10
+ export function renderReviewComment(review: Review, options?: {
11
+ maxChars?: number;
12
+ fileUrl?: ((file: string, line: number) => string | null) | null;
13
+ notes?: string[];
14
+ footer?: string;
15
+ evidenceLines?: number;
16
+ }): string;
@@ -0,0 +1,145 @@
1
+ // The pull request comment for a Thunder review (thunder-review-v1, see review.mjs): what the change does, in plain
2
+ // sentences, grouped by the action, rule, or function it changed, with the risks first and honest counts of what was
3
+ // explained in sentences, what is only shown as code, and what a person has to check because Thunder cannot.
4
+ //
5
+ // Pure and browser-safe, with no imports, so the GitHub Action (action/thunder-review.mjs) can render a review made by
6
+ // any published compiler version. The wording comes from the review itself: this file never says "safe" or "same";
7
+ // it only repeats what the review showed and counts it.
8
+
9
+ export const REVIEW_MARKER = '<!-- thunder-review -->';
10
+ /** GitHub rejects comment bodies over 65,536 characters; stay under it with room for the marker and footer. */
11
+ export const GITHUB_COMMENT_LIMIT = 65536;
12
+ export const COMMENT_TITLE = 'Thunder review: what this change does, in plain sentences';
13
+ /** When a member no longer fits in full, at most this many of its sentences are shown. */
14
+ const COMPACT_SENTENCES = 3;
15
+ const DOCS_URL = 'https://thunderlang.dev/docs/github-action';
16
+ const SITE_URL = 'https://thunderlang.dev';
17
+
18
+ // What a person has to check because Thunder could not read or does not read it.
19
+ const CANNOT_CHECK = new Set(['unreadable', 'infrastructure', 'not-read']);
20
+ // Changes Thunder shows as the code before and after, rather than explaining in sentences.
21
+ const SHOWN_AS_CODE = new Set(['hidden', 'outside']);
22
+
23
+ /** How an item reached the reviewer: 'explained' (in sentences), 'code' (shown as code), or 'person' (cannot check). */
24
+ export function itemHow(x) {
25
+ if (CANNOT_CHECK.has(x.kind) || (x.kind === 'added' && x.severity === 'risk')) return 'person';
26
+ if (SHOWN_AS_CODE.has(x.kind)) return 'code';
27
+ return 'explained';
28
+ }
29
+
30
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
31
+
32
+ /** Honest counts for the comment's second line. Each item counts once, as in the review's own summary. */
33
+ export function reviewCounts(r) {
34
+ const c = { explained: 0, code: 0, person: 0, notRead: r.notRead?.length ?? 0 };
35
+ for (const x of r.items) c[itemHow(x)]++;
36
+ return c;
37
+ }
38
+
39
+ export function countsLine(c) {
40
+ const parts = [`${plural(c.explained, 'change')} explained in sentences`, `${c.code} shown as code (Thunder did not put ${c.code === 1 ? 'it' : 'them'} into words)`];
41
+ parts.push(`${c.person} Thunder cannot check (check ${c.person === 1 ? 'it' : 'them'} yourself)`);
42
+ if (c.notRead) parts.push(`${plural(c.notRead, 'file')} Thunder does not read`);
43
+ return `${parts.join(' · ')}.`;
44
+ }
45
+
46
+ const esc = (s) => String(s).replace(/[<>]/g, (ch) => (ch === '<' ? '&lt;' : '&gt;'));
47
+ const fence = (lines) => ['```', ...lines.map((l) => l.replace(/```/g, "'''")), '```'];
48
+ const cutLines = (lines, max) => (lines.length > max ? [...lines.slice(0, max), `… ${lines.length - max} more lines`] : lines);
49
+
50
+ function evidence(ev, maxLines) {
51
+ if (!ev) return [];
52
+ const out = [];
53
+ if (ev.counterexample) out.push(`Tried on both versions: when ${ev.counterexample.facts}, before: **${ev.counterexample.before}**, after: **${ev.counterexample.after}**.`, '');
54
+ if (ev.before?.length) out.push('Before:', ...fence(cutLines(ev.before, maxLines)));
55
+ if (ev.after?.length) out.push('After:', ...fence(cutLines(ev.after, maxLines)));
56
+ return out;
57
+ }
58
+
59
+ const HEADINGS = {
60
+ risk: ['Needs a careful look', 'A Stop removed or under new conditions, a new address, something that now reaches outside the program, or code Thunder cannot check.'],
61
+ meaning: ['Changes in meaning', 'Anything else that changes what the code does.'],
62
+ form: ['Only the form changed', 'Shown, not guessed: the same code apart from spacing, comments, or names it declares itself, or a rule with the same answer on every edge case.'],
63
+ };
64
+
65
+ /**
66
+ * Render a thunder-review-v1 review as one sticky pull request comment.
67
+ * options: { maxChars (default 60000, under GITHUB_COMMENT_LIMIT; pass more for a job summary), fileUrl(file, line) => url|null,
68
+ * notes: string[] (shown as quotes under the counts), footer, evidenceLines (per before or after block) }
69
+ * Returns the Markdown; it always starts with REVIEW_MARKER and is never longer than maxChars: members that do not fit
70
+ * are left out whole and counted ("N more not shown"), so no code block or <details> is cut in half.
71
+ */
72
+ export function renderReviewComment(r, { maxChars = 60000, fileUrl = null, notes = [], footer = '', evidenceLines = 40 } = {}) {
73
+ const where = (w) => {
74
+ const label = `\`${esc(w.file)}:${w.line}\``;
75
+ const url = fileUrl?.(w.file, w.line);
76
+ return url ? `[${label}](${url})` : label;
77
+ };
78
+ const head = [REVIEW_MARKER, `### ${COMMENT_TITLE}`, '', `**${r.says}**`, '', countsLine(reviewCounts(r)), ''];
79
+ for (const n of notes.filter(Boolean)) head.push(`> ${n}`, '');
80
+
81
+ // One block per changed action, rule, or function (a "member"), in the review's order of importance.
82
+ const blocks = [];
83
+ for (const sev of ['risk', 'meaning', 'form']) {
84
+ const list = r.items.filter((x) => x.severity === sev);
85
+ if (!list.length) continue;
86
+ const members = new Map();
87
+ for (const x of list) {
88
+ const k = `${x.where.file}\u0000${x.subject}`;
89
+ if (!members.has(k)) members.set(k, []);
90
+ members.get(k).push(x);
91
+ }
92
+ const [title, why] = HEADINGS[sev];
93
+ const open = sev === 'form' ? [`<details><summary>${title} (${list.length})</summary>`, '', `_${why}_`, ''] : [`#### ${title} (${list.length})`, '', `_${why}_`, ''];
94
+ const close = sev === 'form' ? ['</details>', ''] : [];
95
+ // Each member twice: in full, and compact (its first sentences, without the code) for when the full one no longer fits.
96
+ const memberBlocks = [...members.values()].map((xs) => {
97
+ const render = (compact) => {
98
+ const lines = [`- **${esc(xs[0].subject)}** · ${where(xs[0].where)}`];
99
+ const list = compact ? xs.slice(0, COMPACT_SENTENCES) : xs;
100
+ for (const x of list) {
101
+ const ev = sev === 'form' ? [] : evidence(x.evidence, evidenceLines);
102
+ const at = x.where.line !== xs[0].where.line || x.where.file !== xs[0].where.file ? ` (${where(x.where)})` : '';
103
+ lines.push(` - ${esc(x.says)}${at}${compact && (ev.length || x.also?.length) ? ' _(Before and after, and other places: in the job summary.)_' : ''}`);
104
+ if (compact) continue;
105
+ if (ev.length) lines.push('', ` <details><summary>Before and after</summary>`, '', ...ev.map((l) => (l ? ` ${l}` : '')), '', ' </details>', '');
106
+ if (x.also?.length) {
107
+ lines.push('', ` <details><summary>The same in ${x.also.length} more</summary>`, '', ...x.also.slice(0, 50).map((a) => ` - **${esc(a.subject)}** · ${where(a.where)}`),
108
+ ...(x.also.length > 50 ? [` - and ${x.also.length - 50} more`] : []), '', ' </details>', '');
109
+ }
110
+ }
111
+ if (list.length < xs.length) lines.push(` - _…and ${xs.length - list.length} more changes to it, in the job summary._`);
112
+ return { lines, items: list.length };
113
+ };
114
+ return { full: render(false), compact: render(true) };
115
+ });
116
+ blocks.push({ open, close, members: memberBlocks });
117
+ }
118
+ const tail = [];
119
+ if (r.notRead?.length) tail.push(`Also changed, not read by Thunder (check ${r.notRead.length === 1 ? 'it' : 'them'} yourself if ${r.notRead.length === 1 ? 'it matters' : 'they matter'}): ${r.notRead.slice(0, 20).map((f) => `\`${esc(f.path)}\``).join(', ')}${r.notRead.length > 20 ? `, and ${r.notRead.length - 20} more` : ''}.`, '');
120
+ const foot = ['---', `<sub>Read from the code by the Thunder compiler, with no AI and without running the code. "Only the form changed" is said only when it is shown. Thunder describes the change; a person still decides whether it is right. [How this works](${DOCS_URL}) · [thunderlang.dev](${SITE_URL})${footer ? ` · ${footer}` : ''}</sub>`, ''];
121
+
122
+ // Fill blocks in order of importance. A member that does not fit in full is shown compact (its sentences); when
123
+ // even that does not fit, stop there and say how many were left out.
124
+ const size = (lines) => lines.join('\n').length + 1;
125
+ const total = r.items.length;
126
+ const moreLine = (n) => [`**${n} more not shown** to stay under GitHub's comment size limit. The job summary and \`thunder review\` on your computer have all of them.`, ''];
127
+ const reserve = size(head) + size(tail) + size(foot) + size(moreLine(total)) + 64;
128
+ if (reserve > maxChars) throw new Error(`maxChars ${maxChars} is too small for the comment header and footer.`);
129
+ let used = reserve, shown = 0, full = true;
130
+ const body = [];
131
+ for (const b of blocks) {
132
+ if (!full) break;
133
+ const opened = size(b.open) + size(b.close);
134
+ if (used + opened + (b.members[0] ? size(b.members[0].compact.lines) : 0) > maxChars) { full = false; break; }
135
+ body.push(...b.open); used += opened;
136
+ for (const m of b.members) {
137
+ const pick = used + size(m.full.lines) <= maxChars ? m.full : used + size(m.compact.lines) <= maxChars ? m.compact : null;
138
+ if (!pick) { full = false; break; }
139
+ body.push(...pick.lines); used += size(pick.lines); shown += pick.items;
140
+ }
141
+ body.push('', ...b.close);
142
+ }
143
+ const out = [...head, ...body, ...(shown < total ? moreLine(total - shown) : []), ...tail, ...foot];
144
+ return out.join('\n');
145
+ }