@skillstech/thunderlang 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/dist/core.cjs +13779 -10043
  3. package/dist/index.cjs +28500 -24392
  4. package/dist/learn.cjs +12853 -9579
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/libraries.mjs +2 -2
  33. package/src/mcp.mjs +23 -0
  34. package/src/meaning.mjs +47 -7
  35. package/src/model.d.mts +7 -3
  36. package/src/model.mjs +30 -9
  37. package/src/money.d.mts +18 -0
  38. package/src/money.mjs +124 -0
  39. package/src/plain-contract.mjs +18 -2
  40. package/src/powershell.mjs +24 -5
  41. package/src/read-repo.mjs +1 -0
  42. package/src/read.d.mts +11 -0
  43. package/src/read.mjs +121 -13
  44. package/src/review-comment.d.mts +16 -0
  45. package/src/review-comment.mjs +145 -0
  46. package/src/rlang.mjs +10 -3
  47. package/src/say-less.mjs +1432 -0
  48. package/src/shell.mjs +45 -8
  49. package/src/sql-proc.mjs +1198 -0
  50. package/src/sql.mjs +87 -119
  51. package/src/steps.mjs +188 -37
  52. package/src/system.mjs +153 -44
  53. package/src/target-cs.mjs +39 -34
  54. package/src/target-elixir.mjs +40 -30
  55. package/src/target-go.mjs +41 -36
  56. package/src/target-java.mjs +34 -27
  57. package/src/target-kotlin.mjs +43 -35
  58. package/src/target-py.mjs +57 -55
  59. package/src/target-result.d.mts +48 -0
  60. package/src/target-result.mjs +112 -0
  61. package/src/target-rust.mjs +42 -38
  62. package/src/target-scala.mjs +45 -35
  63. package/src/target-ts.mjs +37 -45
  64. package/src/target-types.mjs +41 -5
  65. package/src/target-util.mjs +55 -2
  66. package/src/trace-cli.mjs +58 -0
  67. package/src/trace-fs.mjs +76 -0
  68. package/src/trace.mjs +261 -0
  69. package/src/translate.d.mts +3 -0
  70. package/src/translate.mjs +62 -32
  71. package/src/why-cli.mjs +31 -0
  72. package/src/why.d.mts +28 -0
  73. package/src/why.mjs +532 -0
  74. package/src/write-steps.mjs +22 -5
