@skillstech/thunderlang 0.5.5 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillstech/thunderlang",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "Deterministic ThunderLang compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -16,6 +16,11 @@
16
16
  "import": "./src/core.mjs",
17
17
  "require": "./dist/core.cjs"
18
18
  },
19
+ "./learn": {
20
+ "types": "./src/learn.d.mts",
21
+ "import": "./src/learn.mjs",
22
+ "require": "./dist/learn.cjs"
23
+ },
19
24
  "./package.json": "./package.json"
20
25
  },
21
26
  "bin": {
@@ -47,6 +52,10 @@
47
52
  "esbuild": "^0.28.1"
48
53
  },
49
54
  "keywords": [
55
+ "thunder",
56
+ "thunder-programming-language",
57
+ "programming-language",
58
+ "human-native-programming",
50
59
  "intent",
51
60
  "thunderlang",
52
61
  "intent-oriented-programming",
package/src/core.d.ts CHANGED
@@ -11,8 +11,8 @@ export { HumanContractPreview, compileHumanContract, previewHumanContract, rende
11
11
  export { ANCHOR_SCHEMA, spanRange, spanText, replaceSpan, editStep, anchorReport } from './anchor.mjs';
12
12
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
13
13
  export { STEPS_SCHEMA, classifyStatement } from './steps.mjs';
14
- export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText, thunderTokens } from './visual.mjs';
15
- export { MODEL_SCHEMA, THING_LANGUAGES, thunderModel, modelText, flowOf, ruleFlow, askAsQuestion, stepDoes } from './model.mjs';
14
+ export { VISUAL_SCHEMA, THUNDER_VISUAL, LEVELS, PLACES, visualFor, visualForStep, thunderText, thunderTokens } from './visual.mjs';
15
+ export { MODEL_SCHEMA, THING_LANGUAGES, thunderModel, modelText, readLevel, flowOf, ruleFlow, askAsQuestion, stepDoes } from './model.mjs';
16
16
  export { THUNDERIZE_SCHEMA, THUNDER_TEXT_EXT, thunderizeFile, thunderizeFiles } from './thunderize.mjs';
17
17
  export { SAME_SCHEMA, sameMeaning, compareRules, renderSame } from './same.mjs';
18
18
  export type { ColorRole, ElementKind, Provenance as VisualProvenance, Visual } from './visual.mjs';
package/src/core.mjs CHANGED
@@ -10,8 +10,8 @@ export { compileHumanContract, previewHumanContract, renderHumanContract, render
10
10
  export { ANCHOR_SCHEMA, spanRange, spanText, replaceSpan, editStep, anchorReport } from './anchor.mjs';
11
11
  export { WRITE_SCHEMA, writeRule, changedCases, ruleParts, joinRuleParts, COMPARISON_CHOICES } from './write.mjs';
12
12
  export { STEPS_SCHEMA, classifyStatement } from './steps.mjs';
13
- export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText, thunderTokens } from './visual.mjs';
14
- export { MODEL_SCHEMA, THING_LANGUAGES, thunderModel, modelText, flowOf, ruleFlow, askAsQuestion, stepDoes } from './model.mjs';
13
+ export { VISUAL_SCHEMA, THUNDER_VISUAL, LEVELS, PLACES, visualFor, visualForStep, thunderText, thunderTokens } from './visual.mjs';
14
+ export { MODEL_SCHEMA, THING_LANGUAGES, thunderModel, modelText, readLevel, flowOf, ruleFlow, askAsQuestion, stepDoes } from './model.mjs';
15
15
  export { THUNDERIZE_SCHEMA, THUNDER_TEXT_EXT, thunderizeFile, thunderizeFiles } from './thunderize.mjs';
16
16
  export { SAME_SCHEMA, sameMeaning, compareRules, renderSame } from './same.mjs';
17
17
  export { plainFromReading, conditionText } from './plain-contract.mjs';
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '0.5.5';
33
+ export const COMPILER_VERSION = '0.5.7';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.
@@ -0,0 +1,458 @@
1
+ // Learn Thunder: the Thunder V1 tutorial, shipped in the npm package (`@skillstech/thunderlang/learn`) so every
2
+ // release carries a tutorial that matches its language. Twelve short lessons on reading software in Thunder, about
3
+ // one small pizza app and a school library. thunderlang.dev/learn and the Skills Tech Talk course are built from
4
+ // this file. Every quiz answer is worked out by the compiler (`check`) when the lessons are built: if the compiler
5
+ // ever disagrees with what a lesson expects, the build fails (see learn.mjs and test/learn-export.test.mjs).
6
+
7
+ /**
8
+ * @typedef {{ language: string, label: string, code: string }} LessonFile
9
+ * @typedef {{
10
+ * slug: string, title: string, idea: string, picture: string,
11
+ * files: LessonFile[], focus: string,
12
+ * show: 'steps' | 'card' | 'compare' | 'text' | 'honest' | 'shapes' | 'thing' | 'flow' | 'howto' | 'openthunder',
13
+ * examples?: string, questions: { q: string, a: string }[],
14
+ * part?: 'read' | 'write', quiz: QuizQuestion[],
15
+ * }} ReadLesson
16
+ * @typedef {{ prompt: string, choices: string[], expect: string, explain: string, check: (ctx: any) => string }} QuizQuestion
17
+ */
18
+
19
+ /** The delivery rule in four languages, without doc comments, so only the language differs. */
20
+ const strip = (code) => code.split('\n').filter((l) => !/^\s*("""|\/\*\*|\/\/ )/.test(l)).join('\n');
21
+
22
+ const DELIVERY = {
23
+ python: `def delivery_fee(total: float, distance_km: float) -> str:
24
+ """Nearby orders of $20 or more are delivered free."""
25
+ if total >= 20 and distance_km <= 5:
26
+ return "Free"
27
+ if distance_km > 15:
28
+ return "TooFar"
29
+ return "Standard"
30
+ `,
31
+ typescript: `/** Nearby orders of $20 or more are delivered free. */
32
+ function deliveryFee(total: number, distanceKm: number): string {
33
+ if (total >= 20 && distanceKm <= 5) return "Free";
34
+ if (distanceKm > 15) return "TooFar";
35
+ return "Standard";
36
+ }
37
+ `,
38
+ java: `class Delivery {
39
+ /** Nearby orders of $20 or more are delivered free. */
40
+ static String deliveryFee(double total, double distanceKm) {
41
+ if (total >= 20 && distanceKm <= 5) return "Free";
42
+ if (distanceKm > 15) return "TooFar";
43
+ return "Standard";
44
+ }
45
+ }
46
+ `,
47
+ go: `package delivery
48
+
49
+ // DeliveryFee: nearby orders of $20 or more are delivered free.
50
+ func DeliveryFee(total float64, distanceKm float64) string {
51
+ if total >= 20 && distanceKm <= 5 {
52
+ return "Free"
53
+ }
54
+ if distanceKm > 15 {
55
+ return "TooFar"
56
+ }
57
+ return "Standard"
58
+ }
59
+ `,
60
+ };
61
+
62
+
63
+ /** The school library: a Thing with what it knows and what it can do (lessons 3 and 4). */
64
+ const LIBRARY = `from dataclasses import dataclass
65
+ from enum import Enum
66
+
67
+
68
+ class Status(Enum):
69
+ ON_SHELF = "on shelf"
70
+ BORROWED = "borrowed"
71
+
72
+
73
+ @dataclass
74
+ class Book:
75
+ """A book in the school library."""
76
+ title: str
77
+ status: Status = Status.ON_SHELF
78
+
79
+
80
+ class Library:
81
+ """Lends books to students and takes them back."""
82
+
83
+ def __init__(self, max_books: int = 3):
84
+ self.max_books = max_books
85
+ self.overflow = []
86
+
87
+ def late_fee(self, days_late: int) -> str:
88
+ """Small fines for late books."""
89
+ if days_late <= 7:
90
+ return "SmallFee"
91
+ return "BigFee"
92
+
93
+ def return_book(self, student, book, days_late: int):
94
+ """A student brings a book back."""
95
+ if book not in student.books:
96
+ raise NotBorrowed("This student does not have this book")
97
+ student.books.remove(book)
98
+ if days_late > 0:
99
+ fee = self.late_fee(days_late)
100
+ student.fees.append(fee)
101
+ else:
102
+ student.thanks += 1
103
+ try:
104
+ self.shelf.put(book)
105
+ except ShelfFull:
106
+ self.overflow.append(book)
107
+ finally:
108
+ book.status = Status.ON_SHELF
109
+ `;
110
+
111
+ /** Examples a person adds to check the rule (code has none). */
112
+ const DELIVERY_EXAMPLES = `
113
+ Examples
114
+ 25, 3 gives Free (a big order nearby)
115
+ 20, 5 gives Free (exactly at both limits)
116
+ 19, 3 gives Standard (one dollar short)
117
+ 25, 6 gives Standard (just too far for free delivery)
118
+ 25, 16 gives TooFar (outside the delivery area)
119
+ `;
120
+
121
+ /** A small app with two doors and one rule (lesson 11: reading a whole app in OpenThunder). */
122
+ const PIZZA_APP = `from fastapi import APIRouter
123
+
124
+ router = APIRouter()
125
+
126
+
127
+ def delivery_fee(total: float, distance_km: float) -> str:
128
+ """Nearby orders of $20 or more are delivered free."""
129
+ if total >= 20 and distance_km <= 5:
130
+ return "Free"
131
+ if distance_km > 15:
132
+ return "TooFar"
133
+ return "Standard"
134
+
135
+
136
+ @router.post("/orders")
137
+ def place_order(order):
138
+ """A customer orders pizza."""
139
+ if not order.items:
140
+ raise EmptyOrder("Add at least one pizza")
141
+ fee = delivery_fee(order.total, order.distance_km)
142
+ if fee == "TooFar":
143
+ raise TooFar("We do not deliver that far")
144
+ order.save()
145
+ return order
146
+
147
+
148
+ @router.get("/orders/{order_id}")
149
+ def track_order(order_id):
150
+ """A customer checks where their pizza is."""
151
+ order = Order.find(order_id)
152
+ return order.status
153
+ `;
154
+
155
+ // Helpers the quiz checks use: they look only at what the compiler produced.
156
+ const flatSteps = (steps) => (steps || []).flatMap((s) => [s, ...flatSteps(s.children), ...flatSteps(s.otherwise)]);
157
+ const humanAnswer = (s) => String(s).replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^(\w)(.*)$/, (_, a, b) => a.toUpperCase() + b.toLowerCase());
158
+ const TS_DELIVERY_16 = strip(DELIVERY.typescript).replace('distanceKm > 15', 'distanceKm > 16');
159
+
160
+ /** @type {ReadLesson[]} */
161
+ export const READ_LESSONS = [
162
+ {
163
+ slug: "pictures",
164
+ part: "read",
165
+ quiz: [
166
+ { prompt: "In order_total, which step happens only when the order has a coupon?", choices: ["Adds item price to total", "Subtracts 5 from total", "Gives back total"], expect: "Subtracts 5 from total",
167
+ explain: "It sits inside the choice \"If order has coupon\", so it only happens on that path. The other two happen for every order.",
168
+ check: ({ item }) => flatSteps(item.steps).find((s) => s.kind === 'branch' && /coupon/.test(s.says)).children[0].says },
169
+ ],
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.",
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
+ files: [{ language: "python", label: "Python", code: `def order_total(order):
174
+ total = 0
175
+ for item in order.items:
176
+ total += item.price
177
+ if order.has_coupon:
178
+ total -= 5
179
+ return total
180
+ ` }],
181
+ focus: "order_total",
182
+ show: "steps",
183
+ questions: [
184
+ { q: "In your own words, what does order_total do?", a: "It adds up the price of every item, takes $5 off when the order has a coupon, and gives back the total. You could say that without knowing Python. That is the point." },
185
+ { q: "Who drew this picture, a person or an AI?", a: "Neither. The Thunder compiler read the code with fixed rules and no AI. The same code always gives the same picture." },
186
+ ],
187
+ },
188
+ {
189
+ slug: "shapes",
190
+ part: "read",
191
+ quiz: [
192
+ { prompt: "Which shape means the program stops and says why?", choices: ["Thing", "Rule", "Steps", "Stop"], expect: "Stop",
193
+ explain: "Stop is the octagon, like a stop sign. It ends that path and shows the reason.",
194
+ check: ({ symbols }) => Object.values(symbols).find((s) => s.beginner && s.color === 'failure').name },
195
+ { prompt: "Which shape looks at some facts and picks one answer?", choices: ["Thing", "Rule", "Steps", "Data"], expect: "Rule",
196
+ explain: "A Rule is the diamond: a decision, such as which fee to charge.",
197
+ check: ({ symbols }) => Object.values(symbols).find((s) => s.beginner && s.color === 'question').name },
198
+ ],
199
+ title: "The six shapes",
200
+ idea: "Everything in a program is one of six kinds of thing, and each has its own shape. Learn these six and you can tell what any piece of code is before you read a single word.",
201
+ picture: "Road signs again: a stop sign is an octagon everywhere in the world. Thunder's shapes work the same way in every programming language.",
202
+ files: [],
203
+ show: "shapes",
204
+ questions: [
205
+ { q: "You see a diamond. What kind of thing is it, and what will it do?", a: "A Rule. It looks at some facts and picks one answer, like \"Small fee\" or \"Big fee\"." },
206
+ { q: "Which shape tells you the program gives up and says why?", a: "The octagon: Stop. It ends the path and shows the reason, for example \"This student does not have this book\"." },
207
+ ],
208
+ },
209
+ {
210
+ slug: "things",
211
+ part: "read",
212
+ quiz: [
213
+ { prompt: "How many books can a student have at once, unless someone says otherwise?", choices: ["1", "3", "As many as they like"], expect: "3",
214
+ explain: "What the Library knows includes \"max books: 3 unless told otherwise\". It comes from max_books: int = 3 in the code.",
215
+ check: ({ target }) => target.knows.find((k) => k.label === 'max books').start.match(/\d+/)[0] },
216
+ { prompt: "Book only remembers facts (a title and a status). How does Thunder draw it?", choices: ["As a Thing", "As Data", "As a Rule"], expect: "As Data",
217
+ explain: "It can't do anything, it only remembers facts, so it is Data (a record), drawn smaller than a Thing.",
218
+ check: ({ model }) => (model.things.find((t) => t.name === 'Book').kind === 'thing' ? 'As a Thing' : 'As Data') },
219
+ ],
220
+ title: "Things: what it knows, what it can do",
221
+ idea: "Programs are built from Things. A Thing knows some facts and can do some jobs. Code calls a Thing a class; Thunder just shows the box: what it knows, and what it can do.",
222
+ picture: "A toy robot's instruction card: on one side what's inside it (battery, 3 lights), on the other the buttons it has (walk, beep). You don't need to see the wires.",
223
+ files: [{ language: "python", label: "Python", code: LIBRARY }],
224
+ focus: "Library",
225
+ show: "thing",
226
+ questions: [
227
+ { q: "How many books can a student have at once, if nobody says otherwise?", a: "3. \"max books: a number, 3 unless told otherwise\" is in what the Library knows." },
228
+ { q: "Book and Status are drawn smaller. Why are they not Things?", a: "They only remember facts (a Book's title and status) or list allowed choices (on shelf, borrowed). They can't do anything, so Thunder draws them as Data." },
229
+ ],
230
+ },
231
+ {
232
+ slug: "flow",
233
+ part: "read",
234
+ quiz: [
235
+ { prompt: "A book comes back 3 days late. Which fee does the late fee rule pick?", choices: ["Small fee", "Big fee", "No fee"], expect: "Small fee",
236
+ explain: "3 is at most 7, so the rule picks Small fee. The compiler ran the rule on 3 to check.",
237
+ check: ({ run }) => humanAnswer(run({ 'days late': 3 }, 'late_fee')) },
238
+ { prompt: "The shelf is full when the book comes back. Does the book still end up marked \"on shelf\"?", choices: ["Yes", "No"], expect: "Yes",
239
+ explain: "\"If ShelfFull goes wrong\" puts it on the overflow pile, and \"Always, at the end\" marks it on shelf no matter what happened.",
240
+ check: ({ text }) => (/Always, at the end:\n\s+- Sets the book's status to on shelf/.test(text) ? 'Yes' : 'No') },
241
+ ],
242
+ title: "Follow the flow",
243
+ idea: "When a Thing does a job, it follows a path. Questions split the path into Yes and No. Some paths end at a Stop. Some steps only happen if something goes wrong, and some always happen at the end.",
244
+ picture: "A Choose Your Own Adventure book: at each question you turn to the Yes page or the No page, and some pages say THE END.",
245
+ files: [{ language: "python", label: "Python", code: LIBRARY }],
246
+ focus: "return_book",
247
+ show: "flow",
248
+ questions: [
249
+ { q: "A student returns a book 3 days late. What happens to their fees?", a: "Days late is more than 0, so Yes: the late fee rule works out a fee (Small fee, because 3 is at most 7) and it is added to the student's fees." },
250
+ { q: "The shelf is full. Does the book still end up marked \"on shelf\"?", a: "Yes. \"If ShelfFull goes wrong\" puts it in the overflow pile, and \"Always, at the end\" marks it on shelf no matter what happened before." },
251
+ ],
252
+ },
253
+ {
254
+ slug: "steps",
255
+ part: "read",
256
+ quiz: [
257
+ { prompt: "How many different ways can check_order fail?", choices: ["None", "1", "2", "3"], expect: "2",
258
+ explain: "There are two ✕ steps: EmptyOrder when there are no items, and TooFar when the address is more than 15 km away.",
259
+ check: ({ item }) => String(flatSteps(item.steps).filter((s) => s.kind === 'fail').length) },
260
+ ],
261
+ title: "Read the steps",
262
+ idea: "Most functions are a short list of steps. Each step has a mark that tells you what kind of step it is, so you can scan a function without reading every word.",
263
+ picture: "Road signs: you know what a stop sign means before you read the word. ◇ means a choice, ↻ means repeat, ✕ means something went wrong.",
264
+ files: [{ language: "python", label: "Python", code: `def check_order(order):
265
+ if not order.items:
266
+ raise EmptyOrder("Add at least one pizza")
267
+ if order.distance_km > 15:
268
+ raise TooFar("We do not deliver that far")
269
+ for item in order.items:
270
+ item.checked = True
271
+ count = len(order.items)
272
+ log.info("Order checked")
273
+ return count
274
+ ` }],
275
+ focus: "check_order",
276
+ show: "steps",
277
+ questions: [
278
+ { q: "Which marks show the two ways this function can fail?", a: "The two ✕ steps: an order with no items fails with EmptyOrder, and an address more than 15 km away fails with TooFar. Each sits inside the ◇ choice that leads to it." },
279
+ { q: "What does the ↻ step repeat, and what happens inside it?", a: "It goes through every item in the order and marks each one as checked (the = step inside it)." },
280
+ ],
281
+ },
282
+ {
283
+ slug: "cards",
284
+ part: "read",
285
+ quiz: [
286
+ { prompt: "An order of exactly $20, exactly 5 km away. What does the card say?", choices: ["Free", "Standard", "TooFar"], expect: "Free",
287
+ explain: "At least $20 and at most 5 km both include the limit itself, so the first rule fits: Free.",
288
+ check: ({ run }) => run({ total: 20, 'distance km': 5 }) },
289
+ { prompt: "An order of $25, 16 km away. What does the card say?", choices: ["Free", "Standard", "TooFar"], expect: "TooFar",
290
+ explain: "It is too far for free delivery, and 16 is over 15, so the second rule fits: TooFar.",
291
+ check: ({ run }) => run({ total: 25, 'distance km': 16 }) },
292
+ ],
293
+ title: "Rules become cards",
294
+ idea: "Some functions decide something: they look at a few facts and pick an answer. Thunder draws each one as a card. You can ask the card a question and see which answer it gives, and why.",
295
+ picture: "A card is a referee's rule book page: the facts it looks at, each rule in order, and the answer when no rule fits. The first rule that fits wins.",
296
+ files: [{ language: "python", label: "Python", code: DELIVERY.python }],
297
+ focus: "delivery_fee",
298
+ show: "card",
299
+ examples: DELIVERY_EXAMPLES,
300
+ questions: [
301
+ { q: "An order of exactly $20, exactly 5 km away. Free or Standard? Decide before you ask the card.", a: "Free. The rule says at least $20 and at most 5 km, and both include the limit itself. Try it on the card to check." },
302
+ { q: "Where did the line under the title come from?", a: "From the programmer's own note in the code (the docstring). Thunder shows it as the author's note, separately from what the code does, because a note can be out of date while the code is what actually runs." },
303
+ ],
304
+ },
305
+ {
306
+ slug: "actions",
307
+ part: "read",
308
+ quiz: [
309
+ { prompt: "What is the address of this door?", choices: ["GET /orders", "POST /orders", "POST /pay"], expect: "POST /orders",
310
+ explain: "The label on the door comes from @router.post(\"/orders\") in the code.",
311
+ check: ({ item }) => `${item.route.method} ${item.route.path}` },
312
+ { prompt: "The delivery fee comes back TooFar. Is the card charged?", choices: ["Yes", "No"], expect: "No",
313
+ explain: "The TooFar stop comes before the Stripe step, and steps run top to bottom, so the action stops first.",
314
+ check: ({ item }) => {
315
+ const stop = item.steps.findIndex((s) => flatSteps(s.children).some((c) => c.kind === 'fail' && /TooFar/.test(c.says)));
316
+ const charge = item.steps.findIndex((s) => /stripe/i.test(s.says));
317
+ return stop >= 0 && stop < charge ? 'No' : 'Yes';
318
+ } },
319
+ ],
320
+ title: "Actions: the doors into an app",
321
+ idea: "An app has doors: things people can do, like placing an order. Thunder labels each one with its address (POST /orders) and shows what happens behind the door, step by step.",
322
+ picture: "A building with labeled doors. The label tells you which door; the steps tell you what happens after you walk through it.",
323
+ files: [{ language: "python", label: "Python", code: `@router.post("/orders")
324
+ def place_order(order, card):
325
+ """A customer orders pizza and pays for it."""
326
+ if not order.items:
327
+ raise EmptyOrder("Add at least one pizza")
328
+ total = order_total(order)
329
+ fee = delivery_fee(total, order.distance_km)
330
+ if fee == "TooFar":
331
+ raise TooFar("We do not deliver that far")
332
+ payment = stripe.charge(card, total)
333
+ send_email(order.customer, "Your pizza is on its way")
334
+ return payment
335
+ ` }],
336
+ focus: "place_order",
337
+ show: "steps",
338
+ questions: [
339
+ { q: "Name the two outside services this action talks to.", a: "Stripe, to charge the card, and email, to tell the customer the pizza is on its way. Thunder names known services instead of saying \"calls a function\"." },
340
+ { q: "If someone lives 20 km away, does their card get charged?", a: "No. The delivery fee comes back as TooFar, so the action fails with TooFar before the Stripe step. Order matters: steps run top to bottom." },
341
+ ],
342
+ },
343
+ {
344
+ slug: "any-language",
345
+ part: "read",
346
+ quiz: [
347
+ { prompt: "Do Python, TypeScript, Java, and Go give the same Thunder for this rule?", choices: ["Yes, exactly the same", "No, each is a little different"], expect: "Yes, exactly the same",
348
+ explain: "The code differs, but the meaning is the same, so the Thunder Text is identical, word for word.",
349
+ check: ({ texts }) => (texts.every((t) => t === texts[0]) ? 'Yes, exactly the same' : 'No, each is a little different') },
350
+ ],
351
+ title: "Same meaning, any language",
352
+ idea: "The delivery rule can be written in Python, TypeScript, Java, or Go. The code looks different every time. The Thunder is identical, because the meaning is identical.",
353
+ picture: "A song played on piano, guitar, or violin. The instruments sound different, but it is the same tune. Thunder is the tune.",
354
+ files: [
355
+ { language: "python", label: "Python", code: strip(DELIVERY.python) },
356
+ { language: "typescript", label: "TypeScript", code: strip(DELIVERY.typescript) },
357
+ { language: "java", label: "Java", code: strip(DELIVERY.java) },
358
+ { language: "go", label: "Go", code: strip(DELIVERY.go) },
359
+ ],
360
+ focus: "delivery fee",
361
+ show: "compare",
362
+ examples: DELIVERY_EXAMPLES,
363
+ questions: [
364
+ { q: "Pick two languages. Name one difference in the code and one difference in the Thunder.", a: "The code differs in small ways: def or function or func, and the or && for joining conditions. The Thunder has no differences at all. That is what human-native means: you read the meaning, not the language." },
365
+ { q: "Why does that matter when AI writes most of the code?", a: "AI can write in whichever language a team uses. You only need to read Thunder to understand all of it." },
366
+ ],
367
+ },
368
+ {
369
+ slug: "thunder-text",
370
+ part: "read",
371
+ quiz: [
372
+ { prompt: "Which line of Thunder Text is the TooFar rule?", choices: ["TooFar when the distance km is over 15.", "TooFar when the total is under 20.", "TooFar when the distance km is at most 5."], expect: "TooFar when the distance km is over 15.",
373
+ explain: "It matches the code's distance_km > 15, in words.",
374
+ check: ({ texts }) => texts[0].split('\n').map((l) => l.trim().replace(/^- /, '')).find((l) => l.startsWith('TooFar')) },
375
+ ],
376
+ title: "Thunder Text: the same thing in words",
377
+ idea: "Every picture has a twin written in plain words, called Thunder Text. Both are made from the same reading of the code, so they always agree. Use the picture to understand; use the text to read closely, review a change, or keep a copy.",
378
+ picture: "A map and written directions for the same trip. Neither one is a translation of the other; both come from the same roads.",
379
+ files: [{ language: "python", label: "Python", code: DELIVERY.python }],
380
+ focus: "delivery_fee",
381
+ show: "text",
382
+ examples: DELIVERY_EXAMPLES,
383
+ questions: [
384
+ { q: "Find the line in the Thunder Text that matches the TooFar rule on the card.", a: "\"TooFar when the distance km is over 15.\" Same rule, same words, same order." },
385
+ { q: "Is Thunder Text made from the picture?", a: "No. Both are made from the same reading of the code. That is why they can never disagree." },
386
+ ],
387
+ },
388
+ {
389
+ slug: "honest",
390
+ part: "read",
391
+ quiz: [
392
+ { prompt: "Thunder can't explain oven_temperature yet. What does it show you?", choices: ["A sentence an AI wrote", "The code itself, marked Not read yet", "Nothing at all"], expect: "The code itself, marked Not read yet",
393
+ explain: "Thunder never invents an explanation. It shows the exact code on a dashed card labeled Not read yet.",
394
+ check: ({ visuals }) => (visuals[0].line === 'dashed' ? 'The code itself, marked Not read yet' : 'A sentence an AI wrote') },
395
+ ],
396
+ title: "Honest by design",
397
+ idea: "Thunder never pretends. When it cannot explain a piece of code yet, it shows the code itself on a dashed card and says Not read yet. Every piece shows where it came from.",
398
+ picture: "A good guide says \"I don't know this street, here is the map\" instead of inventing directions. Dashed means not established; solid means read exactly or confirmed.",
399
+ files: [{ language: "python", label: "Python", code: `def oven_temperature(dough):
400
+ return (dough.thickness * 17 + 220) % 300
401
+ ` }],
402
+ focus: "oven_temperature",
403
+ show: "honest",
404
+ questions: [
405
+ { q: "Why does Thunder show code here instead of a sentence?", a: "A sentence like \"Returns a computed value\" would only repeat the code without explaining it. Thunder shows the code, dashed, so you know it was not explained, rather than reading a sentence that sounds helpful but says nothing." },
406
+ { q: "Which label would an AI-written explanation get, and how would it look?", a: "AI summary, with a dashed outline, always placed above the exact reading, never instead of it. It helps you understand; it is never the evidence." },
407
+ ],
408
+ },
409
+ {
410
+ slug: "openthunder",
411
+ part: "read",
412
+ title: "Read a whole app in OpenThunder",
413
+ idea: "A real app has many files. OpenThunder, the IDE for Thunder, reads a whole repository. You move from the App to a File, then an Action (a door), then one Rule, and you can read each of them at five levels: Big Picture, Flow, Details, Text, and Original. Every picture is drawn from the code, and the original code is always one click away.",
414
+ picture: "A map app: zoom out to see the whole city, zoom in to one street, then one house. It is the same map at every level.",
415
+ files: [{ language: "python", label: "Python", code: PIZZA_APP }],
416
+ focus: "place_order",
417
+ show: "openthunder",
418
+ quiz: [
419
+ { prompt: "How many doors (actions) does this app have?", choices: ["1", "2", "3"], expect: "2",
420
+ explain: "POST /orders to place an order and GET /orders/{order_id} to track one. delivery_fee is a rule, not a door: nobody can call it from outside.",
421
+ check: ({ all }) => String(all.filter((i) => i.route).length) },
422
+ { prompt: "Which door can stop with TooFar?", choices: ["POST /orders", "GET /orders/{order_id}", "Both"], expect: "POST /orders",
423
+ explain: "Only placing an order asks for the delivery fee and stops when it is TooFar. Tracking an order never does.",
424
+ check: ({ all }) => {
425
+ const doors = all.filter((i) => i.route && flatSteps(i.steps).some((s) => s.kind === 'fail' && /TooFar/.test(s.says)));
426
+ return doors.length > 1 ? 'Both' : `${doors[0].route.method} ${doors[0].route.path}`;
427
+ } },
428
+ { prompt: "delivery_fee looks at two facts and picks one answer. How does OpenThunder draw it?", choices: ["As a rule card", "As a list of steps", "As a Thing"], expect: "As a rule card",
429
+ explain: "A function that only chooses between fixed answers is a Rule, drawn as a card you can ask questions.",
430
+ check: ({ all, visualFor }) => (visualFor(all.find((i) => i.name === 'delivery_fee')).element === 'decision' ? 'As a rule card' : 'As a list of steps') },
431
+ ],
432
+ questions: [
433
+ { q: "A card shows an AI summary chip. Can you rely on it to know what the code does?", a: "No. An AI summary can help you understand, and it is always labeled and dashed, but it is never the evidence. The From code reading, and the original code, are." },
434
+ { q: "A picture looks wrong to you. Where do you check?", a: "The original code, one click away. Every picture is drawn from it, and the code is what actually runs." },
435
+ ],
436
+ },
437
+ {
438
+ slug: "study",
439
+ part: "read",
440
+ title: "Study your own app",
441
+ idea: "Now use Thunder on code you care about: one file in your browser, a whole folder in your terminal, or a whole app in OpenThunder. Converting or rewriting code? Thunder can check that the meaning stayed the same.",
442
+ picture: "A pair of glasses that works on any book. Put them on wherever you are reading.",
443
+ files: [],
444
+ show: "howto",
445
+ quiz: [
446
+ { prompt: "A teammate rewrote the delivery rule in TypeScript and changed 15 km to 16 km. What does thunder same say?", choices: ["Same meaning", "Different meaning"], expect: "Different meaning",
447
+ explain: "thunder same runs both rules on their edge cases. At 16 km the old rule says TooFar and the new one says Standard, so the meaning changed.",
448
+ check: ({ same }) => (same([{ path: 'delivery.py', source: strip(DELIVERY.python) }], [{ path: 'delivery.ts', source: TS_DELIVERY_16 }]) === 'same' ? 'Same meaning' : 'Different meaning') },
449
+ { prompt: "Another teammate only rewrote it in TypeScript, with the same limits. What does thunder same say?", choices: ["Same meaning", "Different meaning"], expect: "Same meaning",
450
+ explain: "The language and the spelling of names changed (distance_km became distanceKm), but every edge case gives the same answer.",
451
+ check: ({ same }) => (same([{ path: 'delivery.py', source: strip(DELIVERY.python) }], [{ path: 'delivery.ts', source: strip(DELIVERY.typescript) }]) === 'same' ? 'Same meaning' : 'Different meaning') },
452
+ ],
453
+ questions: [
454
+ { q: "You want to understand one file someone sent you. Which is fastest?", a: "Semantic Zoom or Thunder Code in your browser: paste the code and read it. Nothing is installed and nothing leaves your browser." },
455
+ { q: "Your team rewrote a service from Python to Java. How do you check nothing changed?", a: "thunder same old-folder new-folder. It reads both, runs every rule on its edge cases, compares the steps, and shows any difference with an example." },
456
+ ],
457
+ },
458
+ ];
@@ -0,0 +1,34 @@
1
+ /** A quiz question. `answer` was worked out by the compiler from the lesson's code. */
2
+ export interface LearnQuestion { prompt: string; choices: string[]; answer: string; explain: string }
3
+
4
+ export interface LearnLesson {
5
+ slug: string;
6
+ title: string;
7
+ /** What the lesson teaches, in plain words. */
8
+ idea: string;
9
+ /** A picture to hold in mind. */
10
+ picture: string;
11
+ part: 'read' | 'write';
12
+ /** The lesson's code (the first file), or null for lessons with no code. */
13
+ snippet: { language: string; code: string } | null;
14
+ /** Every file the lesson shows (a lesson can show the same rule in several languages). */
15
+ snippets: { language: string; label: string; code: string }[];
16
+ /** The Thunder Text the compiler gives for the lesson's focus, or null. */
17
+ thunderText: string | null;
18
+ questions: LearnQuestion[];
19
+ /** Open questions to think about, with a model answer. */
20
+ reflect: { prompt: string; answer: string }[];
21
+ }
22
+
23
+ export interface LearnThunder {
24
+ schema: 'thunder-learn-v1';
25
+ /** The compiler (and language) version these lessons were built against. */
26
+ languageVersion: string;
27
+ lessons: LearnLesson[];
28
+ }
29
+
30
+ export const LEARN_SCHEMA: 'thunder-learn-v1';
31
+ /** Build the tutorial. Throws if any lesson's expected answer disagrees with the compiler. */
32
+ export function learnThunder(): LearnThunder;
33
+ /** The lesson sources (code, wording, and the checks that work out each answer). */
34
+ export const READ_LESSONS: any[];
package/src/learn.mjs ADDED
@@ -0,0 +1,77 @@
1
+ // @skillstech/thunderlang/learn: the Thunder tutorial as data, shipped with every release so a course built from it
2
+ // always matches the language it teaches. Every quiz answer is worked out here by the compiler, from the lesson's
3
+ // own code; if the compiler's answer is not what the lesson expects, building the lessons throws, so a release can
4
+ // never carry a lesson that disagrees with the compiler. Browser-safe.
5
+ import { readCode } from './read.mjs';
6
+ import { thunderText, visualFor, SYMBOLS } from './visual.mjs';
7
+ import { thunderModel, modelText } from './model.mjs';
8
+ import { plainFromReading, explainPlain } from './plain-contract.mjs';
9
+ import { sameMeaning } from './same.mjs';
10
+ import { COMPILER_VERSION } from './emit.mjs';
11
+ import { READ_LESSONS } from './learn-lessons.mjs';
12
+
13
+ export const LEARN_SCHEMA = 'thunder-learn-v1';
14
+ export { READ_LESSONS };
15
+
16
+ const squash = (s) => String(s).replace(/[_\s]/g, '').toLowerCase();
17
+ const EXT = { python: 'py', typescript: 'ts', javascript: 'js', java: 'java', go: 'go', csharp: 'cs', ruby: 'rb', php: 'php', rust: 'rs', kotlin: 'kt' };
18
+ const MODEL_SHOWS = new Set(['thing', 'flow']);
19
+
20
+ /** What a lesson's quiz checks may look at: only what the compiler produced from the lesson's code. */
21
+ function lessonContext(lesson) {
22
+ const files = lesson.files.map((f, i) => ({ path: `lesson${i ? i + 1 : ''}.${EXT[f.language] ?? 'txt'}`, source: f.code }));
23
+ const readings = lesson.files.map((f) => readCode(f.code, { language: f.language }));
24
+ const all = readings.flatMap((r) => r.items);
25
+ const focus = lesson.focus ? readings.map((r) => r.items.find((i) => squash(i.name) === squash(lesson.focus))) : [];
26
+ const model = MODEL_SHOWS.has(lesson.show) && files.length ? thunderModel(files) : null;
27
+ const target = model && (lesson.show === 'thing' ? model.things.find((t) => t.name === lesson.focus) : model.members.find((m) => m.name === lesson.focus));
28
+ /** Run a rule (the focus, or one named) on facts given by their readable labels; gives back the answer. */
29
+ const run = (facts, name) => {
30
+ const item = name ? all.find((i) => squash(i.name) === squash(name)) : focus[0];
31
+ const plain = plainFromReading(item);
32
+ const values = {};
33
+ for (const input of plain.inputs) {
34
+ const key = Object.keys(facts).find((k) => squash(k) === squash(String(input.label).replace(/^the /, '')));
35
+ if (key === undefined) throw new Error(`no value given for ${input.label}`);
36
+ values[input.id] = facts[key];
37
+ }
38
+ return explainPlain(plain, values).outcome;
39
+ };
40
+ return {
41
+ item: focus[0], items: focus, all, model, target,
42
+ text: model && target ? modelText(model, target.id) : undefined,
43
+ texts: focus.map((i) => (i ? thunderText(i) : '')),
44
+ visuals: focus.map((i) => (i ? visualFor(i) : null)),
45
+ symbols: SYMBOLS, visualFor, run,
46
+ same: (oldFiles, newFiles) => sameMeaning(oldFiles, newFiles).verdict,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The tutorial: { schema, languageVersion, lessons }. Each lesson has its idea, a picture to hold in mind, its code
52
+ * (snippet), the Thunder Text the compiler gives for it, quiz questions whose answers the compiler worked out, and
53
+ * open questions to think about (reflect).
54
+ */
55
+ export function learnThunder() {
56
+ const lessons = READ_LESSONS.map((lesson) => {
57
+ const ctx = lessonContext(lesson);
58
+ const questions = (lesson.quiz || []).map((q, i) => {
59
+ const where = `Lesson "${lesson.slug}", question ${i + 1}`;
60
+ let answer;
61
+ try { answer = String(q.check(ctx)); } catch (e) { throw new Error(`${where}: the compiler could not answer it (${e.message}).`); }
62
+ if (!q.choices.includes(answer)) throw new Error(`${where}: the compiler's answer "${answer}" is not one of the choices.`);
63
+ if (answer !== q.expect) throw new Error(`${where}: the lesson expects "${q.expect}", but the compiler says "${answer}". Update the lesson to match the language.`);
64
+ return { prompt: q.prompt, choices: [...q.choices], answer, explain: q.explain };
65
+ });
66
+ const snippets = lesson.files.map((f) => ({ language: f.language, label: f.label, code: f.code }));
67
+ return {
68
+ slug: lesson.slug, title: lesson.title, idea: lesson.idea, picture: lesson.picture, part: lesson.part ?? 'read',
69
+ snippet: snippets[0] ? { language: snippets[0].language, code: snippets[0].code } : null,
70
+ snippets,
71
+ thunderText: ctx.text ?? (ctx.texts[0] || null),
72
+ questions,
73
+ reflect: lesson.questions.map((q) => ({ prompt: q.q, answer: q.a })),
74
+ };
75
+ });
76
+ return { schema: LEARN_SCHEMA, languageVersion: COMPILER_VERSION, lessons };
77
+ }