@skillstech/thunderlang 1.1.0 → 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.
@@ -168,7 +168,7 @@ export const READ_LESSONS = [
168
168
  check: ({ item }) => flatSteps(item.steps).find((s) => s.kind === 'branch' && /coupon/.test(s.says)).children[0].says },
169
169
  ],
170
170
  title: "Software, as pictures",
171
- idea: "Code is a list of instructions written for a computer. Thunder shows the same instructions as a picture written for people. The Thunder compiler reads the code exactly; it never guesses.",
171
+ idea: "Code is a list of instructions written for a computer. Thunder™ shows the same instructions as a picture written for people. The Thunder compiler reads the code exactly; it never guesses.",
172
172
  picture: "A chef's shorthand notes and the recipe card in the cookbook describe the same dish. The code is the shorthand; Thunder is the recipe card anyone can follow.",
173
173
  files: [{ language: "python", label: "Python", code: `def order_total(order):
174
174
  total = 0
@@ -456,3 +456,247 @@ def place_order(order, card):
456
456
  ],
457
457
  },
458
458
  ];
459
+
460
+ // ── Part 2: write and run ──────────────────────────────────────────────────────────────────────────────────────
461
+ // Programs you write in Thunder Core. Every answer is worked out by compiling the lesson's program and running it on
462
+ // the Thunder engine (engine-core.mjs, which needs no Python and runs in a browser too). Each lesson names the
463
+ // programming concept it teaches, and `commands` are what to type in a terminal to do it yourself.
464
+
465
+ /** The program `thunder new` writes (a test checks they stay the same). */
466
+ export const STARTER_PROGRAM = `# Your first Thunder program. Run it with: thunder run
467
+
468
+ To greet:
469
+ Receive name
470
+ Give "Hello, {name}!"
471
+
472
+ say greet with "world"
473
+ `;
474
+
475
+ const CHOOSE = `Set total to $18.50
476
+
477
+ When total is at least $20:
478
+ say "Delivery is free"
479
+ Otherwise:
480
+ say "Delivery costs $3.99"
481
+ `;
482
+
483
+ const LOOP = `Set scores to [90, 75, 100]
484
+ Set total to 0
485
+ For each score in scores:
486
+ Increase total by score
487
+
488
+ say "Total: {total}"
489
+ say "First: {scores at 1}"
490
+ `;
491
+
492
+ const RECORD = `A Book has:
493
+ Title is text
494
+ Copies is a whole number
495
+ Never allow negative copies
496
+
497
+ Set book to a Book with title "Matilda" and copies 1
498
+ Set book's copies to book's copies - 1
499
+ say "{book's title}: {book's copies} left"
500
+ Set book's copies to book's copies - 1
501
+ If this fails:
502
+ say "Not allowed: {error}"
503
+ `;
504
+
505
+ const FEE_TESTS = `To delivery fee:
506
+ Receive total
507
+ When total is at least $20:
508
+ Give $0
509
+ Otherwise:
510
+ Give $3.99
511
+
512
+ Test "orders of $20 or more are free":
513
+ Expect delivery fee with $20 to be $0
514
+
515
+ Test "small orders pay for delivery":
516
+ Expect delivery fee with $5 to be $2.99
517
+ `;
518
+
519
+ const SHOP_PY = `def delivery_fee(total):
520
+ if total >= 20:
521
+ return 0
522
+ return 3.99
523
+
524
+
525
+ def safe_divide(a, b):
526
+ try:
527
+ return a / b
528
+ except ZeroDivisionError:
529
+ return None
530
+ `;
531
+
532
+ /** A small agent run record (OpenTelemetry, GenAI conventions): a refund that could not reach the payment service. */
533
+ const AGENT_RUN = (() => {
534
+ const t = 'a1b2c3d4e5f60718293a4b5c6d7e8f90';
535
+ const ns = (ms) => String(1764064800000000000n + BigInt(ms) * 1000000n);
536
+ const kv = (o) => Object.entries(o).map(([key, v]) => ({ key, value: { stringValue: String(v) } }));
537
+ const fail = (type, message) => ({ status: { code: 2, message }, events: [{ name: 'exception', attributes: kv({ 'exception.type': type, 'exception.message': message }) }] });
538
+ const span = (id, parent, name, s, e, attrs, extra = {}) => ({ traceId: t, spanId: id, ...(parent ? { parentSpanId: parent } : {}), name, startTimeUnixNano: ns(s), endTimeUnixNano: ns(e), attributes: kv(attrs), ...extra });
539
+ const post = (id, s) => span(id, 'c8e0a2b4d6f81a3c', 'POST', s, s + 2900, { 'http.request.method': 'POST', 'url.full': 'https://pay.example.com/v1/refunds', 'error.type': 'ConnectionError' }, fail('ConnectionError', 'Connection refused'));
540
+ return JSON.stringify({ resourceSpans: [{ scopeSpans: [{ spans: [
541
+ span('7c1e4a9b2d3f5061', null, 'invoke_agent support-bot', 0, 12400, { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': 'support-bot' }, fail('RuntimeError', 'tool failed')),
542
+ span('c8e0a2b4d6f81a3c', '7c1e4a9b2d3f5061', 'execute_tool refund_payment', 3150, 12350, { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': 'refund_payment', 'gen_ai.tool.call.arguments': '{"order_id": 1042, "amount": "40.00"}' }, fail('ConnectionError', 'failed after 3 attempts')),
543
+ post('1f3b5d7f9a1c3e50', 3200), post('6a8c0e2a4c6e8a01', 6300), post('b2d4f6b8d0f2b4d6', 9350),
544
+ ] }] }] }, null, 2);
545
+ })();
546
+
547
+ export const WRITE_LESSONS = [
548
+ {
549
+ slug: "first-program",
550
+ part: "write",
551
+ concept: "A program: instructions the computer follows, in order",
552
+ title: "Your first program, in two commands",
553
+ idea: "thunder new hello makes a folder called hello with a program inside. thunder run hello runs it. thunder new does not move you into the folder, so name it when you run it (or type cd hello first, then just thunder run).",
554
+ picture: "A recipe card. Writing it changes nothing; running it is cooking it.",
555
+ commands: ["thunder new hello", "thunder run hello"],
556
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: STARTER_PROGRAM }],
557
+ show: "run",
558
+ quiz: [
559
+ { prompt: "What does this program print?", choices: ["Hello, world!", "Hello, {name}!", "greet with \"world\""], expect: "Hello, world!",
560
+ explain: "To greet makes a step you can use; the last line uses it with \"world\". {name} inside text is filled in with the value, so it says Hello, world!",
561
+ check: ({ core }) => core.stdout.trim() },
562
+ { prompt: "Change \"world\" to \"Ada\" on the last line. What does it print now?", choices: ["Hello, Ada!", "Hello, world!", "Hello, {name}!"], expect: "Hello, Ada!",
563
+ explain: "The same steps run with a different value. That is the whole point of a step with an input: write it once, use it with anything.",
564
+ check: ({ runCore }) => runCore(STARTER_PROGRAM.replace('"world"', '"Ada"')).stdout.trim() },
565
+ ],
566
+ questions: [
567
+ { q: "You typed thunder new hello, then thunder run, and Thunder said there is no project here. Why?", a: "thunder new made the hello folder but did not move you into it. Run thunder run hello, or cd hello first." },
568
+ { q: "Which lines run first?", a: "To greet only describes a step; it runs when it is used. So the first thing that happens is the last line, which uses greet." },
569
+ ],
570
+ },
571
+ {
572
+ slug: "choose",
573
+ part: "write",
574
+ concept: "Conditions: the program chooses what to do",
575
+ title: "Write a choice and run it",
576
+ idea: "Open hello/src/main.thunder, write your own lines, and run it again. Thunder checks what you wrote first and explains any mistake by its line. By default your program runs as Python (Python 3.10 or newer); add --engine thunder to run it without Python. Python is the only full target today.",
577
+ picture: "A fork in a path with a sign: one way when the total is big enough, the other way otherwise.",
578
+ commands: ["thunder run hello", "thunder run hello --engine thunder"],
579
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: CHOOSE }],
580
+ show: "run",
581
+ quiz: [
582
+ { prompt: "What does this program print?", choices: ["Delivery costs $3.99", "Delivery is free"], expect: "Delivery costs $3.99",
583
+ explain: "$18.50 is not at least $20, so the Otherwise lines run.",
584
+ check: ({ core }) => core.stdout.trim() },
585
+ { prompt: "Change the total to $20. What does it print now?", choices: ["Delivery is free", "Delivery costs $3.99"], expect: "Delivery is free",
586
+ explain: "\"At least\" includes the limit itself: $20 is at least $20. The edge of a rule is where mistakes hide, so it is worth trying.",
587
+ check: ({ runCore }) => runCore(CHOOSE.replace('$18.50', '$20')).stdout.trim() },
588
+ ],
589
+ questions: [
590
+ { q: "Why is money written $18.50 and not 18.5?", a: "Money in Thunder is exact: $0.10 + $0.20 is exactly $0.30, and it always shows cents. A plain 18.5 would be a number, not money." },
591
+ ],
592
+ },
593
+ {
594
+ slug: "repeat",
595
+ part: "write",
596
+ concept: "Loops and lists: do something for each item",
597
+ title: "Go through a list",
598
+ idea: "A list holds several values in order. For each goes through them one at a time and runs the indented lines for every one. In Thunder the first item is at position 1, the way people count.",
599
+ picture: "A teacher reading a stack of tests, adding each score to a running total.",
600
+ commands: ["thunder run hello"],
601
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: LOOP }],
602
+ show: "run",
603
+ quiz: [
604
+ { prompt: "What is the total?", choices: ["Total: 265", "Total: 100", "Total: 90"], expect: "Total: 265",
605
+ explain: "The loop runs three times, once for each score: 90 + 75 + 100 = 265.",
606
+ check: ({ core }) => core.stdout.split('\n')[0] },
607
+ { prompt: "What does scores at 1 give?", choices: ["First: 90", "First: 75"], expect: "First: 90",
608
+ explain: "Positions start at 1, so scores at 1 is the first score. (In Python and JavaScript it would be scores[0]; Thunder counts like people do.)",
609
+ check: ({ core }) => core.stdout.split('\n')[1] },
610
+ ],
611
+ questions: [
612
+ { q: "How would you count only the scores of 90 or more?", a: "Inside the loop, add a choice: When score is at least 90: Increase count by 1." },
613
+ ],
614
+ },
615
+ {
616
+ slug: "records",
617
+ part: "write",
618
+ concept: "Records: data with a shape, and rules it must keep",
619
+ title: "Give your data a shape and a rule",
620
+ idea: "A record says what a kind of thing knows (a Book has a title and a number of copies). A Never rule on it is checked every time it changes, so a mistake is caught where it happens, with the rule's own words.",
621
+ picture: "A library card with fixed boxes to fill in, and a line printed at the bottom: copies can never go below zero.",
622
+ commands: ["thunder run hello"],
623
+ files: [{ language: "thunder", label: "hello/src/main.thunder", code: RECORD }],
624
+ show: "run",
625
+ quiz: [
626
+ { prompt: "The second change would make copies -1. What happens?", choices: ["Thunder refuses the change", "Copies becomes -1"], expect: "Thunder refuses the change",
627
+ explain: "Never allow negative copies is checked on every change. The change is refused, and If this fails catches it and says why: the rule, its line, and the value it would have had.",
628
+ check: ({ core }) => (core.stdout.split('\n')[1].startsWith('Not allowed:') ? 'Thunder refuses the change' : 'Copies becomes -1') },
629
+ ],
630
+ questions: [
631
+ { q: "Why put the rule on the record instead of checking before every change?", a: "Because then it cannot be forgotten. Every change to copies, anywhere in the program, is checked by the same rule." },
632
+ ],
633
+ },
634
+ {
635
+ slug: "python-as-thunder",
636
+ part: "write",
637
+ concept: "The same meaning in two languages, and honesty about the rest",
638
+ title: "Read Python as Thunder you can run",
639
+ idea: "thunder read shop.py --as-core turns Python into Thunder Core you can edit and run. A line Thunder cannot say with exactly the same meaning is never turned into something close: it is marked \"Not translated\", with the reason, and a Stop line that explains itself if it ever runs.",
640
+ picture: "A careful interpreter who translates every sentence they are sure of, and says \"I can't translate this one, here is why\" for the rest.",
641
+ commands: ["thunder read shop.py --as-core"],
642
+ files: [{ language: "python", label: "shop.py", code: SHOP_PY }],
643
+ asCore: true,
644
+ show: "run",
645
+ quiz: [
646
+ { prompt: "Which function comes across exactly?", choices: ["delivery fee", "safe divide", "both"], expect: "delivery fee",
647
+ explain: "delivery_fee is a comparison and two answers: Thunder says it exactly. safe_divide uses a Python try with a named error kind, which Core has no step for yet.",
648
+ check: ({ asCore }) => { const exact = asCore.functions.filter((f) => f.exact).map((f) => f.coreName); return exact.length === asCore.functions.length ? 'both' : exact.join(', '); } },
649
+ { prompt: "What happens if the part that was not translated runs?", choices: ["It stops with a clear message", "It guesses what the Python meant"], expect: "It stops with a clear message",
650
+ explain: "The not-translated line becomes Stop with \"Line 8 of the Python was not translated: try:\". Thunder never quietly does something different.",
651
+ check: ({ asCore }) => (/Stop with "Line \d+ of the Python was not translated/.test(asCore.core) ? 'It stops with a clear message' : 'It guesses what the Python meant') },
652
+ ],
653
+ questions: [
654
+ { q: "Why is \"not translated\" better than a close guess?", a: "A close guess looks right and behaves differently, which is the most dangerous kind of mistake. A marked line tells you exactly where to look." },
655
+ ],
656
+ },
657
+ {
658
+ slug: "check-test-verify",
659
+ part: "write",
660
+ concept: "Evidence: checking, testing, and verifying promise different things",
661
+ title: "Check, test, and verify",
662
+ idea: "thunder check reads your program before it runs and finds mistakes like a name that does not exist. thunder test runs your examples (Test blocks) and says which ones fail. thunder verify checks a change to the code, by a person or an AI, against the rules that must stay true. Each answers a different question; none replaces the others.",
663
+ picture: "A spell-checker (check), a practice exam (test), and an inspector who signs off on a renovation (verify).",
664
+ commands: ["thunder check hello", "thunder test hello"],
665
+ files: [{ language: "thunder", label: "hello/src/fee.thunder", code: FEE_TESTS }],
666
+ show: "run",
667
+ quiz: [
668
+ { prompt: "You write say totl instead of say total. When does Thunder tell you?", choices: ["Before it runs: it doesn't know what totl is", "Only when that line runs"], expect: "Before it runs: it doesn't know what totl is",
669
+ explain: "thunder check (and run, before running) reads the whole program first. An unknown name is found by its line, before anything happens.",
670
+ check: ({ compile }) => (compile('Set total to $18.50\nsay totl\n').diagnostics.some((d) => d.code === 'TC201') ? "Before it runs: it doesn't know what totl is" : 'Only when that line runs') },
671
+ { prompt: "Which test fails?", choices: ["small orders pay for delivery", "orders of $20 or more are free", "neither"], expect: "small orders pay for delivery",
672
+ explain: "The program gives $3.99 for a $5 order, but the test expected $2.99. thunder test shows both numbers and the line. Either the test or the program is wrong: a person decides which.",
673
+ check: ({ testCore }) => { const m = testCore(FEE_TESTS).stdout.match(/^FAIL {2}(.+?) \(/m); return m ? m[1] : 'neither'; } },
674
+ ],
675
+ questions: [
676
+ { q: "All your tests pass. Is the program right?", a: "It is right for the examples you wrote. Tests only cover what they check, which is why edge cases (like exactly $20) are worth a test of their own." },
677
+ ],
678
+ },
679
+ {
680
+ slug: "agent-why",
681
+ part: "write",
682
+ concept: "Reading what an AI agent did, and why it stopped",
683
+ title: "Ask what an AI agent did",
684
+ idea: "Agents leave a record of every step (an OpenTelemetry trace). thunder why run.json reads it and tells you in plain words what the agent did, what it changed, and why it stopped. When the record doesn't say whether a tool changes anything, Thunder guesses from the tool's name and says it guessed.",
685
+ picture: "A flight recorder, read back as a short story instead of a wall of numbers.",
686
+ commands: ["thunder why run.json"],
687
+ files: [{ language: "json", label: "run.json", code: AGENT_RUN }],
688
+ why: true,
689
+ show: "run",
690
+ quiz: [
691
+ { prompt: "How many times did the agent try to reach the payment service?", choices: ["3", "1", "0"], expect: "3",
692
+ explain: "Three POST requests in a row failed the same way, so Thunder shows them as one step with 3 tries.",
693
+ check: ({ why }) => String(why.problem.tries) },
694
+ { prompt: "How did Thunder decide that refund_payment changes something?", choices: ["From the tool's name (a guess)", "The tool declared it"], expect: "From the tool's name (a guess)",
695
+ explain: "The record does not say what the tool does, so Thunder used its name, and it says so. When a tool declares what it does (its MCP annotations), Thunder uses that instead.",
696
+ check: ({ why }) => (why.changes[0]?.basis === 'name' ? "From the tool's name (a guess)" : 'The tool declared it') },
697
+ ],
698
+ questions: [
699
+ { q: "The refund did not go through. Was the customer refunded?", a: "Thunder can't know: the record shows the requests failed, not what the payment service did. It says the step may have partly happened, so a person checks." },
700
+ ],
701
+ },
702
+ ];
package/src/learn.d.mts CHANGED
@@ -9,6 +9,12 @@ export interface LearnLesson {
9
9
  /** A picture to hold in mind. */
10
10
  picture: string;
11
11
  part: 'read' | 'write';
12
+ /** Write lessons: the programming concept it teaches ("Loops and lists: do something for each item"). */
13
+ concept?: string;
14
+ /** Write lessons: what to type in a terminal to do it yourself, in order. */
15
+ commands?: string[];
16
+ /** Write lessons: what the lesson's program prints, worked out by running it on the Thunder engine. */
17
+ output?: string;
12
18
  /** The lesson's code (the first file), or null for lessons with no code. */
13
19
  snippet: { language: string; code: string } | null;
14
20
  /** Every file the lesson shows (a lesson can show the same rule in several languages). */
@@ -32,3 +38,5 @@ export const LEARN_SCHEMA: 'thunder-learn-v1';
32
38
  export function learnThunder(): LearnThunder;
33
39
  /** The lesson sources (code, wording, and the checks that work out each answer). */
34
40
  export const READ_LESSONS: any[];
41
+ /** Part 2, write and run: programs whose answers are worked out by running them (no Python needed). */
42
+ export const WRITE_LESSONS: any[];
package/src/learn.mjs CHANGED
@@ -8,10 +8,14 @@ import { thunderModel, modelText } from './model.mjs';
8
8
  import { plainFromReading, explainPlain } from './plain-contract.mjs';
9
9
  import { sameMeaning } from './same.mjs';
10
10
  import { COMPILER_VERSION } from './emit.mjs';
11
- import { READ_LESSONS } from './learn-lessons.mjs';
11
+ import { READ_LESSONS, WRITE_LESSONS } from './learn-lessons.mjs';
12
+ import { compileCore } from './core/index.mjs';
13
+ import { runInProcess, testInProcess } from './core/engine-core.mjs';
14
+ import { pythonToCore } from './core/from-python.mjs';
15
+ import { explainRun } from './why.mjs';
12
16
 
13
17
  export const LEARN_SCHEMA = 'thunder-learn-v1';
14
- export { READ_LESSONS };
18
+ export { READ_LESSONS, WRITE_LESSONS };
15
19
 
16
20
  const squash = (s) => String(s).replace(/[_\s]/g, '').toLowerCase();
17
21
  const EXT = { python: 'py', typescript: 'ts', javascript: 'js', java: 'java', go: 'go', csharp: 'cs', ruby: 'rb', php: 'php', rust: 'rs', kotlin: 'kt' };
@@ -19,6 +23,7 @@ const MODEL_SHOWS = new Set(['thing', 'flow']);
19
23
 
20
24
  /** What a lesson's quiz checks may look at: only what the compiler produced from the lesson's code. */
21
25
  function lessonContext(lesson) {
26
+ if (lesson.part === 'write') return writeContext(lesson);
22
27
  const files = lesson.files.map((f, i) => ({ path: `lesson${i ? i + 1 : ''}.${EXT[f.language] ?? 'txt'}`, source: f.code }));
23
28
  const readings = lesson.files.map((f) => readCode(f.code, { language: f.language }));
24
29
  const all = readings.flatMap((r) => r.items);
@@ -47,13 +52,40 @@ function lessonContext(lesson) {
47
52
  };
48
53
  }
49
54
 
55
+ /**
56
+ * What a write lesson's quiz may look at: its Thunder program compiled and run on the Thunder engine (no Python, so
57
+ * this works in a browser too), Python read as Core, or an agent's record read by thunder why.
58
+ */
59
+ function writeContext(lesson) {
60
+ const compile = (source, file = 'main.thunder') => compileCore(source, { file });
61
+ const runCore = (source) => {
62
+ const r = compile(source);
63
+ if (!r.ok) return { ok: false, diagnostics: r.diagnostics, stdout: '', stderr: r.diagnostics.map((d) => `${d.code} ${d.message}`).join('\n'), status: 1 };
64
+ return { ok: true, diagnostics: [], ...runInProcess({ entry: r }) };
65
+ };
66
+ const testCore = (source) => {
67
+ const r = compile(source);
68
+ if (!r.ok) throw new Error(r.diagnostics.map((d) => `${d.code} line ${d.line}: ${d.message}`).join('; '));
69
+ return testInProcess({ results: [{ ...r, kind: 'src' }] });
70
+ };
71
+ const file = lesson.files[0];
72
+ const ctx = { compile, runCore, testCore };
73
+ if (file?.language === 'thunder' && !/^\s*Test "/m.test(file.code)) {
74
+ ctx.core = runCore(file.code);
75
+ if (!ctx.core.ok || ctx.core.status !== 0) throw new Error(`the lesson's program does not run cleanly: ${ctx.core.stderr}`);
76
+ }
77
+ if (lesson.asCore) ctx.asCore = pythonToCore(file.code);
78
+ if (lesson.why) ctx.why = explainRun(file.code);
79
+ return ctx;
80
+ }
81
+
50
82
  /**
51
83
  * The tutorial: { schema, languageVersion, lessons }. Each lesson has its idea, a picture to hold in mind, its code
52
84
  * (snippet), the Thunder Text the compiler gives for it, quiz questions whose answers the compiler worked out, and
53
85
  * open questions to think about (reflect).
54
86
  */