@@ -0,0 +1,486 @@
1
+ // Thunder Core -> Python 3.10+.
2
+ //
3
+ // The generated code is meant to be read and used without Thunder: plain functions, dataclasses, and a small
4
+ // runtime file (thunder_runtime.py) that is written next to it. Every generated statement ends with
5
+ // `# thunder:N`, the line of the .thunder file it came from; the runtime uses those comments to report errors
6
+ // against Thunder lines.
7
+
8
+ const P = { or: 1, and: 2, not: 3, cmp: 4, add: 5, mul: 6, unary: 7, atom: 9 };
9
+ const wrap = (x, min) => (x.p < min ? `(${x.c})` : x.c);
10
+ const py = (s) => JSON.stringify(s); // a valid Python string literal for any text
11
+
12
+ export function percentDecimal(text) {
13
+ const [i, f = ''] = text.split('.');
14
+ const digits = (i + f).replace(/^0+(?=\d)/, '');
15
+ const pos = digits.length - f.length - 2;
16
+ if (pos <= 0) return `0.${'0'.repeat(-pos)}${digits}`;
17
+ return `${digits.slice(0, pos)}.${digits.slice(pos)}`;
18
+ }
19
+
20
+ const pyType = (t) => {
21
+ if (!t) return 'object';
22
+ switch (t.k) {
23
+ case 'whole': return 'int';
24
+ case 'number': return 'Decimal';
25
+ case 'money': return 'Money';
26
+ case 'text': return 'str';
27
+ case 'bool': return 'bool';
28
+ case 'date': return 'date';
29
+ case 'list': return 'list';
30
+ case 'map': return 'dict';
31
+ case 'record': return py(t.py ?? 'object');
32
+ case 'optional': { const inner = pyType(t.of); return inner.startsWith('"') ? `${inner.slice(0, -1)} | None"` : `${inner} | None`; }
33
+ default: return 'object';
34
+ }
35
+ };
36
+
37
+ const singular = (n) => (n.endsWith('ies') ? `${n.slice(0, -3)}y` : n.endsWith('ses') || n.endsWith('xes') ? n.slice(0, -2) : n.endsWith('s') && !n.endsWith('ss') ? n.slice(0, -1) : null);
38
+
39
+ export function toPython(program, info, { source = 'main.thunder', imports = [] } = {}) {
40
+ const g = new Gen(program, info, source);
41
+ return g.module(imports);
42
+ }
43
+
44
+ class Gen {
45
+ constructor(program, info, source) {
46
+ this.p = program; this.info = info; this.source = source;
47
+ this.out = []; this.ind = 0;
48
+ this.rt = new Set(['run']); this.needDecimal = false; this.needDate = false; this.needDataclass = false;
49
+ this.usedPy = new Set();
50
+ }
51
+ emit(text, line) { this.out.push(`${' '.repeat(this.ind)}${text}${line ? ` # thunder:${line}` : ''}`); }
52
+ blank() { while (this.out.length && this.out.slice(-2).join('|') !== '|') this.out.push(''); }
53
+ R(name) { this.rt.add(name); return name; }
54
+
55
+ module(srcModules) {
56
+ const body = [];
57
+ const top = this.p.body;
58
+ const own = (s) => !this.info.imported?.has(s);
59
+ // Records, functions, kept values, tests, main.
60
+ for (const r of this.info.records.filter(own)) { this.blank(); this.record(r); }
61
+ for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
62
+ const consts = this.info.consts.filter(own);
63
+ if (consts.length) { this.blank(); for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line); }
64
+ const tests = this.info.tests;
65
+ for (const t of tests) {
66
+ this.blank();
67
+ this.emit(`def ${t.py}():`, t.line);
68
+ this.ind++; this.block(t.body); this.ind--;
69
+ }
70
+ if (tests.length) {
71
+ this.blank();
72
+ this.emit('THUNDER_TESTS = [');
73
+ for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
74
+ this.emit(']');
75
+ }
76
+ const main = this.p.main ?? [];
77
+ this.blank();
78
+ if (main.length) {
79
+ this.emit('def main():');
80
+ this.ind++; this.block(main); this.ind--;
81
+ this.blank();
82
+ this.emit('if __name__ == "__main__":');
83
+ this.emit(` ${this.R('run')}(main, __file__)`);
84
+ }
85
+ body.push(...this.out);
86
+
87
+ const head = [
88
+ `# Generated by the Thunder compiler from ${this.source}.`,
89
+ `# This file is a build artifact: change ${this.source.split('/').pop()} and build again, or keep this file and edit it as Python.`,
90
+ '# It needs only Python 3.10+ and thunder_runtime.py (written next to it). "# thunder:N" marks the Thunder line.',
91
+ '',
92
+ ];
93
+ if (this.needDataclass) head.push('from dataclasses import dataclass, field');
94
+ if (this.needDate) head.push('from datetime import date');
95
+ if (this.needDecimal) head.push('from decimal import Decimal');
96
+ for (const m of this.info.modules.filter(own)) head.push(m.module === m.py || (m.module.split('.')[0] === m.py && !m.module.includes('.')) ? `import ${m.module}` : `import ${m.module} as ${m.py}`);
97
+ head.push(`from thunder_runtime import ${[...this.rt].sort().join(', ')}`);
98
+ for (const m of srcModules) head.push(`from ${m} import *`);
99
+ head.push('', `THUNDER_SOURCE = ${py(this.source)}`, '', '');
100
+ return `${head.join('\n')}\n${body.join('\n').replace(/\n{4,}/g, '\n\n\n')}\n`;
101
+ }
102
+
103
+ record(r) {
104
+ this.needDataclass = true;
105
+ this.emit('@dataclass(kw_only=True)', r.line);
106
+ this.emit(`class ${r.py}:`, r.line);
107
+ this.ind++;
108
+ // Fields that may be left out come with a default (nothing, or an empty list or map).
109
+ for (const f of r.fields) {
110
+ const t = pyType(f.type);
111
+ if (t === 'Decimal') this.needDecimal = true;
112
+ if (t === 'Money') this.R('Money');
113
+ if (t === 'date') this.needDate = true;
114
+ const dflt = f.type.k === 'optional' ? ' = None' : f.type.k === 'list' ? ' = field(default_factory=list)' : f.type.k === 'map' ? ' = field(default_factory=dict)' : '';
115
+ this.emit(`${f.py}: ${t}${dflt}`, f.line);
116
+ }
117
+ if (!r.fields.length) this.emit('pass');
118
+ const rules = r.rulesToCheck ?? [];
119
+ if (rules.length) {
120
+ this.out.push('');
121
+ this.emit('def __setattr__(self, name, value):', rules[0].line);
122
+ this.ind++;
123
+ const bySubject = new Map();
124
+ for (const rule of rules) { const f = r.fieldMap.get(rule.subject); (bySubject.get(f.py) ?? bySubject.set(f.py, []).get(f.py)).push(rule); }
125
+ for (const [field, rs] of bySubject) {
126
+ this.emit(`if name == ${py(field)}:`);
127
+ this.ind++;
128
+ for (const rule of rs) this.emit(`${this.R('never')}(${this.x(rule.rule.cond, { subject: 'value' }).c}, ${py(rule.text)}, rule=${rule.line}, value=value)`, rule.line);
129
+ this.ind--;
130
+ }
131
+ this.emit('super().__setattr__(name, value)');
132
+ this.ind--;
133
+ }
134
+ this.ind--;
135
+ }
136
+
137
+ func(f) {
138
+ // A default: a fixed value in the signature; a kept value is filled in when the function is called (it may be
139
+ // written further down the file, and a kept value never changes, so this means the same).
140
+ const late = f.params.filter((p) => p.dflt?.k === 'name');
141
+ this.emit(`def ${f.py}(${f.params.map((p) => (p.dflt ? `${p.py}=${p.dflt.k === 'name' ? `${this.R('NOT_GIVEN')}` : this.x(p.dflt).c}` : p.py)).join(', ')}):`, f.line);
142
+ for (const p of late) this.emit(` if ${p.py} is ${this.R('NOT_GIVEN')}:\n ${p.py} = ${this.x(p.dflt).c}`, p.line);
143
+ this.ind++;
144
+ for (const p of f.params) for (const rule of p.rules ?? []) this.emit(`${this.R('never')}(${this.x(rule.rule.cond, { subject: p.py }).c}, ${py(rule.text)}, rule=${rule.line}, value=${p.py})`, p.line);
145
+ this.block(f.body);
146
+ this.ind--;
147
+ }
148
+
149
+ block(body) {
150
+ if (!body.length) { this.emit('pass'); return; }
151
+ for (const s of body) this.stmt(s);
152
+ }
153
+
154
+ // A name watched by a Never rule gets its new value checked before it is stored, so a refused change
155
+ // leaves the old value in place.
156
+ assign(s, name, value) {
157
+ if (!s.rules?.length) { this.emit(`${name} = ${value}`, s.line); return; }
158
+ const tmp = `new_${name}`;
159
+ this.emit(`${tmp} = ${value}`, s.line);
160
+ this.rulesAfter(s, tmp);
161
+ this.emit(`${name} = ${tmp}`, s.line);
162
+ }
163
+
164
+ rulesAfter(s, targetPy) {
165
+ for (const rule of s.rules ?? []) this.emit(`${this.R('never')}(${this.x(rule.rule.cond, { subject: targetPy }).c}, ${py(rule.text)}, rule=${rule.line}, value=${targetPy})`, s.line);
166
+ }
167
+
168
+ /** Store a value into a name, a field, or an entry (a list position from 1, or a map key). */
169
+ store(t, v, L) {
170
+ if (t.k === 'name') { this.emit(`${t.ref?.py ?? 'unknown'} = ${v}`, L); return; }
171
+ if (t.k === 'field') {
172
+ if (t.static) this.emit(`${wrap(this.x(t.obj), P.atom)}.${t.py} = ${v}`, L);
173
+ else this.emit(`${this.R('set_field')}(${this.x(t.obj).c}, ${py(t.text)}, ${v})`, L);
174
+ return;
175
+ }
176
+ if (t.k === 'at') {
177
+ if (t.objKind === 'list') this.emit(`${this.R('set_item')}(${this.x(t.obj).c}, ${this.x(t.key).c}, ${v})`, L);
178
+ else if (t.objKind === 'map') this.emit(`${wrap(this.x(t.obj), P.atom)}[${this.x(t.key).c}] = ${v}`, L);
179
+ else this.emit(`${this.R('set_entry')}(${this.x(t.obj).c}, ${this.x(t.key).c}, ${v})`, L);
180
+ }
181
+ }
182
+
183
+ lv(e) {
184
+ if (e.k === 'name') return e.ref?.py ?? 'unknown';
185
+ return this.x(e).c;
186
+ }
187
+
188
+ stmt(s) {
189
+ const L = s.line;
190
+ switch (s.k) {
191
+ case 'say': {
192
+ const v = this.x(s.e);
193
+ this.emit(`print(${s.e.type?.k === 'text' ? v.c : `${this.R('show')}(${v.c})`})`, L);
194
+ return;
195
+ }
196
+ case 'set': {
197
+ const t = s.target;
198
+ const v = this.x(s.e).c;
199
+ if (t.k === 'name') { this.assign(s, t.ref.py, v); return; }
200
+ if (t.k === 'field') {
201
+ if (t.static) this.emit(`${wrap(this.x(t.obj), P.atom)}.${t.py} = ${v}`, L);
202
+ else this.emit(`${this.R('set_field')}(${this.x(t.obj).c}, ${py(t.text)}, ${v})`, L);
203
+ return;
204
+ }
205
+ this.store(t, v, L);
206
+ return;
207
+ }
208
+ case 'give': this.emit(s.e.k === 'nothing' ? 'return None' : `return ${this.x(s.e).c}`, L); return;
209
+ case 'stop': this.emit(`raise ${this.R('Stop')}(${s.e.type?.k === 'text' ? this.x(s.e).c : `${this.R('show')}(${this.x(s.e).c})`})`, L); return;
210
+ case 'if':
211
+ s.branches.forEach((b, k) => {
212
+ this.emit(`${k === 0 ? 'if' : 'elif'} ${this.yn(b.cond).c}:`, b.line);
213
+ this.ind++; this.block(b.body); this.ind--;
214
+ });
215
+ if (s.otherwise) { this.emit('else:'); this.ind++; this.block(s.otherwise); this.ind--; }
216
+ return;
217
+ case 'each': {
218
+ const it = this.x(s.iter).c;
219
+ const [a, b] = s.vars;
220
+ if (b) this.emit(`for ${a.py}, ${b.py} in ${s.iterKind === 'map' ? `${wrap(this.x(s.iter), P.atom)}.items()` : s.iterKind === 'pairs' ? it : `${this.R('pairs_of')}(${it})`}:`, L);
221
+ else this.emit(`for ${a.py} in ${it}:`, L);
222
+ this.ind++; this.block(s.body); this.ind--;
223
+ return;
224
+ }
225
+ case 'range': {
226
+ const to = s.to.k === 'num' && s.to.whole ? String(Number(s.to.text) + 1) : `${wrap(this.x(s.to), P.add)} + 1`;
227
+ this.emit(`for ${s.v.py} in range(${this.x(s.from).c}, ${to}):`, L);
228
+ this.ind++; this.block(s.body); this.ind--;
229
+ return;
230
+ }
231
+ case 'while':
232
+ this.emit(`while ${s.until ? `not ${wrap(this.yn(s.cond), P.not)}` : this.yn(s.cond).c}:`, L);
233
+ this.ind++; this.block(s.body); this.ind--;
234
+ return;
235
+ case 'times':
236
+ this.emit(`for _ in range(${this.x(s.count).c}):`, L);
237
+ this.ind++; this.block(s.body); this.ind--;
238
+ return;
239
+ case 'expect': return this.expect(s);
240
+ case 'add': case 'remove': {
241
+ const v = this.x(s.e).c;
242
+ const target = this.lv(s.target);
243
+ if (s.targetKind === 'list') this.emit(s.k === 'add' ? `${target}.append(${v})` : `${this.R('remove_from')}(${target}, ${v})`, L);
244
+ else if (s.targetKind === 'map') this.emit(`${this.R('remove_from')}(${target}, ${v})`, L);
245
+ else if (s.targetKind === 'number') { if (s.target.k === 'name' && s.rules?.length) { this.assign(s, target, `${target} ${s.k === 'add' ? '+' : '-'} ${v}`); return; } this.emit(`${target} ${s.k === 'add' ? '+' : '-'}= ${v}`, L); }
246
+ else if (s.k === 'add') { if (s.target.k === 'name') this.emit(`${target} = ${this.R('add_to')}(${target}, ${v})`, L); else this.store(s.target, `${this.R('add_to')}(${target}, ${v})`, L); }
247
+ else this.emit(`${this.R('remove_from')}(${target}, ${v})`, L);
248
+ if (s.target.k === 'name') this.rulesAfter(s, target);
249
+ return;
250
+ }
251
+ case 'increase': case 'decrease': {
252
+ const target = this.lv(s.target);
253
+ if (s.target.k === 'name' && s.rules?.length) { this.assign(s, target, `${target} ${s.k === 'increase' ? '+' : '-'} ${wrap(this.x(s.e), P.add + 1)}`); return; }
254
+ if (s.target.k === 'name') { this.emit(`${target} ${s.k === 'increase' ? '+' : '-'}= ${this.x(s.e).c}`, L); return; }
255
+ // A field or an entry: read it, then store the new value (a dynamic field cannot be written with +=).
256
+ this.store(s.target, `${wrap(this.numv(s.target, { c: target, p: P.atom }), P.add)} ${s.k === 'increase' ? '+' : '-'} ${wrap(this.numv(s.e, this.x(s.e)), P.add + 1)}`, L);
257
+ return;
258
+ }
259
+ case 'sort': {
260
+ const target = this.x(s.target);
261
+ const key = s.field ? this.keyLambda(s.field) : null;
262
+ const args = [key ? `key=${key}` : null, s.desc ? 'reverse=True' : null].filter(Boolean).join(', ');
263
+ this.emit(`${wrap(target, P.atom)}.sort(${args})`, L);
264
+ return;
265
+ }
266
+ case 'reverse': this.emit(`${wrap(this.x(s.target), P.atom)}.reverse()`, L); return;
267
+ case 'do': this.emit(this.x(s.e).c, L); return;
268
+ case 'tryFail':
269
+ this.emit('try:', L);
270
+ this.ind++; this.stmt(s.stmt); this.ind--;
271
+ this.emit('except Exception as failure:', L);
272
+ this.ind++;
273
+ this.emit(`${s.errPy} = ${this.R('explain')}(failure)`, L);
274
+ this.block(s.handler);
275
+ this.ind--;
276
+ return;
277
+ default: this.emit(`pass # not generated: ${s.k}`, L);
278
+ }
279
+ }
280
+
281
+ expect(s) {
282
+ const L = s.line;
283
+ const text = py((s.raw ?? 'Expect').trim());
284
+ if (s.mode === 'true') { this.emit(`${this.R('expect_true')}(${this.x(s.e).c}, ${text})`, L); return; }
285
+ if (s.mode === 'fail') {
286
+ this.emit(`with ${this.R('expect_failure')}(${text}${s.msg ? `, ${this.x(s.msg).c}` : ''}):`, L);
287
+ this.ind++; this.emit(this.x(s.e).c, L); this.ind--;
288
+ return;
289
+ }
290
+ const actual = this.x(s.e).c;
291
+ if (s.mode === 'cmp') { this.emit(`${this.R('expect_value')}(${actual}, "contains", ${this.x(s.want).c}, ${text})`, L); return; }
292
+ let c = s.check, neg = '';
293
+ if (c.k === 'not') { neg = 'not '; c = c.e; }
294
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
295
+ let op, want = 'None';
296
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r).c; }
297
+ else if (c.k === 'adj') op = c.adj;
298
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
299
+ else if (c.k === 'between') { op = 'between'; want = `(${this.x(c.lo).c}, ${this.x(c.hi).c})`; }
300
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l).c; }
301
+ else op = 'is';
302
+ this.emit(`${this.R('expect_value')}(${actual}, ${py(neg + op)}, ${want}, ${text})`, L);
303
+ }
304
+
305
+ // A name for the item in a list comprehension: the singular of the list's name when it is free, else "item".
306
+ itemVar(listExpr) {
307
+ const base = listExpr.k === 'name' && listExpr.ref?.py ? singular(listExpr.ref.py) : null;
308
+ const taken = (n) => !n || this.isTaken(n);
309
+ let n = !taken(base) ? base : 'item';
310
+ let k = 2;
311
+ while (this.isTaken(n)) n = `item${k++}`;
312
+ return n;
313
+ }
314
+ isTaken(n) {
315
+ if (this.stack?.includes(n)) return true;
316
+ if (!this.allPy) {
317
+ this.allPy = new Set();
318
+ const add = (s) => { if (s?.py) this.allPy.add(s.py); };
319
+ const visit = (body) => { for (const s of body ?? []) { if (s.k === 'set' && s.target.ref) this.allPy.add(s.target.ref.py); (s.vars ?? []).forEach(add); add(s.v); if (s.errPy) this.allPy.add(s.errPy); visit(s.body); visit(s.handler); visit(s.otherwise); (s.branches ?? []).forEach((b) => visit(b.body)); if (s.stmt) visit([s.stmt]); } };
320
+ for (const f of this.info.funcs) { add(f); f.params.forEach(add); visit(f.body); }
321
+ for (const r of this.info.records) add(r);
322
+ for (const c of this.info.consts) add(c);
323
+ for (const m of this.info.modules) add(m);
324
+ visit(this.p.main); for (const t of this.info.tests) visit(t.body);
325
+ }
326
+ return this.allPy.has(n);
327
+ }
328
+
329
+ keyLambda(field, v = 'item') {
330
+ if (field.dynamic) return `lambda ${v}: ${this.R('get_field')}(${v}, ${py(field.key)})`;
331
+ return `lambda ${v}: ${v}.${field.py}`;
332
+ }
333
+
334
+ fieldOf(v, field) { return field.dynamic ? `${this.R('get_field')}(${v}, ${py(field.key)})` : `${v}.${field.py}`; }
335
+
336
+ // ------------------------------------------------------------ expressions
337
+ /** A value whose kind is not known in advance, used in arithmetic or a comparison: a Python float becomes exact. */
338
+ numv(e, c) {
339
+ return ['whole', 'number', 'money', 'text', 'bool', 'list', 'map', 'record', 'date'].includes(e.type?.k) ? c : { c: `${this.R('num')}(${c.c})`, p: P.atom };
340
+ }
341
+
342
+ /** A value used as yes/no: checked at run time unless it is known to be yes/no (never Python's "truthy"). */
343
+ yn(e, ctx = {}) {
344
+ const c = this.x(e, ctx);
345
+ const known = e.type?.k === 'bool' || ['cmp', 'contains', 'between', 'adj', 'isNothing', 'not', 'bool'].includes(e.k) || (e.k === 'bin' && (e.op === 'and' || e.op === 'or'));
346
+ return known ? c : { c: `${this.R('yes_no')}(${c.c})`, p: P.atom };
347
+ }
348
+
349
+ x(e, ctx = {}) {
350
+ const A = (c) => ({ c, p: P.atom });
351
+ const sub = (k) => this.x(k, ctx);
352
+ switch (e.k) {
353
+ case 'num': if (e.whole) return A(e.text); this.needDecimal = true; return A(`Decimal(${py(e.text)})`);
354
+ case 'money': return A(`${this.R('Money')}(${py(e.text)})`);
355
+ case 'percent': this.needDecimal = true; return A(`Decimal(${py(percentDecimal(e.text))})`);
356
+ case 'bool': return A(e.v ? 'True' : 'False');
357
+ case 'nothing': return A('None');
358
+ case 'paren': return sub(e.e);
359
+ case 'today': this.needDate = true; return A('date.today()');
360
+ case 'date': this.needDate = true; return A(`date.fromisoformat(${py(e.text)})`);
361
+ case 'str': return A(this.str(e, ctx));
362
+ case 'list': return A(e.items ? `[${e.items.map((i) => sub(i).c).join(', ')}]` : '{}');
363
+ case 'map': return A('{}');
364
+ case 'name': {
365
+ const r = e.ref ?? {};
366
+ if (r.kind === 'subject') return A(ctx.subject ?? 'value');
367
+ if (r.kind === 'elemField') return A(`${ctx.item}.${r.py}`);
368
+ if (r.kind === 'elemKey') return A(`${this.R('get_field')}(${ctx.item}, ${py(r.key)})`);
369
+ if (r.kind === 'elem') return A(ctx.item);
370
+ return A(r.py ?? e.name.replace(/ /g, '_'));
371
+ }
372
+ case 'call': return A(`${e.py}(${e.args.map((a) => sub(a).c).join(', ')})`);
373
+ case 'new': return A(`${e.py}(${e.fields.map((f) => `${f.py}=${sub(f.e).c}`).join(', ')})`);
374
+ case 'field': return e.static ? A(`${wrap(sub(e.obj), P.atom)}.${e.py}`) : A(`${this.R('get_field')}(${sub(e.obj).c}, ${py(e.text)})`);
375
+ case 'at': {
376
+ const o = sub(e.obj), k = sub(e.key);
377
+ if (e.objKind === 'map') return A(e.dflt ? `${wrap(o, P.atom)}.get(${k.c}, ${sub(e.dflt).c})` : `${wrap(o, P.atom)}[${k.c}]`);
378
+ if (e.objKind === 'list') return A(`${this.R('item_at')}(${o.c}, ${k.c}${e.dflt ? `, ${sub(e.dflt).c}` : ''})`);
379
+ return A(`${this.R('entry')}(${o.c}, ${k.c}${e.dflt ? `, ${sub(e.dflt).c}` : ''})`);
380
+ }
381
+ case 'conv': {
382
+ if (e.to === 'list') return A(`list(${sub(e.e).c})`);
383
+ const fn = { number: 'to_number', whole: 'to_whole', money: 'to_money', text: 'to_text', bool: 'to_yes_no', date: 'to_date' }[e.to];
384
+ return A(`${this.R(fn)}(${sub(e.e).c})`);
385
+ }
386
+ case 'where': {
387
+ const v = this.itemVar(e.list);
388
+ return A(`[${v} for ${v} in ${sub(e.list).c} if ${this.withItem(v, () => this.x(e.cond, { ...ctx, item: v }).c)}]`);
389
+ }
390
+ case 'from': {
391
+ const inner = e.list.k === 'where' ? e.list : null;
392
+ const listE = inner ? inner.list : e.list;
393
+ const v = this.itemVar(listE);
394
+ const cond = inner ? ` if ${this.withItem(v, () => this.x(inner.cond, { ...ctx, item: v }).c)}` : '';
395
+ return A(`[${this.fieldOf(v, e.field)} for ${v} in ${sub(listE).c}${cond}]`);
396
+ }
397
+ case 'sorted': {
398
+ const rev = e.desc ? ', reverse=True' : '';
399
+ if (e.mapSort) return A(`sorted(${wrap(sub(e.list), P.atom)}.items(), key=lambda entry: entry[${e.by === 'key' ? 0 : 1}]${rev})`);
400
+ const v = this.itemVar(e.list);
401
+ return A(`sorted(${sub(e.list).c}, key=${this.keyLambda(e.field, v)}${rev})`);
402
+ }
403
+ case 'dot': return A(`${wrap(sub(e.obj), P.atom)}.${e.attr}${e.args ? `(${e.args.map((a) => sub(a).c).join(', ')})` : ''}`);
404
+ case 'op': {
405
+ const a = sub(e.arg);
406
+ switch (e.op) {
407
+ case 'sum': return A(`${this.R('total_of')}(${a.c})`);
408
+ case 'average': return A(`${this.R('average_of')}(${a.c})`);
409
+ case 'count': case 'length': return A(`len(${a.c})`);
410
+ case 'min': return A(`${this.R('smallest_of')}(${a.c})`);
411
+ case 'max': return A(`${this.R('largest_of')}(${a.c})`);
412
+ case 'first': return A(`${this.R('first_of')}(${a.c})`);
413
+ case 'last': return A(`${this.R('last_of')}(${a.c})`);
414
+ case 'words': return A(`${this.R('words_of')}(${a.c})`);
415
+ case 'lines': return A(`${wrap(a, P.atom)}.splitlines()`);
416
+ case 'lowercase': return A(`${wrap(a, P.atom)}.lower()`);
417
+ case 'uppercase': return A(`${wrap(a, P.atom)}.upper()`);
418
+ case 'trimmed': return A(`${wrap(a, P.atom)}.strip()`);
419
+ case 'parts': return A(`${this.R('parts_of')}(${a.c})`);
420
+ case 'abs': return A(`${this.R('absolute')}(${a.c})`);
421
+ case 'jsonText': return A(`${this.R('json_text')}(${a.c})`);
422
+ case 'jsonData': return A(`${this.R('json_data')}(${a.c})`);
423
+ case 'keys': return A(`list(${wrap(a, P.atom)}.keys())`);
424
+ case 'values': return A(`list(${wrap(a, P.atom)}.values())`);
425
+ default: return A(`${e.op}(${a.c})`);
426
+ }
427
+ }
428
+ case 'round': return A(`${this.R('round_to')}(${sub(e.e).c}${e.places ? `, ${sub(e.places).c}` : ''})`);
429
+ case 'readFile': return A(`${this.R('read_file')}(${sub(e.path).c})`);
430
+ case 'neg': return { c: `-${wrap(sub(e.e), P.unary)}`, p: P.unary };
431
+ case 'not': return { c: `not ${wrap(this.yn(e.e, ctx), P.not)}`, p: P.not };
432
+ case 'bin': {
433
+ const l = sub(e.l), r = sub(e.r);
434
+ if (e.op === 'and') { const a = this.yn(e.l, ctx), b = this.yn(e.r, ctx); return { c: `${wrap(a, P.and)} and ${wrap(b, P.and + 1)}`, p: P.and }; }
435
+ if (e.op === 'or') { const a = this.yn(e.l, ctx), b = this.yn(e.r, ctx); return { c: `${wrap(a, P.or)} or ${wrap(b, P.or + 1)}`, p: P.or }; }
436
+ if (e.op === '+' || e.op === '-') { const a = this.numv(e.l, l), b = this.numv(e.r, r); return { c: `${wrap(a, P.add)} ${e.op} ${wrap(b, P.add + 1)}`, p: P.add }; }
437
+ if (e.op === '*') { const a = this.numv(e.l, l), b = this.numv(e.r, r); return { c: `${wrap(a, P.mul)} * ${wrap(b, P.mul + 1)}`, p: P.mul }; }
438
+ if (e.op === '/') return A(`${this.R('divide')}(${l.c}, ${r.c})`);
439
+ if (e.op === 'mod') {
440
+ if (e.l.type?.k === 'whole' && e.r.type?.k === 'whole') return { c: `${wrap(l, P.mul)} % ${wrap(r, P.mul + 1)}`, p: P.mul };
441
+ return A(`${this.R('modulo')}(${l.c}, ${r.c})`);
442
+ }
443
+ return A(`${e.op}(${l.c}, ${r.c})`);
444
+ }
445
+ case 'cmp': {
446
+ const l = sub(e.l), r = sub(e.r);
447
+ if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) return { c: `${wrap(this.yn(e.l, ctx), P.cmp + 1)} ${e.op === '==' ? 'is' : 'is not'} ${r.c}`, p: P.cmp };
448
+ return { c: `${wrap(this.numv(e.l, l), P.cmp + 1)} ${e.op} ${wrap(this.numv(e.r, r), P.cmp + 1)}`, p: P.cmp };
449
+ }
450
+ case 'between': return { c: `${wrap(sub(e.lo), P.cmp + 1)} <= ${wrap(sub(e.e), P.cmp + 1)} <= ${wrap(sub(e.hi), P.cmp + 1)}`, p: P.cmp };
451
+ case 'contains': return { c: `${wrap(sub(e.r), P.cmp + 1)} in ${wrap(sub(e.l), P.cmp + 1)}`, p: P.cmp };
452
+ case 'affix': return A(`${this.R(e.end ? 'ends_with' : 'starts_with')}(${sub(e.l).c}, ${sub(e.r).c})`);
453
+ case 'sortedValues': return A(`${this.R('sorted_values')}(${sub(e.list).c}${e.desc ? ', True' : ''})`);
454
+ case 'joined': return A(`${this.R('joined')}(${sub(e.list).c}, ${sub(e.sep).c})`);
455
+ case 'splitAt': return A(`${this.R('split_at')}(${sub(e.text).c}, ${sub(e.sep).c})`);
456
+ case 'replacing': return A(`${this.R('replacing')}(${sub(e.text).c}, ${sub(e.from).c}, ${sub(e.to).c})`);
457
+ case 'adj': {
458
+ const v = sub(e.e);
459
+ if (e.adj === 'empty') return { c: `len(${v.c}) == 0`, p: P.cmp };
460
+ return { c: `${wrap(v, P.cmp + 1)} ${{ positive: '>', negative: '<', zero: '==' }[e.adj]} 0`, p: P.cmp };
461
+ }
462
+ case 'isNothing': return { c: `${wrap(sub(e.e), P.cmp + 1)} ${e.neg ? 'is not' : 'is'} None`, p: P.cmp };
463
+ case 'hole': return A('None');
464
+ default: return A(`None # not generated: ${e.k}`);
465
+ }
466
+ }
467
+ withItem(v, fn) { (this.stack ??= []).push(v); try { return fn(); } finally { this.stack.pop(); } }
468
+
469
+ // Text with {holes} becomes an f-string; a value that is not text is shown the Thunder way (yes/no, $1.00, nothing).
470
+ str(e, ctx) {
471
+ if (e.parts.every((p) => typeof p === 'string')) return py(e.parts.join(''));
472
+ const holes = e.parts.map((p) => {
473
+ if (typeof p === 'string') return null;
474
+ const t = p.e.type?.k;
475
+ const c = this.x(p.e, ctx).c;
476
+ return t === 'text' || t === 'whole' ? c : `${this.R('show')}(${c})`;
477
+ });
478
+ const code = holes.filter(Boolean).join('');
479
+ const q = !code.includes('"') ? '"' : !code.includes("'") ? "'" : null;
480
+ if (q && !code.includes('\\')) {
481
+ const lit = (s) => py(s).slice(1, -1).replace(/\{/g, '{{').replace(/\}/g, '}}').replace(q === "'" ? /'/g : /(?!)/g, "\\'").replace(q === "'" ? /\\"/g : /(?!)/g, '"');
482
+ return `f${q}${e.parts.map((p, k) => (typeof p === 'string' ? lit(p) : `{${holes[k]}}`)).join('')}${q}`;
483
+ }
484
+ return e.parts.map((p, k) => (typeof p === 'string' ? py(p) : holes[k].startsWith('show(') ? holes[k] : `${this.R('show')}(${holes[k]})`)).join(' + ');
485
+ }
486
+ }
package/src/core.d.ts CHANGED
@@ -23,6 +23,7 @@ export { linkSystem, callsSummary, areaOf } from './system.mjs';
23
23
  export { THUNDERIZE_SCHEMA, THUNDER_TEXT_EXT, thunderizeFile, thunderizeFiles } from './thunderize.mjs';
