@skillstech/thunderlang 0.5.11 → 0.5.12

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 (66) hide show
  1. package/CHANGELOG.md +437 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
@@ -50,6 +50,20 @@ function docAbove(src, idx) {
50
50
  return null;
51
51
  }
52
52
 
53
+ /** C and C++ also document with a plain block comment (/* … *\/) on the lines right above. */
54
+ function cDocAbove(src, idx) {
55
+ const before = src.slice(Math.max(0, idx - 1200), idx).trimEnd();
56
+ if (/\*\/$/.test(before) && !/\/\*\*[\s\S]*\*\/$/.test(before.slice(before.lastIndexOf('/*')))) {
57
+ const at = before.lastIndexOf('/*');
58
+ if (at >= 0 && /(?:^|\n)[ \t]*$/.test(before.slice(0, at))) {
59
+ const para = [];
60
+ for (const l of before.slice(at + 2, -2).split('\n')) { const t = l.replace(/^\s*\*?\s?/, '').trim(); if (!t) { if (para.length) break; continue; } para.push(t); }
61
+ return para.join(' ') || null;
62
+ }
63
+ }
64
+ return docAbove(src, idx);
65
+ }
66
+
53
67
  /** The body of a brace block with nested blocks removed: the type's own declarations, not its methods' bodies. */