55
87
  export function learnThunder() {
56
- const lessons = READ_LESSONS.map((lesson) => {
88
+ const lessons = [...READ_LESSONS, ...WRITE_LESSONS].map((lesson) => {
57
89
  const ctx = lessonContext(lesson);
58
90
  const questions = (lesson.quiz || []).map((q, i) => {
59
91
  const where = `Lesson "${lesson.slug}", question ${i + 1}`;
@@ -66,9 +98,13 @@ export function learnThunder() {
66
98
  const snippets = lesson.files.map((f) => ({ language: f.language, label: f.label, code: f.code }));
67
99
  return {
68
100
  slug: lesson.slug, title: lesson.title, idea: lesson.idea, picture: lesson.picture, part: lesson.part ?? 'read',
101
+ ...(lesson.concept ? { concept: lesson.concept } : {}),
102
+ ...(lesson.commands ? { commands: [...lesson.commands] } : {}),
69
103
  snippet: snippets[0] ? { language: snippets[0].language, code: snippets[0].code } : null,
70
104
  snippets,
71
- thunderText: ctx.text ?? (ctx.texts[0] || null),
105
+ thunderText: ctx.text ?? (ctx.texts?.[0] || null),
106
+ // What the lesson's program prints, worked out by running it (write lessons).
107
+ ...(ctx.core ? { output: ctx.core.stdout } : {}),
72
108
  questions,
73
109
  reflect: lesson.questions.map((q) => ({ prompt: q.q, answer: q.a })),
74
110
  };
@@ -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/term.mjs ADDED
@@ -0,0 +1,89 @@
1
+ // Calm color for the terminal: green for what worked, red only for real problems, yellow for warnings and choices,
2
+ // cyan for commands to type, bold for headings. Off when the output is not a terminal (a file, a pipe, a script, an
3
+ // editor reading it), when NO_COLOR is set, or for TERM=dumb; FORCE_COLOR=1 turns it on. Color never carries meaning
4
+ // alone: every colored line also has its words and its mark (✓ ✗ !).
5
+ const env = (typeof process !== 'undefined' && process.env) || {};
6
+
7
+ /** Whether to color text written to `stream` (default: standard output). */
8
+ export function useColor(stream = typeof process !== 'undefined' ? process.stdout : null) {
9
+ if (env.NO_COLOR != null && env.NO_COLOR !== '') return false;
10
+ if (env.FORCE_COLOR != null && env.FORCE_COLOR !== '' && env.FORCE_COLOR !== '0') return true;
11
+ if (env.TERM === 'dumb') return false;
12
+ return !!stream?.isTTY;
13
+ }
14
+
15
+ const wrap = (open, close) => (s, on = useColor()) => (on ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
16
+ export const bold = wrap(1, 22);
17
+ export const dim = wrap(2, 22);
18
+ export const green = wrap(32, 39);
19
+ export const red = wrap(31, 39);
20
+ export const yellow = wrap(33, 39);
21
+ export const cyan = wrap(36, 39);
22
+
23
+ /** A command to type: cyan, so it stands out from the words around it. */
24
+ export const cmd = (s, on) => cyan(s, on);
25
+ /** A heading. */
26
+ export const head = (s, on) => bold(s, on);
27
+
28
+ /** Color the marks at the start of a line: ✓ green, ✗ red, ! yellow. */
29
+ export function marks(line, on = useColor()) {
30
+ if (!on) return line;
31
+ return line
32
+ .replace(/^(\s*)✓/, (_, s) => `${s}${green('✓', on)}`)
33
+ .replace(/^(\s*)✗/, (_, s) => `${s}${red('✗', on)}`)
34
+ .replace(/^(\s*)!(?= )/, (_, s) => `${s}${yellow('!', on)}`);
35
+ }
36
+
37
+ /** The words that can follow "thunder" in a command (so prose like "thunder is on your PATH" stays plain). */
38
+ const VERBS = 'new|run|build|test|check|format|fmt|read|try|why|help|doctor|completion|init|mission|trace|review|same|write|repo|thunderize|verify|prove|lift|drift|changes|scan|report|explain|docs|atlas|index|gen|conform|export|import|runtime|anchor|text|human|graph|focus|risks|gaps|edit|mcp|lsp';
39
+ const COMMAND = new RegExp(`(^|[\\s\`(:])(thunder (?:${VERBS})\\b[^\\n\`]*)`, 'g');
40
+
41
+ /** Highlight `thunder …` commands inside a line of text: up to two spaces, a semicolon, or the end. */
42
+ export function commands(line, on = useColor()) {
43
+ if (!on) return line;
44
+ return line.replace(COMMAND, (_, pre, rest) => {
45
+ let c = rest.split(/ {2,}|; /)[0];
46
+ const tail = rest.slice(c.length);
47
+ const trail = c.match(/[.?!,;)]+$/)?.[0] ?? '';
48
+ c = c.slice(0, c.length - trail.length);
49
+ return `${pre}${cyan(c, on)}${trail}${tail}`;
50
+ });
51
+ }
52
+
53
+ /** Remove color (for tests and for measuring width). */
54
+ export const plain = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '');
55
+
56
+ /**
57
+ * Paint a screen of text: marks (✓ ✗ ! ◆ ■ ▶), `thunder …` commands, "Label:" words at the start of a line, and
58
+ * headings (a line of its own with no indent). Plain text comes back unchanged when color is off.
59
+ */
60
+ export function paint(text, on = useColor()) {
61
+ if (!on) return text;
62
+ return String(text).split('\n').map((line) => {
63
+ if (/^─+$/.test(line)) return dim(line, on);
64
+ let l = marks(line, on);
65
+ l = l.replace(/^(\s*)◆/, (_, s) => `${s}${yellow('◆', on)}`).replace(/^(\s*)■/, (_, s) => `${s}${green('■', on)}`).replace(/^(\s*)▶/, (_, s) => `${s}${cyan('▶', on)}`);
66
+ l = l.replace(/^⚡ (.+?)(?=:|$)/, (_, t) => `${yellow('⚡', on)} ${bold(t, on)}`);
67
+ // " Why: …", "Answer: …", "Next: …": the label in bold.
68
+ l = l.replace(/^(\s*)([A-Z][A-Za-z ]{1,18}:)(?=\s|$)/, (_, s, lab) => `${s}${bold(lab, on)}`);
69
+ // A title like "Flow · Late fee (library.py:24)".
70
+ if (/^[A-Z][^·]* · /.test(line)) l = bold(l, on);
71
+ // A heading: an unindented line with no colon-label, not a sentence that ends with a full stop.
72
+ if (/^[A-Z][^.:]*$/.test(plain(line)) && plain(line).length < 60) l = bold(l, on);
73
+ return commands(l, on);
74
+ }).join('\n');
75
+ }
76
+
77
+ /** The full command list: headings bold, each command name cyan, its [options] dimmed. */
78
+ export function paintHelp(text, on = useColor()) {
79
+ if (!on) return text;
80
+ return String(text).split('\n').map((line) => {
81
+ if (/^─+$/.test(line)) return dim(line, on);
82
+ if (/^⚡ /.test(line)) return `${yellow('⚡', on)} ${bold(line.slice(2), on)}`;
83
+ if (/^Advanced:/.test(line)) return yellow(line, on);
84
+ if (/^[A-Z][^:]*$/.test(line) && !/^usage/.test(line)) return bold(line, on);
85
+ const m = line.match(/^( {2})([a-z][a-z0-9-]*(?: \| [a-z][a-z0-9-]*)*)(.*)$/);
86
+ if (m) return `${m[1]}${cyan(m[2], on)}${m[3].replace(/(\[[^\]]*\])/g, (x) => dim(x, on))}`;
87
+ return line;
88
+ }).join('\n');
89
+ }