24
24
  export { SAME_SCHEMA, sameMeaning, compareRules, comparePlainRules, renderSame } from './same.mjs';
25
25
  export { REVIEW_SCHEMA, REVIEW_MARKER, thunderReview, renderReview } from './review.mjs';
26
+ export { renderReviewComment, reviewCounts, GITHUB_COMMENT_LIMIT } from './review-comment.mjs';
26
27
  export type { ColorRole, ElementKind, Provenance as VisualProvenance, Visual } from './visual.mjs';
27
28
  export { plainFromReading } from './plain-contract.mjs';
28
29
  export function conditionText(model: unknown, condition: unknown): string;
@@ -77,7 +78,9 @@ export {
77
78
  } from './index';
78
79
 
79
80
  // Code generation , deterministic scaffolds from intent.
80
- export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython, subjectName, intentRefId, skillRefId } from './index';
81
+ export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython, generateWithDiagnostics, subjectName, intentRefId, skillRefId } from './index';
82
+ export { GEN_UNTRANSLATED, ERROR_KINDS, isCaseResult, untranslatedMessage, parseMoney, formatMoney, roundHalfUp, minorUnitsFor, moneyTypeMinorUnits, MoneyError, MONEY_DEFAULT_MINOR_UNITS } from './index';
83
+ export type { CaseResult, TargetRun, TargetErrorKind, GenerationDiagnostic } from './index';
81
84
 
