@skillstech/thunderlang 1.0.4 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +221 -0
- package/README.md +4 -1
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +16994 -8339
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +241 -89
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +184 -0
- package/src/core/diagnostics.mjs +82 -0
- package/src/core/engine-core.mjs +572 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +39 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +177 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/target-python.mjs +487 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +45 -6
- package/src/model.d.mts +7 -3
- package/src/model.mjs +19 -6
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/read-level.mjs +146 -0
- package/src/read.d.mts +11 -0
- package/src/read.mjs +40 -6
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/say-less.mjs +1432 -0
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/term.mjs +89 -0
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +41 -0
- package/src/why.d.mts +38 -0
- package/src/why.mjs +613 -0
- package/src/write-steps.mjs +22 -5
package/src/data-schema.mjs
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// consumable by API tooling (validators, codegen, mock servers) , the data-shape sibling of
|
|
4
4
|
// the DMN/BPMN decision/lifecycle exporters. Deterministic and pure.
|
|
5
5
|
|
|
6
|
+
import { moneyTypeMinorUnits } from './money.mjs';
|
|
7
|
+
|
|
6
8
|
// Known semantic types (with formats) and primitives, keyed lowercase. Module-level so the
|
|
7
9
|
// security/type semantic pass (`isRecognizedType`) and the JSON-Schema mapping share ONE
|
|
8
10
|
// source of truth , no drift between "what compiles" and "what the schema knows."
|
|
@@ -15,7 +17,8 @@ const SEMANTIC = {
|
|
|
15
17
|
timestamp: { type: 'string', format: 'date-time' },
|
|
16
18
|
duration: { type: 'string', format: 'duration' },
|
|
17
19
|
uuid: { type: 'string', format: 'uuid' },
|
|
18
|
-
|
|
20
|
+
// Thunder Money is an exact decimal string ("12.30"), never a JSON number a consumer would read as a float.
|
|
21
|
+
money: { type: 'string', pattern: '^-?[0-9]+(\\.[0-9]{1,2})?$', description: 'Thunder Money: an exact decimal amount with up to 2 minor units, as a string.' },
|
|
19
22
|
currency: { type: 'string' },
|
|
20
23
|
percentage: { type: 'number', minimum: 0, maximum: 100 },
|
|
21
24
|
secret: { type: 'string', writeOnly: true },
|
|
@@ -61,6 +64,10 @@ export function typeToJsonSchema(type) {
|
|
|
61
64
|
if (listMatch) return { type: 'array', items: typeToJsonSchema(listMatch[1]) };
|
|
62
65
|
|
|
63
66
|
const key = t.toLowerCase();
|
|
67
|
+
const units = moneyTypeMinorUnits(t);
|
|
68
|
+
if (units != null && key !== 'money') {
|
|
69
|
+
return { type: 'string', pattern: units ? `^-?[0-9]+(\\.[0-9]{1,${units}})?$` : '^-?[0-9]+$', description: `Thunder Money: an exact decimal amount with up to ${units} minor units, as a string.` };
|
|
70
|
+
}
|
|
64
71
|
if (SEMANTIC[key]) return { ...SEMANTIC[key] };
|
|
65
72
|
if (PRIMITIVE[key]) return { ...PRIMITIVE[key] };
|
|
66
73
|
// Unknown PascalCase entity -> an opaque object carrying its name (title), so tooling can
|
package/src/emit.mjs
CHANGED
|
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
export const COMPILER_VERSION = '1.0
|
|
33
|
+
export const COMPILER_VERSION = '1.2.0';
|
|
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.
|
package/src/evidence.mjs
CHANGED
|
@@ -88,7 +88,7 @@ export function conformToEvidence(report, ctx = {}) {
|
|
|
88
88
|
const targets = {};
|
|
89
89
|
for (const col of columns) {
|
|
90
90
|
const t = { pass: 0, fail: 0, declared: 0 };
|
|
91
|
-
for (const c of cases) { const s = c.targets?.[col]?.status; if (s === 'pass') t.pass++; else if (s === 'fail') t.fail++; else t.declared++; }
|
|
91
|
+
for (const c of cases) { const s = c.targets?.[col]?.status; if (s === 'pass') t.pass++; else if (s === 'fail' || s === 'error') t.fail++; else t.declared++; } // a target that could not run a case (error) failed it
|
|
92
92
|
targets[col] = t;
|
|
93
93
|
}
|
|
94
94
|
return [envelope('conformance.verified', `tl-conform-${short(ctx.intentHash)}`, ctx, {
|
package/src/expr.mjs
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
// unary := '-' unary | primary
|
|
14
14
|
// primary := number | string | bool | ident(.ident)* | '(' or ')' | '[' list ']'
|
|
15
15
|
|
|
16
|
+
import { moneyLiteral, moneyCompare, numberToDecimalText, MONEY_TYPES } from './money.mjs';
|
|
17
|
+
|
|
16
18
|
export class ExprError extends Error {}
|
|
17
19
|
|
|
18
20
|
const OPS = ['>=', '<=', '==', '!=', '&&', '||', '>', '<', '=', '+', '-', '*', '/', '%', '!', '(', ')', '[', ']', ','];
|
|
@@ -155,6 +157,10 @@ function evalNode(n, inputs) {
|
|
|
155
157
|
case 'neg': { const r = -Number(evalNode(n.a, inputs)); return Number.isFinite(r) ? r : null; }
|
|
156
158
|
case 'arith': {
|
|
157
159
|
const a = Number(evalNode(n.a, inputs)); const b = Number(evalNode(n.b, inputs));
|
|
160
|
+
// Thunder numbers are decimals: + - * are exact on decimal operands (0.1 + 0.2 == 0.3), so a
|
|
161
|
+
// money or percentage rule never decides on a binary floating point artefact.
|
|
162
|
+
const exact = decimalArith(n.op, a, b);
|
|
163
|
+
if (exact !== null) return exact;
|
|
158
164
|
const r = n.op === '+' ? a + b : n.op === '-' ? a - b : n.op === '*' ? a * b : n.op === '/' ? a / b : a % b;
|
|
159
165
|
// Non-finite results (divide/modulo by zero, NaN from non-numeric operands) are
|
|
160
166
|
// neutralized to null so they can never leak a surprising truthy comparison (e.g.
|
|
@@ -184,6 +190,36 @@ function evalNode(n, inputs) {
|
|
|
184
190
|
}
|
|
185
191
|
}
|
|
186
192
|
|
|
193
|
+
// Exact decimal + - * for finite numbers whose shortest decimal text has no exponent: scale both to
|
|
194
|
+
// integers (BigInt), operate, and scale back. Returns null when the operands are not plain decimals
|
|
195
|
+
// (the caller then uses ordinary number arithmetic) or the operator is / or %.
|
|
196
|
+
const PLAIN_DECIMAL = /^(-)?(\d+)(?:\.(\d+))?$/;
|
|
197
|
+
function decimalParts(x) {
|
|
198
|
+
if (!Number.isFinite(x)) return null;
|
|
199
|
+
const m = String(x).match(PLAIN_DECIMAL);
|
|
200
|
+
if (!m) return null;
|
|
201
|
+
const frac = m[3] || '';
|
|
202
|
+
const int = BigInt(m[2] + frac);
|
|
203
|
+
return { int: m[1] ? -int : int, scale: frac.length };
|
|
204
|
+
}
|
|
205
|
+
function decimalArith(op, a, b) {
|
|
206
|
+
if (op !== '+' && op !== '-' && op !== '*') return null;
|
|
207
|
+
const x = decimalParts(a); const y = decimalParts(b);
|
|
208
|
+
if (!x || !y) return null;
|
|
209
|
+
let int; let scale;
|
|
210
|
+
if (op === '*') { int = x.int * y.int; scale = x.scale + y.scale; }
|
|
211
|
+
else {
|
|
212
|
+
scale = Math.max(x.scale, y.scale);
|
|
213
|
+
const xi = x.int * 10n ** BigInt(scale - x.scale); const yi = y.int * 10n ** BigInt(scale - y.scale);
|
|
214
|
+
int = op === '+' ? xi + yi : xi - yi;
|
|
215
|
+
}
|
|
216
|
+
const neg = int < 0n;
|
|
217
|
+
const digits = (neg ? -int : int).toString().padStart(scale + 1, '0');
|
|
218
|
+
const text = scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits;
|
|
219
|
+
const r = Number(`${neg ? '-' : ''}${text}`);
|
|
220
|
+
return Number.isFinite(r) ? r : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
187
223
|
function eq(a, b) {
|
|
188
224
|
const na = asNum(a); const nb = asNum(b);
|
|
189
225
|
if (na != null && nb != null) return na === nb;
|
|
@@ -219,9 +255,47 @@ const DIALECTS = {
|
|
|
219
255
|
elixir: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => String(v), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(', ')}]`, nil: 'nil' },
|
|
220
256
|
};
|
|
221
257
|
|
|
222
|
-
|
|
258
|
+
// The literal decimal text of a numeric literal node (or a negated one), or null.
|
|
259
|
+
function literalDecimal(n) {
|
|
260
|
+
if (n.k === 'lit' && typeof n.v === 'number') return numberToDecimalText(n.v);
|
|
261
|
+
if (n.k === 'neg' && n.a.k === 'lit' && typeof n.a.v === 'number') return `-${numberToDecimalText(n.a.v)}`;
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function renderExpr(src, inputs, D, money = {}, dialect = 'js') {
|
|
223
266
|
const known = new Set(inputs);
|
|
267
|
+
const isMoney = (n) => n.k === 'ref' && Object.prototype.hasOwnProperty.call(money, n.path);
|
|
268
|
+
const moneyRefs = (n, out = []) => {
|
|
269
|
+
if (isMoney(n)) out.push(n.path);
|
|
270
|
+
else if (n.k === 'arith' || n.k === 'cmp') { moneyRefs(n.a, out); moneyRefs(n.b, out); }
|
|
271
|
+
else if (n.k === 'neg') moneyRefs(n.a, out);
|
|
272
|
+
return out;
|
|
273
|
+
};
|
|
274
|
+
// A comparison that involves a Money input renders with the target's exact Money type. Each side
|
|
275
|
+
// may be a Money input, an amount such as 12.30, or a sum/difference of those (exact in every Money
|
|
276
|
+
// representation). Anything else (multiplication, division, mixing currencies) is refused.
|
|
277
|
+
const moneyCmp = (n) => {
|
|
278
|
+
if (!MONEY_TYPES[dialect]) throw new ExprError(`Money inputs have no exact representation in this target yet, and Thunder will not compare money as binary floating point`);
|
|
279
|
+
const refs = moneyRefs(n);
|
|
280
|
+
const units = money[refs[0]];
|
|
281
|
+
const other = refs.find((p) => money[p] !== units);
|
|
282
|
+
if (other) throw new ExprError(`"${refs[0]}" and "${other}" are Money with different minor units (different currencies)`);
|
|
283
|
+
const side = (x) => {
|
|
284
|
+
if (isMoney(x)) return x.path;
|
|
285
|
+
const dec = literalDecimal(x);
|
|
286
|
+
if (dec != null) { try { return moneyLiteral(dialect, dec, units); } catch (e) { throw new ExprError(e.message); } }
|
|
287
|
+
if (x.k === 'arith' && (x.op === '+' || x.op === '-')) {
|
|
288
|
+
const a = side(x.a); const b = side(x.b);
|
|
289
|
+
if (dialect === 'java') return `${a}.${x.op === '+' ? 'add' : 'subtract'}(${b})`;
|
|
290
|
+
return `(${a} ${x.op} ${b})`;
|
|
291
|
+
}
|
|
292
|
+
throw new ExprError(`Money can only be compared with Money inputs, amounts such as 12.30, or their sums and differences; multiplication, division, and other computed values are not translated exactly`);
|
|
293
|
+
};
|
|
294
|
+
return moneyCompare(dialect, n.op, side(n.a), side(n.b));
|
|
295
|
+
};
|
|
224
296
|
const r = (n) => {
|
|
297
|
+
if (n.k === 'cmp' && moneyRefs(n).length) return moneyCmp(n);
|
|
298
|
+
if (isMoney(n)) throw new ExprError(`Money input "${n.path}" is used outside a comparison (arithmetic, lists, or yes/no use are not translated exactly)`);
|
|
225
299
|
switch (n.k) {
|
|
226
300
|
case 'or': return D.or(r(n.a), r(n.b));
|
|
227
301
|
case 'and': return D.and(r(n.a), r(n.b));
|
|
@@ -274,10 +348,13 @@ export function simplifyExpr(src) {
|
|
|
274
348
|
/**
|
|
275
349
|
* Render a `when` condition as an equivalent expression in a target language, for code generation.
|
|
276
350
|
* Input names render as identifiers; any other bare token is an enum literal (a string). Reuses
|
|
277
|
-
* the parser, so precedence is exact. `dialect` is js (default) | csharp | java
|
|
351
|
+
* the parser, so precedence is exact. `dialect` is js (default) | csharp | java | python | go | rust |
|
|
352
|
+
* kotlin | scala | elixir. `money` maps Money input names to their minor units; comparisons on them
|
|
353
|
+
* render with the target's exact Money type (money.mjs), and any other use throws ExprError.
|
|
278
354
|
*/
|
|
279
|
-
export function exprToCode(src, { inputs = [], dialect = 'js' } = {}) {
|
|
280
|
-
|
|
355
|
+
export function exprToCode(src, { inputs = [], dialect = 'js', money = {} } = {}) {
|
|
356
|
+
const d = DIALECTS[dialect] ? dialect : 'js';
|
|
357
|
+
return renderExpr(src, inputs, DIALECTS[d], money || {}, d);
|
|
281
358
|
}
|
|
282
359
|
export const exprToJs = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'js' });
|
|
283
360
|
export const exprToCSharp = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'csharp' });
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// Generated by scripts/form-words.mjs from the step readers' fixed wording. Do not edit by hand.
|
|
2
|
+
export const FORM_WORDS = new Set("abort about above acc accepted access account accountsfor across act action actions active actives actor ad add added adding address adds admin administrator after afterall aftereach again against agrees ahead aks alias alignas alignof all allowed allows allsteps alone along alongside also alter always amazon amount an analytics and andor andorsteps annotateroutes annotation annotations announces another ansible answer answers any anything anywhere api app appending applies apply approves appservice are arg args argsat argsof argument arguments argv arith arithsays arithwords arm armexpr arms armsays armssubject around arr array arraylist arrives arrow arrowparam arrowre as ascall ascodewords asg aside asking asks asm assert assign assigned assignedto assignment assigns assignsteps assignwords associatedtype async asyncsession at atom attachclause attaches attr attribute attributes auth author auto available average await away aws az azure ba back background backs backticks backup bad badgateway badge badrequest balance balanced balancedreturnhead balancedtext balancer band bang bar bare base based baseline basync bb bbetween bc bdo be become becomes before beforeall beforebare beforeeach begin being belong below belse belseif bench berrors besides best between bfor bhandler bif big bigint bin binds bis bits blank blankcalls blanked blankpreprocessor blankstrings blet blk blob block blockat blocked blockend blocks bmethod bnot bo bodies bodiless body bodyrange bodystart book books bool boolean bor both bottom brace braces bracetextwithvalues bracewords bracket brackets bracketsclosed branch branches break brings bthen bucket build building builds built builtin bulk bus buse but bwhere by byname byte cache calculation call callable callargs callback called callee caller calling callnoun callof calls callverb can cancellationtoken cancelled cancels cannot cannotfail cap capital captures card carries carry case casebreaks caselabel cases cast cat catch catchall catches categories caught caused ccontainer cd cdecl cdeclaration cerr cfg ch chain chained change changed changes changing channel char character characters charat chars chart charts chead check checked checknotnull checkpoint checkpoints checks children choice choices choose chooser chooses choosing chr claim class classes classifystatement classifywords classname clause clausehead clausekids clauses clean cleancheader cleandoc cleans cleansteps clears cli click client clip clog close closed closein closeof closes closing closure closurehead closures cloud cloudformation cloudfront cloudwatch cls cluster cmd cmdlets cmds cmp cnormalize co code codeexpr codeof col collapsed collect collection colon column columns come comes command commandcalledas commands comment comments commit commits committed common compare compares comparison comparisons compile compiled completely completenessof compose compound computed cond condition conditions condjs condsaid condt condwords config configureawait confirm confirms conflict conn connected connection connects const consteval constexpr constinit constructor cont contain container containers content contents context continuation continuations continue continues control controller convenience conversion convert copies copy cosmos could count countable counted counting counts cout cpp crate create created createdataction createdatroute creates creturntype csays cstyle csuffixok csv ct ctor ctrl ctx ctype cur curl current cursor da daemon dashed data database date datetime db dbcc dbcontext dbl deallocate debounce debugging debugprint debugs decimal decision decisionof declaration declarations declare declared declares declspec decltype decodes decorator decorators def default defer defined definefunction defineproperty defines definething definition definitions deinit delete deletes delim delivery deliveryfee deny depends deploying deployment deploys deprecate deprecated deps depth desc descending describe detached detaches detail detailed details dev dfr di dialect dialects dict dictionary did didset dies differ different diouxxeeffggaacspn dir directory disconnects display displaylabel diusc divided divides dividing do doas doc docabove docker dockerfile docline docstring docstrings does dollar done double doubled down downloads dprintf dq drawn draws drop drops due dur dw dyn dynamic dynamodb ea each early easy eb ec echo ecr ecs ed edits ee eennbbxx effect eks elif eligible elixir else elseat elseif elsif elvis email empties empty enabled encodes end endline ends endswith enforces english ensure enters entries entry enum enumerable enumerated enums env environment eo err error errorf errors esc escapes eval even event eventhubs every everyday everything ex exact exactly example examples excel except excepted exchange exec execute executed exist existing exists exit exitcode expands expect explained explains explicit export exported exports expr express expression exprsteps extension extern extof extra exts fa fact fail failcode failed failnow fails failure faithfulness fakes fallback fallbackwords fallsthrough fallthrough false family far fastify fastifyreply fastifyrequest fatal fatalf fb fd fdescribe fee fetch ffddmmll field fields file fileprivate files fills filter final finally find findcfunctions findindex finds findswiftfunctions finish finished finishes first firstargs firstblock firststring firsttext fits fix fixed fixedof fixes flags flat flatmap float fmt fmtat fn fname fnidx fnline fnre fns fnsteps fnvalue folder folders follows foo fooled for forbidden force forceinline foreach forgets form format formats forms formula forward forwardref found fprintf fputs frame framework frees friend from front full fully fun func function functions fv gate gated gateway gc generic get getopts gets getter gg gi gim git give given gives givevalue giving glob global globals globby gm go goes going gone google got goto gradle grant grants graph grep group groupcases grouped grouping groupop groups grows gt guard had halt handle handler handlers handles handling hands happens has hash hashset hashtable hasown hastext have having head header headerdoc headers headline headof hello helm helper helptext here hh hides highest history hit hold holds home hour how hs htmlresponse http httpcontext httperrorof httpfail httprequest httpresponse httpservletrequest hubs iam id identity idioms idx if ifchain ifsteps ignores ignoring ilnow ilogger im image images impl implemented implicitreturn import imports in iname inat include included includes inclusive indentedjson index indexedwords indexof inferred init initialize initializer inl inline inlineelse inlinekid inner innere innernote inners input inputs inputsof insert insertcode inserted insertgetid insertname inside inspects installed installing installs instanceof int integer interesting interface internal internalservererror interrupt intest into intoalways invisible ioexception ip is isarray iscode iscodewords isdef isdevnull isglob isid isinstance islast isop isp isplumbing isset isspace istest isvar isw it item items iter iterable its itself iw java javascript jmp job jobs join joincontinued joined joinedtext joins joinword jscontext jsmorefunctions json jsonify jsonresponse jump jumps just kb keep keepat keeping keeps kept key keyboard keys keyvault keyword kid kids kill kind kinds kindwords know known knows knowsfrom koa kotlin kotlinexprend kotlinpattern kotlinterminate kotlinwhenarms kt kubectl kubernetes kv kw label labels lambda lang language languages lapply large larger largest last lastcmd lastexitcode lastindex lastindexof lastn lastop lastseg laststeps lastval lastwords late later latest lead leadingdoc least leave leaves left len length less let lets letter letters letting level lex lexsql lgl lhs lib library librarystep licence like limits line lineat linedoc linefinder lines link linked links list listargs listed lists listwords lit literal literalpath literals live ll load loads local location lock locks lodash log logger logging logic logical login logs long longer looking looks lookup loop loopofapply lower lowest ls lv machine macro macros made make makereader makes makestepper makestype managed management manager many map mapcode mapping mapply mark marked marks maskcode masked match matchall matchclose matched matches matching matchingclose matchparen math matters maven max may meaning measures media member memberranges memo memoize memory memset mentions merge merges merging message messageof messages method methodnotallowed methods methodsfrom microsoft mid middle middleware millisecond min minute missing mistake mistakes mjs mls model modify module modulemember modules monitor more most mounts move moved moves msg multiplies must mut mutable mutating my mysql na name nameat named names namespace namespaces nametok native nc nee needed needs neg negate negation negations nest nested nestedstep net network never new newer next nextfunction nextkind nextrequest nexttok nil nk nl nm no nocontent node nodecond nodes nodesteps noexcept noglob nohup none nonisolated nonnull noreturn norm normalizephp not note noteerrors notes notfound nothing notimplemented notnull noun nsg nslog null nullptr num number numbers numeric nx obj objclose object objectkeys objects objopen of off offsets og ok old older on once one oneline onevalue online only onshelf op open opened openers opens openssl operator operators ops opt optimizes option options opts or order ordered original orjsonresponse other others otherwise otherwiseline out outer outes output outputs outputwords outside over overdue override own owner pa package packages packs page paid pair paired panic para paragraph param parameter parameters params paramsclose paramsof paramsopen paramtext paren parent parentheses parentof parse parseexpr parseparams parsestatement part partly parts partsof pass passedto passes password past pat patch path pats pattern patterns pauses payload payloadtoolarge payloadwords payment paymentrequired pclose pending per perror person pester pg pgsql php phphashcomments pick picks pieces pings pipe pipeline pipelines pipelinesteps pl place placeholder plain plainenums plainname plaintextresponse plan playbook plumber plumbing plural pode pointer points pop popd popen port pos position positional positions possessivewords post postgresql power powershell powershellreading pre pred prefix prefixof prepared prepares preprocessor prev previous principal print printed printf printftext println prints prisma private procedures process processes prog program programs progress project prompt prop properties props protected protects protocol prototype ps pscommandpath psitem psscriptroot psthings ptr public publishes punc punct purges purrr push pushd put puts pv pw pwd py pybalanced pydocstring pyheader python qualifier query question questions queue quick quietly quote quoted quotedbody quotes raise raiserror raises random range ranges rangewords rare rasg rather raw rawt rawv rds re react read readable readableshare reader reading readinglanguage readkotlinif readonly reads ready real rearranges reason reasons receives recognize recognizes reconfigure record records redirect redirectof redirecttarget redirs redirwords redis redo redoes reduce references regexp register registers registration registry release releases reloads relying remainder remembering remembers remote remove removed removes renames renews repairs repeat repeated repeating repeats repl replace replaced replaces replays replof reply reports repositories repository representation req request requestidioms requests require required requirement requirenamespace requirenotnull requires res rescue resets reshapes resizes resource resources resp responds response responseentity responseof responsewriter rest restarts restate restated restates restore restores result results resumes ret retention retry return returned returns returnstep reverse revoke revokes rg rhs right ro role rollback rolling rolls rotates round roup route routefor router routeres routes routine row rows rq rr rreading rruu rscript rthings rtype ruby rule rules run running runs rust rv rw rwords safe safely said same sametype sapply save saved saves saving say sayarithmetic sayatom sayatomwords saycall saychain sayclibrary saycodecondition saycommand saycommon sayexactly saylibrarycall saylogic saynativeshape saynode saypython says sayvalue saywhether sayword scala scalar scale scales scaling scheduled scoped scopes scrambled scrambles screen script scriptparams scriptpath search searches second secret secrets sections security see seed seeing sees seg select selectcasesays selector self semi semicolons send sending sends sent sentence sentstep separate seq sequelize server serverrequest service servicebus services serviceunavailable servlet session set setclass setgeneric setmethod setopt setotherwise setpair setrefclass sets setting settings setup setvalidity several sh shape shapes share shares shebang shelf shell shellcheck shellreading shellwordsof shift short shortcut should show showing shown shows side sig sign signal signals signature signed signing signs sigs sil simple simplesays simplesaysinner single size sizeof skip skipbalanced skipparens skipped skips skipstring slash slice slots sm small smallest sn snprintf sns so some something sort sorts source sp space spaces span spanof special specify spelled spells splat splice split splitcomma splitlogic splits splitshift splitstatements splittop splittopargs spread sql sqlcondition sqllogicname sqltextwords sqs src ss ssh st stack stage standard start startat starting startline starts startswith startvalue state stateful statement statementexpr statements static status statusof stay stays std stderr step steps stepsfrom stepsin stepsofbody still stmts stmtstart stop stopf stopifnot stopped stops storage stored stores str strcasecmp strcmp strictmode string stringify strings stringtext strip stripe stripquotedtext striprubystrings striptail strlen strtext struct structs structure style sub subj subject subjectnames submits submodules subscript subscription subshell subtracts success such sudo suffix sui suite summary sums super supports suppress suppressmessages sv swaps swift swiftcondition swifthead swifttextwithvalues switch switches switchstep symbol synchronized syncs syntax system systems table tables tag tags tail taken takes tal target targetwords task teardown tee tells template templates term terminal terms ternary terraform test tests testthat testwords text textof texts than that the their theirs them then thenpart thensays thento thentoks there these they thing things this those thread throttle throw throws thunder tied time timeout timeoutexception times tnr to today together tok token tokens toks tokscode told tolowercase too tool tools toomanyrequests top toplevel toplevelindex topsteps tostderr total tothundercondition tothunderoutcome touppercase tr traces trail trailing transaction trap traps treats tree tried tries triggers trim triple true truncate try trycatch trystep ts tsql tuple turn turned turns tv tx txt ty type typealias typed typedef typeof types typescript typeset ui un unauthorized unavailable unblocks unchanged unchecked undefined under underneath understood undoes undone uninstalls union unique unknowncommand unless unlocks unmarks unmounts unpacks unprocessable unprocessableentity unprotects unq unquote unquoted unread unregisters unsafe unsaved unset unsetopt unshift unsigned unsupported until unused up update updates upgrades uploads upper url usage use usecallback used useeffectevent useevent usememo user users uses using usual uullff val valid vals value valuechoice valued valuelogic valueof valueofblock values valuewords vapor vapply var variable variables vars varwords vault vec vector ver verb verbstep version versions very via view views vim virtual visible visit vnet void volatile volume vt vtoks wait waitfor waiting waits walk walking wantfail warning warns was watches way weak web webrequest well wget wh what when whenever where whereof wherever whether which whichever while whitespace who whole wholecallargs wholevaluecall whose whosefrom widths willset with withcallinghandlers withinwindow without withoutsinglequoted word words wordsplain work worked workflow workloads works workspace would wrapped wraps write writes written wrong ws wur xdescribe xml xs xtest xx yaml yes yesno yet yield yields you za zero zeros zsh".split(' '));
|
package/src/index.d.ts
CHANGED
|
@@ -705,7 +705,13 @@ export function toCSharp(ast: IntentAst): string;
|
|
|
705
705
|
export function toJava(ast: IntentAst): string;
|
|
706
706
|
export function toPython(ast: IntentAst): string;
|
|
707
707
|
export const GENERATORS: Record<string, (ast: IntentAst) => string>;
|
|
708
|
-
|
|
708
|
+
/** Generated code plus one IL-GEN-001 error per rule condition the target could not translate (that rule throws). */
|
|
709
|
+
export function generateWithDiagnostics(ast: IntentAst, target: string): { code: string; diagnostics: import('./target-result.mjs').GenerationDiagnostic[] };
|
|
710
|
+
export { GEN_UNTRANSLATED, ERROR_KINDS, isCaseResult, untranslatedMessage } from './target-result.mjs';
|
|
711
|
+
export type { CaseResult, TargetRun, TargetErrorKind, GenerationDiagnostic } from './target-result.mjs';
|
|
712
|
+
export { parseMoney, formatMoney, roundHalfUp, minorUnitsFor, moneyTypeMinorUnits, MoneyError, MONEY_DEFAULT_MINOR_UNITS } from './money.mjs';
|
|
713
|
+
/** `money` maps Money input names to minor units; their comparisons render exactly, other uses throw. */
|
|
714
|
+
export function exprToJs(src: string, opts?: { inputs?: string[]; money?: Record<string, number> }): string;
|
|
709
715
|
export function subjectName(ast: IntentAst): string | null;
|
|
710
716
|
export function intentRefId(astOrName: IntentAst | string, opts?: { sourceHash?: string }): string;
|
|
711
717
|
|
|
@@ -743,6 +749,7 @@ export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText }
|
|
|
743
749
|
export { thunderizeFiles, THUNDER_TEXT_EXT } from './thunderize.mjs';
|
|
744
750
|
export { sameMeaning, renderSame } from './same.mjs';
|
|
745
751
|
export { thunderReview, renderReview, REVIEW_SCHEMA } from './review.mjs';
|
|
752
|
+
export { renderReviewComment, reviewCounts } from './review-comment.mjs';
|
|
746
753
|
export { EXPR_SCHEMA, parseStatement, renderStatement, sayFull, detailOf, sameExpr } from './meaning.mjs';
|
|
747
754
|
export type { Expr } from './meaning.mjs';
|
|
748
755
|
export { stepRoundTrip, runBehavior, ROUND_TRIP_LANGUAGES } from './round-trip.mjs';
|
package/src/index.mjs
CHANGED
|
@@ -115,7 +115,10 @@ export { FOCUS_SCHEMA, SCOPE_TYPES, FOCUS_REASONS, makeScope, buildFocusGraph, i
|
|
|
115
115
|
// Comprehension Contract , the C0..C7 understanding level (intent-comprehension-v1)
|
|
116
116
|
export { COMPREHENSION_SCHEMA, LEVELS as COMPREHENSION_LEVELS, comprehensionLevel, comprehensionReport } from './comprehension.mjs';
|
|
117
117
|
// Code generation , deterministic scaffolds from intent (intent-codegen-v1)
|
|
118
|
-
export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython } from './codegen.mjs';
|
|
118
|
+
export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython, generateWithDiagnostics } from './codegen.mjs';
|
|
119
|
+
// Honest generation and run results (IL-GEN-001, structured case results) and exact Thunder Money
|
|
120
|
+
export { GEN_UNTRANSLATED, ERROR_KINDS, isCaseResult, untranslatedMessage } from './target-result.mjs';
|
|
121
|
+
export { parseMoney, formatMoney, roundHalfUp, minorUnitsFor, moneyTypeMinorUnits, MoneyError, MONEY_DEFAULT_MINOR_UNITS } from './money.mjs';
|
|
119
122
|
// Change Lens , what a branch/PR changed by meaning (intent-changes-v1)
|
|
120
123
|
export { CHANGES_SCHEMA, changeReport } from './changes.mjs';
|
|
121
124
|
export { exprToJs, exprToCSharp, exprToJava, exprToCode } from './expr.mjs';
|
|
@@ -194,6 +197,7 @@ export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText }
|
|
|
194
197
|
export { thunderizeFiles, THUNDER_TEXT_EXT } from "./thunderize.mjs";
|
|
195
198
|
export { sameMeaning, renderSame } from "./same.mjs";
|
|
196
199
|
export { thunderReview, renderReview, REVIEW_SCHEMA } from "./review.mjs";
|
|
200
|
+
export { renderReviewComment, reviewCounts } from "./review-comment.mjs";
|
|
197
201
|
// Every step's meaning tree, and code → Thunder → code for steps.
|
|
198
202
|
export { EXPR_SCHEMA, parseStatement, renderStatement, sayFull, detailOf, sameExpr } from "./meaning.mjs";
|
|
199
203
|
export { stepRoundTrip, runBehavior, ROUND_TRIP_LANGUAGES } from "./round-trip.mjs";
|
package/src/intent-schema.mjs
CHANGED
|
@@ -133,6 +133,7 @@ const IL_AUTHOR_RULE_ROWS = [
|
|
|
133
133
|
{ ruleId: 'IL-SEC-001', area: 'security', severity: 'blocker', blocks: ['release'], summary: 'Secret-typed field travels over the event bus.' },
|
|
134
134
|
{ ruleId: 'IL-SEC-002', area: 'security', severity: 'blocker', blocks: ['release'], summary: 'API returns a secret with no auth requirement.' },
|
|
135
135
|
{ ruleId: 'IL-TYPE-001', area: 'type', severity: 'info', blocks: [], summary: 'Field uses an unrecognized (likely mistyped) type.' },
|
|
136
|
+
{ ruleId: 'IL-GEN-001', area: 'generation', severity: 'error', blocks: ['implementation'], summary: 'A rule condition could not be translated for a target: generation reports it, the generated rule throws, and live runs report it not translated (never a stand-in false).' },
|
|
136
137
|
// 12-Factor Agents conformance (twelve-factor-v1). Advisory: an intent's alignment with the
|
|
137
138
|
// humanlayer/12-factor-agents principles. `thunder twelve-factor` scores these.
|
|
138
139
|
{ ruleId: 'IL-12F-01', area: 'twelve-factor', severity: 'info', blocks: [], summary: 'F1 Natural language to tool calls: model dispatch as a decision/command.' },
|
package/src/learn-lessons.mjs
CHANGED
|
@@ -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
|
};
|