54
68
  function ownLevel(body) {
55
69
  let depth = 0, own = '';
@@ -342,7 +356,268 @@ export function makeThingReaders({ words, kindWords, startValue }) {
342
356
  return out;
343
357
  }
344
358
 
359
+ /**
360
+ * The members written at a type's own level, split where a declaration ends (`;`, or a newline for Swift) or where a
361
+ * brace block closes: [{ head, block, at }] where `block` is the inside of the braces that end it (or null) and `at`
362
+ * is the head's offset in `body`.
363
+ */
364
+ function members(raw, { newlines = false } = {}) {
365
+ // Comments blanked once (same length), so a `;` or `{` in a comment is never read as code.
366
+ const chars = raw.split('');
367
+ for (let i = 0; i < chars.length; i++) {
368
+ if (chars[i] === '/' && chars[i + 1] === '/') { while (i < chars.length && chars[i] !== '\n') chars[i++] = ' '; continue; }
369
+ if (chars[i] === '/' && chars[i + 1] === '*') { chars[i] = chars[i + 1] = ' '; i += 2; while (i < chars.length && !(chars[i] === '*' && chars[i + 1] === '/')) { if (chars[i] !== '\n') chars[i] = ' '; i++; } if (i < chars.length) { chars[i] = ' '; if (i + 1 < chars.length) chars[i + 1] = ' '; i++; } }
370
+ }
371
+ const body = chars.join('');
372
+ const out = [];
373
+ let from = 0, depth = 0;
374
+ const emit = (end, block) => { const head = body.slice(from, end); if (head.trim() || block != null) out.push({ head: head.trim(), block, at: from + (head.length - head.trimStart().length) }); };
375
+ for (let i = 0; i < body.length; i++) {
376
+ const c = body[i];
377
+ if (c === '"' || c === "'") { const q = c; for (i++; i < body.length && body[i] !== q && body[i] !== '\n'; i++) if (body[i] === '\\') i++; continue; }
378
+ if (c === '(' || c === '[') { depth++; continue; }
379
+ if (c === ')' || c === ']') { depth--; continue; }
380
+ if (depth) continue;
381
+ if (c === '{') {
382
+ const close = braceEnd(body, i);
383
+ if (close < 0) break;
384
+ emit(i, body.slice(i + 1, close));
385
+ from = close + 1; i = close;
386
+ continue;
387
+ }
388
+ if (c === ';' || (newlines && c === '\n')) { emit(i, null); from = i + 1; }
389
+ }
390
+ emit(body.length, null);
391
+ return out;
392
+ }
393
+
394
+ /** Drop a common prefix from enum values: STATUS_ON_SHELF, STATUS_BORROWED -> ON_SHELF, BORROWED; kOnShelf -> OnShelf. */
395
+ function enumNames(names) {
396
+ if (names.length > 1) {
397
+ const parts = names.map((n) => n.split('_'));
398
+ let k = 0;
399
+ while (parts.every((p) => p.length > k + 1 && p[k] === parts[0][k])) k++;
400
+ if (k) names = parts.map((p) => p.slice(k).join('_'));
401
+ }
402
+ if (names.length && names.every((n) => /^k[A-Z]/.test(n))) names = names.map((n) => n.slice(1));
403
+ return names;
404
+ }
405
+
406
+ /** C: struct, typedef struct, union, and enum. A struct is a record; the model makes it a Thing when functions take it. */
407
+ function cThings(src, file) {
408
+ const code = src.replace(/^[ \t]*#.*(?:\\\r?\n.*)*$/gm, (m) => m.replace(/[^\n]/g, ' '));
409
+ const lineAt = lineFinder(code);
410
+ const out = [];
411
+ for (const m of code.matchAll(/(?:^|\n)[ \t]*(typedef\s+)?(struct|union|enum)\b\s*(\w+)?\s*\{/g)) {
412
+ const at = m.index + (m[0].startsWith('\n') ? 1 : 0);
413
+ const open = m.index + m[0].length - 1;
414
+ const close = braceEnd(code, open);
415
+ if (close < 0) continue;
416
+ const alias = m[1] ? (code.slice(close + 1, close + 200).match(/^\s*(\w+)/) || [])[1] : null;
417
+ const name = alias || m[3];
418
+ if (!name) continue;
419
+ const doc = cDocAbove(code, at);
420
+ const t = { kind: m[2] === 'enum' ? 'choices' : 'record', name, ...(m[3] && m[3] !== name ? { tag: m[3] } : {}), file, lines: [lineAt(at), lineAt(close)], ...(doc ? { doc } : {}), knows: [], choices: [] };
421
+ const body = code.slice(open + 1, close);
422
+ if (m[2] === 'enum') {
423
+ t.choices = enumNames(splitParams(body.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')).map((x) => (x.trim().match(/^(\w+)/) || [])[1]).filter(Boolean)).map((n) => words(n));
424
+ } else {
425
+ for (const { head } of members(body)) {
426
+ const fp = head.match(/\(\s*\*\s*(\w+)\s*\)\s*\(/); // a function pointer field: int (*compare)(int, int)
427
+ if (fp) { t.knows.push(know(fp[1], null, null, {})); continue; }
428
+ const d = head.replace(/\s*:\s*\d+\s*$/, '').match(/^((?:(?:const|unsigned|signed|struct|enum|union|volatile|long|short)\s+)*[A-Za-z_]\w*)\s*((?:\*\s*)*)(\w+)\s*((?:\[[^\]]*\]\s*)*)((?:,\s*\**\s*\w+\s*(?:\[[^\]]*\])*)*)$/);
429
+ if (!d) continue;
430
+ const type = (base, stars, arr) => `${base.replace(/\b(?:const|struct|enum|union|volatile)\s+/g, '').trim()}${stars ? '*' : ''}${arr ? '[]' : ''}`;
431
+ t.knows.push(know(d[3], cKind(type(d[1], d[2].trim(), d[4].trim())), null, {}));
432
+ for (const more of d[5].split(',').map((x) => x.trim()).filter(Boolean)) { const n = more.match(/^(\**)\s*(\w+)\s*(\[[^\]]*\])?/); if (n) t.knows.push(know(n[2], cKind(type(d[1], n[1], n[3])), null, {})); }
433
+ }
434
+ }
435
+ out.push(t);
436
+ }
437
+ // Starting values from a C constructor: Library library_new(int max) { Library lib = { .max_books = 3 }; … }
438
+ for (const t of out.filter((x) => x.kind === 'record')) {
439
+ const snake = words(t.name).replace(/ /g, '_');
440
+ const ctor = code.match(new RegExp(`\\b(?:${snake}_(?:new|create|init|make|alloc)|(?:new|create|init|make)_${snake})\\s*\\(([^)]*)\\)\\s*\\{`));
441
+ if (!ctor) continue;
442
+ const open = ctor.index + ctor[0].length - 1;
443
+ const fnBody = code.slice(open + 1, braceEnd(code, open));
444
+ const params = Object.fromEntries(splitParams(ctor[1]).map((p) => [(p.match(/(\w+)\s*(?:\[[^\]]*\])?\s*$/) || [])[1], null]).filter(([n]) => n && n !== 'void'));
445
+ for (const a of fnBody.matchAll(/(?:\.|->)\s*(\w+)\s*=\s*(\{[^{}]*\}|[^,;}\n]+)/g)) {
446
+ const k = t.knows.find((x) => x.name === a[1]);
447
+ if (k && !k.start) k.start = startValue(a[2].trim().replace(/^\{\s*0?\s*\}$/, '{}'), params);
448
+ }
449
+ }
450
+ return out;
451
+ }
452
+
453
+ /** C/C++ field types in the reader's terms: int, words (char *, std::string), yes or no, lists, or the type. */
454
+ function cKind(type) {
455
+ const t = String(type).replace(/\bstd::/g, '').replace(/\s+/g, ' ').trim();
456
+ if (/^(?:unsigned |signed )?char\*$|^(?:string|string_view|wstring|sds)$/.test(t)) return 'string';
457
+ if (/^(?:(?:unsigned|signed|long|short) )*(?:int|long|short|unsigned|signed)$|^(?:size_t|ssize_t|off_t|time_t|u?int\d+_t|float|double|long double|uint|uintptr_t|intptr_t)$/.test(t)) return 'int';
458
+ if (/^(?:bool|_Bool)$/.test(t)) return 'bool';
459
+ const list = t.match(/^(?:vector|list|deque|array|set|unordered_set|span)<\s*([\w:]+)\s*(?:,[^>]*)?>$/);
460
+ if (list) return `${list[1].split('::').pop()}[]`;
461
+ if (/^(?:map|unordered_map|multimap)</.test(t)) return 'Map<>';
462
+ if (/^(?:unique_ptr|shared_ptr|optional)<\s*([\w:]+)\s*>$/.test(t)) return t.replace(/^\w+<\s*([\w:]+)\s*>$/, '$1').split('::').pop();
463
+ return t.replace(/\*+$/, '');
464
+ }
465
+
466
+ /** C++: classes and structs (Things when they have methods, records otherwise), enums and enum classes (choices). */
467
+ function cppThings(src, file) {
468
+ const code = src.replace(/^[ \t]*#.*(?:\\\r?\n.*)*$/gm, (m) => m.replace(/[^\n]/g, ' '));
469
+ const lineAt = lineFinder(code);
470
+ const out = [];
471
+ const byName = new Map();
472
+ for (const m of code.matchAll(/(?:^|\n)[ \t]*(?:template\s*<[^>{;]*>\s*)?(?:(class|struct|union)\s+(?:alignas\([^)]*\)\s*)?(?:[A-Z_][A-Z0-9_]*\s+)*(\w+)(?:\s+final)?\s*(?::[^{;]*)?|enum(?:\s+(?:class|struct))?\s+(\w+)(?:\s*:\s*[\w:]+)?\s*)\{/g)) {
473
+ const at = m.index + (m[0].startsWith('\n') ? 1 : 0);
474
+ const open = m.index + m[0].length - 1;
475
+ const close = braceEnd(code, open);
476
+ if (close < 0) continue;
477
+ const name = m[2] || m[3];
478
+ const doc = cDocAbove(code, at);
479
+ const body = code.slice(open + 1, close);
480
+ if (m[3]) {
481
+ const vals = splitParams(body.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')).map((x) => (x.trim().match(/^(\w+)/) || [])[1]).filter(Boolean);
482
+ out.push({ kind: 'choices', name, file, lines: [lineAt(at), lineAt(close)], ...(doc ? { doc } : {}), knows: [], choices: enumNames(vals).map((n) => words(n)) });
483
+ continue;
484
+ }
485
+ const t = { kind: 'record', name, file, lines: [lineAt(at), lineAt(close)], ...(doc ? { doc } : {}), knows: [], choices: [], memberRanges: [] };
486
+ let methods = false;
487
+ const inits = {}, params = {};
488
+ for (const mem of members(body)) {
489
+ const head = mem.head.replace(/^(?:(?:public|private|protected)\s*:\s*)+/, '').replace(/\[\[[^\]]*\]\]\s*/g, '').trim();
490
+ if (!head || /^(?:using|friend|typedef|static_assert|template|enum|class|struct|union|namespace|static|constexpr\s+static|inline\s+static|Q_OBJECT)\b/.test(head)) continue;
491
+ const sig = head.replace(/<[^<>]*(?:<[^<>]*>[^<>]*)*>/g, '<>');
492
+ const call = sig.split(/=(?!=)/)[0];
493
+ if (/\(/.test(call) && !/\(\s*\*\s*\w+\s*\)\s*\(/.test(call)) {
494
+ methods = true;
495
+ // The constructor: its parameters, member initializers (: max_(max)), and body assignments start the Thing.
496
+ const ctor = head.match(new RegExp(`^(?:explicit\\s+|constexpr\\s+|inline\\s+)*${name}\\s*\\(([^)]*)\\)\\s*(?:noexcept\\s*)?(?::\\s*([\\s\\S]+))?$`));
497
+ if (ctor) cppCtor(ctor[1], ctor[2], mem.block, params, inits);
498
+ continue;
499
+ }
500
+ let f = head.match(/^((?:(?:const|mutable|volatile|unsigned|signed|long|short|inline)\s+)*[\w:]+(?:<[^;]*>)?(?:\s*[*&]+)?)\s+[*&]*\s*(\w+)\s*(?:\[[^\]]*\])?\s*(?:=\s*([\s\S]+))?$/);
501
+ if (f) { t.knows.push(know(f[2].replace(/^m_/, ''), cKind(f[1].replace(/\b(?:const|mutable|volatile|inline)\s+/g, '').replace(/\s*[*&]+$/, '')), f[3] ? cppValue(f[3]) : mem.block != null ? cppValue(`{${mem.block}}`) : null, {})); t.knows[t.knows.length - 1].name = f[2]; continue; }
502
+ if ((f = head.match(/^((?:(?:const|mutable|unsigned|signed|long|short)\s+)*[\w:]+(?:<[^;]*>)?(?:\s*[*&]+)?)\s+[*&]*\s*(\w+)$/)) && mem.block != null) {
503
+ t.knows.push({ ...know(f[2].replace(/^m_/, ''), cKind(f[1]), cppValue(`{${mem.block}}`), {}), name: f[2] });
504
+ }
505
+ }
506
+ // Methods written outside the class (Library::lateFee) and an outside constructor (Library::Library(...) : …).
507
+ for (const d of code.matchAll(new RegExp(`\\b${name}::(~?\\w+)\\s*\\(`, 'g'))) {
508
+ const pOpen = d.index + d[0].length - 1;
509
+ let depth = 0, pClose = -1;
510
+ for (let k = pOpen; k < code.length && k < pOpen + 4000; k++) { if (code[k] === '(') depth++; else if (code[k] === ')' && --depth === 0) { pClose = k; break; } }
511
+ if (pClose < 0) continue;
512
+ const brace = code.indexOf('{', pClose), semi = code.indexOf(';', pClose);
513
+ if (brace < 0 || (semi >= 0 && semi < brace) || /[()]/.test(code.slice(pClose + 1, brace).replace(/:\s*[\s\S]*$/, ''))) continue;
514
+ methods = true;
515
+ const bClose = braceEnd(code, brace);
516
+ t.memberRanges.push([lineAt(d.index), lineAt(bClose >= 0 ? bClose : brace)]);
517
+ if (d[1] === name) cppCtor(code.slice(pOpen + 1, pClose), (code.slice(pClose + 1, brace).match(/^\s*(?:noexcept\s*)?:\s*([\s\S]+)$/) || [])[1], bClose > 0 ? code.slice(brace + 1, bClose) : '', params, inits);
518
+ }
519
+ for (const k of t.knows) {
520
+ const v = inits[k.name] ?? inits[k.name.replace(/^m_|_$/g, '')];
521
+ if (v != null) k.start = startValue(cppValue(v), params);
522
+ }
523
+ if (methods || m[1] === 'class') t.kind = 'thing';
524
+ out.push(t); byName.set(name, t);
525
+ }
526
+ return out;
527
+ }
528
+ /** A C++ starting value as the reader's words take it: {} or a std container is empty; nullptr is nothing. */
529
+ function cppValue(v) {
530
+ const s = String(v).trim().replace(/;$/, '');
531
+ if (/^\{\s*\}$|^\(\s*\)$|^(?:std::)?(?:vector|list|deque|map|unordered_map|set|unordered_set|string|array)\s*(?:<[^;]*>)?\s*(?:\{\s*\}|\(\s*\))$/.test(s)) return '{}';
532
+ if (/^\{\s*(.+?)\s*\}$/.test(s) && !/,/.test(s)) return s.slice(1, -1).trim();
533
+ return s.replace(/^(-?\d+(?:\.\d+)?)[uUlLfF]+$/, '$1').replace(/^nullptr$/, 'NULL');
534
+ }
535
+ function cppCtor(paramText, initText, bodyText, params, inits) {
536
+ for (const p of splitParams(paramText || '')) {
537
+ const pm = p.match(/(\w+)\s*(?:\[[^\]]*\])?\s*(?:=\s*(.+))?$/);
538
+ if (pm && pm[1] !== 'void') params[pm[1]] = pm[2] != null ? cppValue(pm[2]) : null;
539
+ }
540
+ for (const it of splitParams(String(initText || '').replace(/\{\s*$/, ''))) {
541
+ const im = it.trim().match(/^(\w+)\s*[({]([\s\S]*)[)}]$/);
542
+ if (im) inits[im[1]] = im[2].trim() || '{}';
543
+ }
544
+ for (const a of String(bodyText || '').matchAll(/(?:this->)?(\w+)\s*=\s*([^;\n]+);/g)) if (inits[a[1]] == null) inits[a[1]] = a[2];
545
+ }
546
+
547
+ /** Swift: class, struct, actor (Things or records), enum with case (choices), extension (methods that belong to the type). */
548
+ function swiftThings(src, file) {
549
+ const lineAt = lineFinder(src);
550
+ const out = [];
551
+ const byName = new Map();
552
+ for (const m of src.matchAll(/(?:^|\n)[ \t]*(?:@\w+(?:\([^)\n]*\))?\s+)*(?:(?:public|private|internal|fileprivate|open|final|indirect|nonisolated)\s+)*(class|struct|enum|actor|protocol)\s+(\w+)(?:<[^>{\n]*>)?[ \t]*(?::[ \t]*([^{\n]+?))?[ \t]*\{/g)) {
553
+ if (m[1] === 'protocol') continue; // a contract other types promise to keep, not a Thing
554
+ const at = m.index + (m[0].startsWith('\n') ? 1 : 0);
555
+ const open = m.index + m[0].length - 1;
556
+ const close = braceEnd(src, open);
557
+ if (close < 0) continue;
558
+ const doc = docAbove(src, at);
559
+ const body = src.slice(open + 1, close);
560
+ const t = { kind: m[1] === 'enum' ? 'choices' : 'record', name: m[2], file, lines: [lineAt(at), lineAt(close)], ...(doc ? { doc } : {}), knows: [], choices: [], memberRanges: [] };
561
+ const mems = members(body, { newlines: true });
562
+ if (m[1] === 'enum') {
563
+ for (const { head } of mems) {
564
+ const c = head.match(/^(?:indirect\s+)?case\s+([\s\S]+)$/);
565
+ if (!c) continue;
566
+ for (const part of splitParams(c[1])) {
567
+ const v = part.trim().match(/^(\w+)\s*(?:\([^)]*\))?\s*(?:=\s*(.+))?$/);
568
+ if (v) t.choices.push(v[2] && /^"/.test(v[2].trim()) ? v[2].trim().slice(1, -1) : words(v[1]));
569
+ }
570
+ }
571
+ out.push(t); byName.set(t.name, t);
572
+ continue;
573
+ }
574
+ let methods = mems.some((x) => /(?:^|\s)func\s/.test(x.head));
575
+ const params = {}, inits = {};
576
+ for (const { head, block } of mems) {
577
+ const h = head.replace(/^(?:@\w+(?:\([^)]*\))?\s+)+/, '');
578
+ if (/(?:^|\s)(?:static|class)\s+(?:let|var|func)\b/.test(h) || /^(?:case|typealias|associatedtype|subscript|deinit|#)/.test(h)) continue;
579
+ const init = h.match(/^(?:(?:public|private|internal|fileprivate|open|convenience|required|override|nonisolated)\s+)*init[?!]?\s*\(([\s\S]*)\)\s*(?:throws\s*)?$/);
580
+ if (init) {
581
+ for (const p of splitParams(init[1])) { const pm = p.match(/^(?:\w+\s+)?(\w+)\s*:\s*[^=]+?(?:=\s*(.+))?$/); if (pm) params[pm[1]] = pm[2] ?? null; }
582
+ for (const a of String(block || '').matchAll(/(?:self\.)?(\w+)\s*=\s*([^\n;]+)/g)) if (inits[a[1]] == null) inits[a[1]] = a[2].trim();
583
+ continue;
584
+ }
585
+ if (/(?:^|\s)func\s/.test(h)) { methods = true; continue; }
586
+ const p = h.match(/^(?:(?:public|private|internal|fileprivate|open|final|lazy|weak|unowned|override|nonisolated)(?:\((?:set|get)\))?\s+)*(let|var)\s+(\w+)\s*(?::\s*([^=]+?))?\s*(?:=\s*([\s\S]+))?$/);
587
+ if (!p) continue;
588
+ // A computed property (`var total: Int { … }`) is worked out each time: something it can do, not something it knows.
589
+ if (block != null && !p[4] && !/^\s*(?:willSet|didSet)\b/.test(block)) continue;
590
+ t.knows.push(know(p[2], p[3] ? swiftType(p[3]) : null, p[4] != null ? p[4].trim() : null, {}));
591
+ }
592
+ for (const k of t.knows) if (inits[k.name] != null && !k.start) k.start = startValue(inits[k.name], params);
593
+ if (methods || m[1] === 'class' || m[1] === 'actor') t.kind = 'thing';
594
+ out.push(t); byName.set(t.name, t);
595
+ }
596
+ // extension Library { … }: its methods belong to Library (a struct that can do things is a Thing).
597
+ for (const m of src.matchAll(/(?:^|\n)[ \t]*(?:(?:public|private|internal|fileprivate)\s+)?extension\s+([\w.]+)[^{\n]*\{/g)) {
598
+ const t = byName.get(m[1].split('.').pop());
599
+ if (!t) continue;
600
+ const at = m.index + (m[0].startsWith('\n') ? 1 : 0);
601
+ const close = braceEnd(src, m.index + m[0].length - 1);
602
+ if (close < 0) continue;
603
+ t.memberRanges.push([lineAt(at), lineAt(close)]);
604
+ if (t.kind === 'record' && /(?:^|\s)func\s/.test(src.slice(at, close))) t.kind = 'thing';
605
+ }
606
+ return out;
607
+ }
608
+ /** Swift types as the shared kind words read them: [Book] is a list, [String: Int] a lookup table, Int? optional. */
609
+ function swiftType(type) {
610
+ const t = String(type).trim();
611
+ let m;
612
+ if ((m = t.match(/^\[\s*([^:\]]+?)\s*\]$/))) return `${m[1]}[]`;
613
+ if (/^\[[^\]]*:[^\]]*\]$/.test(t)) return 'Map<>';
614
+ return t;
615
+ }
616
+
345
617
  return function thingsFor(language, src, file) {
618
+ if (language === 'c') return cThings(src, file);
619
+ if (language === 'cpp') return cppThings(src, file);
620
+ if (language === 'swift') return swiftThings(src, file);
346
621
  if (language === 'go') return goThings(src, file);
347
622
  if (language === 'rust') return rustThings(src, file);
348
623
  if (language === 'ruby') return rubyThings(src, file);
@@ -8,10 +8,10 @@ import { thunderText, visualFor } from './visual.mjs';
8
8
  export const THUNDERIZE_SCHEMA = 'thunderize-v1';
9
9
  export const THUNDER_TEXT_EXT = '.thunder-text';
10
10
 
11
- const LANGUAGE_NAMES = { typescript: 'TypeScript', javascript: 'JavaScript', python: 'Python', go: 'Go', rust: 'Rust', csharp: 'C#', java: 'Java', kotlin: 'Kotlin', php: 'PHP', ruby: 'Ruby' };
11
+ const LANGUAGE_NAMES = { typescript: 'TypeScript', javascript: 'JavaScript', python: 'Python', go: 'Go', rust: 'Rust', csharp: 'C#', java: 'Java', kotlin: 'Kotlin', php: 'PHP', ruby: 'Ruby', sql: 'SQL', c: 'C', cpp: 'C++', swift: 'Swift', r: 'R', shell: 'Shell', powershell: 'PowerShell', dockerfile: 'Dockerfile', 'github-actions': 'GitHub Actions', terraform: 'Terraform', bicep: 'Bicep', kubernetes: 'Kubernetes', 'docker-compose': 'Docker Compose' };
12
12
 
13
13
  /** One file in Thunder Text: a header, then every action, rule, and function in order, then how it can fail. */
14
- export function thunderizeFile(path, source, language = readableLanguage(path), reading = readCode(source, { language, file: path })) {
14
+ export function thunderizeFile(path, source, language = readableLanguage(path, source), reading = readCode(source, { language, file: path })) {
15
15
  const main = reading.items.filter((i) => i.kind === 'decision' || i.kind === 'function');
16
16
  const failures = [...new Set(reading.items.filter((i) => i.kind === 'error').map((i) => i.name))];
17
17
  const counts = { actions: 0, rules: 0, functions: 0, notReadYet: 0, failures: failures.length };
@@ -43,7 +43,7 @@ function summary(c) {
43
43
  export function thunderizeFiles(files, { name = 'app' } = {}) {
44
44
  const out = [], skipped = [];
45
45
  for (const f of files) {
46
- const language = readableLanguage(f.path);
46
+ const language = readableLanguage(f.path, f.source);
47
47
  if (!language) { skipped.push({ path: f.path, reason: 'not a language Thunder reads yet' }); continue; }
48
48
  if (!f.source) { skipped.push({ path: f.path, reason: f.size ? 'too large to read' : 'empty' }); continue; }
49
49
  try { out.push(thunderizeFile(f.path, f.source, language, readingOf(f, language))); }
package/src/visual.d.mts CHANGED
@@ -4,7 +4,7 @@ import type { ReadItem, ReadStep } from './read.mjs';
4
4
  export const VISUAL_SCHEMA: 'thunder-visual-v1';
5
5
  export const PRINCIPLE: string;
6
6
  export type ColorRole = 'structure' | 'question' | 'fact' | 'comparison' | 'amount' | 'outcome' | 'name' | 'failure' | 'pass' | 'fail' | 'unread';
7
- export type ElementKind = 'app' | 'area' | 'file' | 'data-shape' | 'action' | 'decision' | 'function' | 'not-read' | 'error' | 'test' | 'event' | 'source';
7
+ export type ElementKind = 'app' | 'area' | 'file' | 'data-shape' | 'action' | 'decision' | 'function' | 'not-read' | 'error' | 'test' | 'event' | 'source' | 'resource' | 'permission' | 'setting' | 'pipeline' | 'image-build';
8
8
  export type Provenance = 'from-code' | 'confirmed' | 'authors-note' | 'ai-summary' | 'not-read';
9
9
  export type Status = 'available' | 'partial' | 'planned';
10
10
 
@@ -15,21 +15,21 @@ export const LINES: { solid: string; dashed: string };
15
15
  export const PROVENANCE: Record<Provenance, { label: string; line: 'solid' | 'dashed'; says: string }>;
16
16
  export const STEP_MARKS: Record<ReadStep['kind'] | 'restates', { mark: string; label: string; color: ColorRole; show: 'words' | 'code'; line?: 'dashed' }>;
17
17
  export const ELEMENTS: Record<ElementKind, { zoom: number; name: string; shape: string; status: Status; shows: string; text: string; badge?: string; mark?: string; color?: ColorRole; line?: 'dashed' }>;
18
- export const LANGUAGES: Record<string, { name: string; status: Status; action: string; decision: string; doc: string; 'data-shape': string; event?: string; steps?: string }>;
18
+ export const LANGUAGES: Record<string, { name: string; status: Status; action: string; decision: string; doc: string; 'data-shape'?: string; event?: string; steps?: string; category?: 'application' | 'infrastructure' | 'delivery'; resource?: string; permission?: string; setting?: string }>;
19
19
  export const RULES: string[];
20
20
 
21
21
  export interface Visual {
22
22
  element: ElementKind; shape: string; line: 'solid' | 'dashed'; title: string;
23
23
  provenance: Provenance; mark?: string; color?: ColorRole; note?: string;
24
- badge?: { kind: 'route'; text: string };
24
+ badge?: { kind: 'route' | 'when'; text: string };
25
25
  doc?: { text: string; provenance: 'authors-note' };
26
26
  }
27
27
  export function visualFor(item: ReadItem): Visual;
28
28
  export function visualForStep(step: ReadStep): { mark: string; label: string; color: ColorRole; show: 'words' | 'code'; line: 'solid' | 'dashed'; text: string };
29
29
  export function thunderText(item: ReadItem): string;
30
- export type SymbolId = 'app' | 'area' | 'file' | 'thing' | 'data' | 'record' | 'choices' | 'action' | 'rule' | 'steps' | 'setup' | 'stop' | 'not-read';
30
+ export type SymbolId = 'app' | 'area' | 'file' | 'thing' | 'data' | 'record' | 'choices' | 'action' | 'rule' | 'steps' | 'setup' | 'stop' | 'not-read' | 'resource' | 'permission';
31
31
  export const SYMBOLS: Record<SymbolId, { name: string; says: string; color: ColorRole; paths: string[]; circles?: [number, number, number][]; fill?: boolean; dashed?: boolean; beginner?: boolean; group?: string }>;
32
- export type Does = 'start' | 'find' | 'keep-only' | 'check' | 'decide' | 'calculate' | 'save' | 'send' | 'redirect' | 'ask' | 'repeat' | 'answer' | 'stop' | 'do' | 'code';
32
+ export type Does = 'start' | 'find' | 'keep-only' | 'check' | 'decide' | 'calculate' | 'save' | 'send' | 'redirect' | 'ask' | 'repeat' | 'answer' | 'stop' | 'do' | 'code' | 'when';
33
33
  export const DOES: Record<Does, { label: string; mark: string; color: ColorRole; dashed?: boolean; symbol?: SymbolId }>;
34
34
  export const BEGINNER: SymbolId[];
35
35
  /** The five reading levels, in order: how deep you read something. */
package/src/visual.mjs CHANGED
@@ -115,6 +115,12 @@ export const ELEMENTS = {
115
115
  error: { zoom: 4, name: 'Failure', shape: 'chip', mark: '✕', color: 'failure', status: 'available', shows: 'A way the code can fail, by name.', text: 'Can fail with <Name>' },
116
116
  test: { zoom: 4, name: 'Test', shape: 'chip', mark: '⚑', color: 'structure', status: 'available', shows: 'A test that exists. Green or red only once it has run.', text: 'Test: <name>' },
117
117
  event: { zoom: 3, name: 'Trigger', shape: 'steps-card', badge: 'when', status: 'planned', shows: 'Something that runs when an event happens (a database trigger, a message handler, a schedule).', text: 'When <event>, it\n - <step>' },
118
+ // The whole application (spec section 12): where it runs and how it ships.
119
+ resource: { zoom: 2, name: 'Resource', shape: 'block', status: 'available', shows: 'Something that exists when the app runs (an image, a server, a database), with what it knows: its settings.', text: 'Resource <name> (<kind>)\n It knows' },
120
+ permission: { zoom: 2, name: 'Permission', shape: 'key', status: 'available', shows: 'Who can do what to which resource. Wide permissions are called wide.', text: '<who> can <what> on <resource>' },
121
+ setting: { zoom: 2, name: 'Setting', shape: 'chip', status: 'available', shows: 'A value the app or the infrastructure is given, and where it comes from. A secret is only ever named.', text: 'Setting <name>: <where it comes from>' },
122
+ pipeline: { zoom: 3, name: 'Pipeline', shape: 'steps-card', badge: 'when', status: 'available', shows: 'Automation: when it runs, then its jobs as steps.', text: 'When someone pushes to main\n - <step>' },
123
+ 'image-build': { zoom: 3, name: 'Image build', shape: 'steps-card', status: 'available', shows: 'How an app is packaged and started, one card per build stage.', text: 'What the image build does\n - <step>' },
118
124
  source: { zoom: 5, name: 'Original code', shape: 'code', status: 'available', shows: 'The exact lines, highlighted, in the original language.', text: '(the original code)' },
119
125
  };
120
126
 
@@ -130,7 +136,19 @@ export const LANGUAGES = {
130
136
  kotlin: { name: 'Kotlin', status: 'available', action: 'Spring annotations', decision: 'a fun with when or if returning fixed answers', doc: '/** KDoc */', 'data-shape': 'data class, enum class (planned)' },
131
137
  php: { name: 'PHP', status: 'available', action: '#[Route] (Symfony)', decision: 'a function that returns fixed answers', doc: '/** PHPDoc */', 'data-shape': 'class, enum (planned)' },
132
138
  ruby: { name: 'Ruby', status: 'available', action: 'Sinatra get/post blocks (Rails routes.rb planned)', decision: 'a def that returns fixed answers', doc: '# comment above the def', 'data-shape': 'class, Struct (planned)' },
139
+ c: { name: 'C', status: 'available', action: '(none: a C program is reached through main or another program)', decision: 'a function that returns fixed answers', doc: '/* comment */ or // comment above the function', 'data-shape': 'struct, typedef struct, enum', steps: 'if/else, for, while, do … while, switch with break and fall-through, goto and labels, malloc/free in plain words; a pointer the reader cannot explain stays as code' },
140
+ cpp: { name: 'C++', status: 'available', action: '(none yet: Crow, Drogon planned)', decision: 'a function or method that returns fixed answers', doc: '/** Doxygen */, /// or // above', 'data-shape': 'class, struct, enum class', steps: 'range-for, try/catch, throw, lambdas, new/delete; methods written outside the class (Type::method) belong to it' },
141
+ swift: { name: 'Swift', status: 'available', action: 'Vapor app.get("orders", ":id") { req in … } and routes.post(…, use: handler)', decision: 'a func with switch or if returning fixed answers', doc: '/// doc comment', 'data-shape': 'struct, class, enum with case, extension (protocol is a contract)', steps: 'guard … else as a Stop, if let as "is set", defer, do/try/catch, throw, closures, ranges' },
133
142
  sql: { name: 'SQL', status: 'available', action: '(none: SQL is reached through the app)', decision: 'CHECK and UNIQUE constraints; IF in functions and procedures', doc: '-- comment above, COMMENT ON', 'data-shape': 'CREATE TABLE / VIEW', event: 'CREATE TRIGGER', steps: 'SELECT / INSERT / UPDATE / DELETE: which data, filtered by which conditions, changed how' },
143
+ r: { name: 'R', status: 'available', action: 'plumber #* @get / #* @post annotations', decision: 'a function whose if/else or switch() gives fixed answers', doc: "#' roxygen comment above", 'data-shape': 'R6Class, setRefClass, setClass', steps: 'pipelines (|> and %>%) one verb at a time: keeps only the rows where …, groups, sums up, sorts' },
144
+ shell: { name: 'Shell', status: 'available', action: '(none: the script itself is what runs)', decision: '(none: steps only)', doc: '# comment above the function, or at the top of the script', 'data-shape': '(none: shell has no classes)', steps: 'tests in words, exit as a Stop with its message, set -e, trap … EXIT, and well-known tools (docker, kubectl, helm, az, aws, gcloud, git, npm, curl) by what they do' },
145
+ powershell: { name: 'PowerShell', status: 'available', action: 'Pode Add-PodeRoute', decision: 'a function whose if/elseif/else or switch gives fixed answers', doc: '<# .SYNOPSIS #> comment-based help', 'data-shape': 'class, enum', steps: 'cmdlets by Verb-Noun (Get-AzResourceGroup: gets the Azure resource groups), -eq/-gt/-like in words, pipelines with Where-Object and ForEach-Object' },
146
+ dockerfile: { name: 'Dockerfile', status: 'available', category: 'infrastructure', action: '(none: it packages the app)', decision: '(none)', doc: '# comment above FROM', steps: 'each build stage: FROM, COPY, RUN, ENV, EXPOSE, USER, CMD in words', resource: 'the image it makes' },
147
+ 'github-actions': { name: 'GitHub Actions', status: 'available', category: 'delivery', action: 'each job, with a When badge (its trigger)', decision: 'if: as a question', doc: "the workflow's name:", steps: 'well-known actions and run: commands in words', permission: 'permissions:', setting: 'env:, secrets (named only), inputs' },
148
+ terraform: { name: 'Terraform', status: 'available', category: 'infrastructure', action: '(none: it describes what exists)', decision: 'count = cond ? 1 : 0 as a question', doc: '# comment above a block', steps: 'the order things are created, from their references', resource: 'resource, data (looked up), module', permission: 'azurerm_role_assignment, AWS IAM policies, google_*_iam_member', setting: 'variable (sensitive named only), locals, output' },
149
+ bicep: { name: 'Bicep', status: 'available', category: 'infrastructure', action: '(none: it describes what exists)', decision: 'if (…) as a question', doc: '// comment or @description above', steps: 'the order things are created, from their references', resource: "resource (existing: looked up), module", permission: 'Microsoft.Authorization/roleAssignments (well-known roles named)', setting: 'param (@secure() named only), var, output' },
150
+ kubernetes: { name: 'Kubernetes', status: 'available', category: 'infrastructure', action: '(none: it describes what runs)', decision: '(none)', doc: '# comment above a resource', steps: 'the order things are made, from their links', resource: 'each resource (Deployment, Service, Ingress, ConfigMap, Secret, …), by Kind/name', permission: 'Role/ClusterRole rules and RoleBinding/ClusterRoleBinding', setting: 'env (secretKeyRef named only), ConfigMap and Secret keys' },
151
+ 'docker-compose': { name: 'Docker Compose', status: 'available', category: 'infrastructure', action: '(none: it describes what runs)', decision: 'profiles: as a question', doc: "the file's name:", steps: 'the order services start, from depends_on', resource: 'each service, named volume, network, secret, and config', setting: 'environment (secret-looking values not shown; ${VAR} worked out when it starts), secrets' },
134
152
  };
135
153
 
136
154
  /** Rules every Thunder view follows. A view that breaks one is wrong, however good it looks. */
@@ -156,14 +174,14 @@ export function visualFor(item) {
156
174
  const base = { provenance: item.provenance === 'confirmed' ? 'confirmed' : 'from-code', ...(item.doc ? { doc: { text: item.doc, provenance: 'authors-note' } } : {}) };
157
175
  if (item.kind === 'error') return { element: 'error', shape: 'chip', line: 'solid', mark: '✕', color: 'failure', title: `Can fail with ${item.name}`, ...base };
158
176
  if (item.kind === 'test') return { element: 'test', shape: 'chip', line: 'solid', mark: '⚑', color: 'structure', title: `Test: ${item.name}`, ...base };
159
- const badge = item.route ? { kind: 'route', text: `${item.route.method} ${item.route.path}`.trim() } : undefined;
177
+ const badge = item.route ? { kind: item.when ? 'when' : 'route', text: `${item.route.method} ${item.route.path}`.trim() } : undefined;
160
178
  if (item.kind === 'decision') {
161
179
  const card = safePlain(item);
162
180
  return { element: 'decision', shape: 'card', line: item.status === 'partial' ? 'dashed' : 'solid', title: card?.question || `How ${words(item.name)} decides`, ...(badge ? { badge } : {}), ...(item.status === 'partial' ? { note: 'Partly read' } : {}), ...base };
163
181
  }
164
182
  const readable = (item.stepsReadable ?? 0) >= 0.5 && item.steps?.length;
165
183
  if (!readable) return { element: 'not-read', shape: 'dashed-card', line: 'dashed', title: `What ${words(item.name)} does`, ...(badge ? { badge } : {}), ...base, provenance: 'not-read' };
166
- return { element: item.route ? 'action' : 'function', shape: 'steps-card', line: 'solid', title: item.route ? `When someone calls ${badge.text}` : `What ${words(item.name)} does`, ...(badge ? { badge } : {}), ...base };
184
+ return { element: item.route ? 'action' : 'function', shape: 'steps-card', line: 'solid', title: item.title ?? (item.route ? `When someone calls ${badge.text}` : `What ${words(item.name)} does`), ...(badge ? { badge } : {}), ...base };
167
185
  }
168
186
 
169
187
  /** How to draw one step: its mark, label, color role, and whether to show words or the original code. */
@@ -238,6 +256,8 @@ export const SYMBOLS = {
238
256
  setup: { name: 'Starts with', says: 'What a new Thing has when it is made.', color: 'structure', paths: ['M22 5 V15 M22 29 V39 M5 22 H15 M29 22 H39 M10 10 L16 16 M28 28 L34 34 M34 10 L28 16 M16 28 L10 34'] },
239
257
  stop: { name: 'Stop', says: 'Something is wrong, so it stops and says why.', color: 'failure', beginner: true, paths: ['M15 5 H29 L39 15 V29 L29 39 H15 L5 29 V15 Z', 'M16 22 H28'] },
240
258
  'not-read': { name: 'Not read yet', says: "Thunder shows the code, because it can't explain it yet.", color: 'unread', dashed: true, paths: ['M11 5 H33 V39 H11 Z', 'M17 22 H27'] },
259
+ resource: { name: 'Resource', says: 'Something that exists when the app runs: an image, a server, a database. It knows its settings.', color: 'fact', paths: ['M7 8 H37 V18 H7 Z', 'M7 26 H37 V36 H7 Z', 'M22 18 V26'], circles: [[13, 13, 1.6], [13, 31, 1.6]], fill: true },
260
+ permission: { name: 'Permission', says: 'Who can do what. A wide one can change a lot.', color: 'comparison', paths: ['M24 20 L38 34 M33 29 L29 33 M37 33 L34 36'], circles: [[16, 16, 9]] },
241
261
  };
242
262
 
243
263
  /** What a step does, in a kid's words (model flow nodes carry `does`). Shape first, color second. */
@@ -257,6 +277,7 @@ export const DOES = {
257
277
  stop: { label: 'Stops', mark: '■', color: 'failure', symbol: 'stop' },
258
278
  do: { label: 'Does', mark: '→', color: 'outcome' },
259
279
  code: { label: 'Not read yet', mark: '·', color: 'unread', dashed: true },
280
+ when: { label: 'Runs when', mark: '⚡', color: 'structure' },
260
281
  };
261
282
 
262
283
  /** The six concepts a beginner learns first; the model keeps all of SYMBOLS. */
@@ -269,7 +290,7 @@ export const THUNDER_VISUAL = { schema: VISUAL_SCHEMA, principle: PRINCIPLE, for
269
290
 
270
291
  // ── Thunder Text colors: each word's role, decided by the compiler so every view colors it the same way ──────
271
292
 
272
- const STRUCTURE_WORDS = /^(?:Ask:|Yes:|No:|Otherwise:|Otherwise,|Always, at the end:|For each:|When done:|You give it:|You get back:|Takes|Author's note:|It knows|It can|One of:|We need|Examples|Why:|When someone calls|What|Thing|Record|Choices|Area|File|App|Not read)(?=\s|$)/;
293
+ const STRUCTURE_WORDS = /^(?:Resource|Permissions|Settings|Ask:|Yes:|No:|Otherwise:|Otherwise,|Always, at the end:|For each:|When done:|You give it:|You get back:|Takes|Author's note:|It knows|It can|One of:|We need|Examples|Why:|When someone calls|What|Thing|Record|Choices|Area|File|App|Not read)(?=\s|$)/;
273
294
  const COMPARISON_RE = /\b(?:is at least|is at most|is less than|is more than|is not in|is in|is not|at least|at most|less than|more than|under|over|exactly|whether|is set|is not set|is empty|is not empty|has no|has|is)\b/;
274
295
 
275
296
  /**
@@ -0,0 +1,64 @@
1
+ // Writing in Thunder (see src/write-steps.mjs): change software in Thunder; the code is written and proven.
2
+ export const WRITE_STEPS_SCHEMA: 'thunder-write-steps-v1';
3
+ export const WRITE_STEPS_LANGUAGES: string[];
4
+ export const EDIT_OPS: ThunderEdit['op'][];
5
+
6
+ /** A function: a model member id (path#owner#name#line), "path:name[:line]", a bare name, or { file, name, line }. */
7
+ export type MemberRef = string | { file?: string; name: string; line?: number };
8
+ /** A step: "line:12" (or 12), a path from 0 such as "1.0" or [1, 'else', 0], or a flow node id such as "n4". */
9
+ export type StepRef = string | number | (number | 'else')[];
10
+ /** Code a person writes for a value or condition, in Thunder's neutral form or the file's language; or a tree. */
11
+ export type CodeText = string;
12
+ export type NewStep = CodeText | { if: CodeText; then?: NewStep[]; else?: NewStep[] } | { stop: string; error?: string };
13
+ type Where = { before: StepRef } | { after: StepRef } | { into: StepRef | { step: StepRef; side?: 'yes' | 'no'; at?: 'start' | 'end' } };
14
+
15
+ export type ThunderEdit =
16
+ | { op: 'setValue'; member: MemberRef; step: StepRef; from?: unknown; to: number | string | boolean | null; at?: number }
17
+ | { op: 'setCondition'; member: MemberRef; step: StepRef; clause?: number; when?: CodeText; compare?: '<' | '<=' | '>' | '>=' | '==' | '!='; operand?: { side?: 'left' | 'right'; to: CodeText }; negate?: boolean; addClause?: { join?: 'and' | 'or'; when: CodeText }; removeClause?: number }
18
+ | ({ op: 'addStep'; member: MemberRef; step?: NewStep; steps?: NewStep[] } & Where)
19
+ | { op: 'removeStep'; member: MemberRef; step: StepRef }
20
+ | ({ op: 'moveStep'; member: MemberRef; step: StepRef } & ({ before: StepRef } | { after: StepRef }))
21
+ | ({ op: 'addStop'; member: MemberRef; when: CodeText; message: string; error?: string } & ({ before: StepRef } | { after: StepRef }))
22
+ | { op: 'addStop'; member: MemberRef; step: StepRef; side?: 'yes' | 'no'; message: string; error?: string }
23
+ | { op: 'removeStop'; member: MemberRef; step: StepRef }
24
+ | { op: 'addInput'; member: MemberRef; name: string; type?: string; default?: unknown }
25
+ | { op: 'removeInput'; member: MemberRef; name: string }
26
+ | { op: 'setGivesBack'; member: MemberRef; step?: StepRef; value?: CodeText; type?: string }
27
+ | { op: 'rename'; member: MemberRef; from?: string; to: string }
28
+ | { op: 'addFunction'; file?: string; name: string; inputs?: (string | { name: string; type?: string })[]; returns?: string; steps: NewStep[]; after?: MemberRef; export?: boolean };
29
+
30
+ export interface ShapeStep { e: unknown; c: ShapeStep[]; o?: ShapeStep[]; h?: { e: unknown; c: ShapeStep[] }[]; a?: ShapeStep[] }
31
+ export interface WriteProof {
32
+ edited: { status: 'proven' | 'failed' | 'not-checked'; checks: { member: string; file: string; result: 'exact' | 'different' | 'missing'; steps?: number }[]; note?: string };
33
+ unchanged: { status: 'same' | 'failed'; checked: number; items: { name: string; file: string; line?: number; status: 'same' | 'different' | 'missing' | 'new'; reason?: string; note?: string; same?: string }[] };
34
+ /** Filled by a caller that runs something (the CLI's --test). */
35
+ run?: { command: string; passed: boolean; exit: number | null; seconds: number; output: string };
36
+ }
37
+ export interface ThunderWriteResult {
38
+ schema: 'thunder-write-steps-v1';
39
+ status: 'written' | 'needs-ai' | 'refused';
40
+ edits: ThunderEdit[];
41
+ /** Who wrote the code: the compiler, or an AI (checked with `options.candidate`; labeled "AI-written"). */
42
+ author?: 'thunder' | 'ai';
43
+ label?: 'AI-written';
44
+ /** A unified diff of every changed file. */
45
+ patch?: string;
46
+ /** The changed files' new text (nothing is written to disk). */
47
+ files?: Record<string, string>;
48
+ /** The edited function in Thunder, before and after. */
49
+ before?: string | null;
50
+ after?: string | null;
51
+ proof?: WriteProof;
52
+ /** In plain words: "Changed 7 to 10 in …; nothing else changed: …". */
53
+ says: string;
54
+ reason?: string;
55
+ /** For 'needs-ai': a self-contained instruction for an AI coding agent. */
56
+ prompt?: string;
57
+ /** For 'needs-ai' when the compiler's own patch failed its proof: that patch and proof, for inspection only. */
58
+ rejected?: { patch: string; proof: unknown };
59
+ }
60
+ export function thunderWrite(files: { path: string; source: string }[] | Record<string, string>, edits: ThunderEdit | ThunderEdit[], options?: { candidate?: Record<string, string> }): ThunderWriteResult;
61
+ export function proveChange(before: Map<string, string>, after: Map<string, string>, plans: unknown[]): { ok: boolean; edited: WriteProof['edited']; unchanged: WriteProof['unchanged']; problems: string[] };
62
+ export function stepShape(steps: unknown[]): ShapeStep[];
63
+ export function unifiedDiff(path: string, before: string, after: string): string;
64
+ export function describeEdit(edit: ThunderEdit): string;