82
85
  // 12-Factor Agents conformance lens (twelve-factor-v1).
83
86
  export { TWELVE_FACTOR_SCHEMA, TwelveFactorResult, twelveFactorReport, twelveFactorSummary } from './index';
@@ -126,7 +129,7 @@ export {
126
129
  } from './index';
127
130
 
128
131
  // Decisions -> readable typed source in six languages.
129
- export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
132
+ export { translateDecisions, translateDecisionsWithDiagnostics, TRANSLATE_LANGUAGES } from './translate.mjs';
130
133
  export type { TranslateLanguage } from './translate.mjs';
131
134
 
132
135
  // Read code you don't know.
package/src/core.mjs CHANGED
@@ -22,6 +22,7 @@ export { THUNDERIZE_SCHEMA, THUNDER_TEXT_EXT, thunderizeFile, thunderizeFiles }
22
22
  export { SAME_SCHEMA, sameMeaning, compareRules, comparePlainRules, renderSame } from './same.mjs';
23
23
  // Review in Thunder: what a change did to the meaning of the code, in plain sentences (pure; the CLI does the git work).
24
24
  export { REVIEW_SCHEMA, REVIEW_MARKER, thunderReview, renderReview } from './review.mjs';
25
+ export { renderReviewComment, reviewCounts, GITHUB_COMMENT_LIMIT } from './review-comment.mjs';
25
26
  export { plainFromReading, conditionText } from './plain-contract.mjs';
26
27
  // Editor help (browser-safe): completions, hover, autocorrect, quick fixes, and the semantic type vocabulary.
27
28
  export { getCompletions, getHover, autocorrectSource, getCodeActions, SEMANTIC_TYPES } from './intellisense.mjs';
@@ -101,7 +102,9 @@ export { FOCUS_SCHEMA, SCOPE_TYPES, FOCUS_REASONS, makeScope, buildFocusGraph, i
101
102
  // Comprehension Contract: the C0..C7 understanding level (browser-safe; every product reads it).
102
103
  export { COMPREHENSION_SCHEMA, LEVELS as COMPREHENSION_LEVELS, comprehensionLevel, comprehensionReport } from './comprehension.mjs';
103
104
  // Code generation: deterministic scaffolds from intent (browser-safe, so the playground renders it).
104
- export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython } from './codegen.mjs';
105
+ export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython, generateWithDiagnostics } from './codegen.mjs';
106
+ export { GEN_UNTRANSLATED, ERROR_KINDS, isCaseResult, untranslatedMessage } from './target-result.mjs';
107
+ export { parseMoney, formatMoney, roundHalfUp, minorUnitsFor, moneyTypeMinorUnits, MoneyError, MONEY_DEFAULT_MINOR_UNITS } from './money.mjs';
105
108
  // Change Lens: what a branch/PR changed by meaning (pure; the CLI supplies the git-diffed graphs).
106
109
  export { CHANGES_SCHEMA, changeReport } from './changes.mjs';
107
110
  export { subjectName, intentRefId, skillRefId } from './parse.mjs';
@@ -115,7 +118,7 @@ export { graphToSource, GRAPH_SOURCE_SCHEMA } from './graph-source.mjs';
115
118
  export { resolveObligations } from './obligations.mjs';
116
119
  export { runTests, TEST_SCHEMA } from './testing.mjs';
117
120
  // Decisions -> readable typed source in six languages (browser-safe; same translators as the targets).
118
- export { translateDecisions, TRANSLATE_LANGUAGES } from './translate.mjs';
121
+ export { translateDecisions, translateDecisionsWithDiagnostics, TRANSLATE_LANGUAGES } from './translate.mjs';
119
122
  // Read code you don't know: decisions recovered from six languages as ThunderLang + plain English.
120
123
  export { readCode, searchReading, detectLanguage, READ_SCHEMA, READ_LANGUAGES, INFRA_LANGUAGES, completenessOf, displayLabel } from './read.mjs';
121
124
  // Read a whole repository (pure: the caller passes file contents) and turn a recovered decision into a contract.
@@ -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
- money: { type: 'number' },
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.3';
33
+ export const COMPILER_VERSION = '1.1.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, {