@skillstech/thunderlang 1.0.4 → 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 (66) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/dist/core.cjs +2568 -462
  3. package/dist/index.cjs +7562 -5084
  4. package/dist/learn.cjs +1963 -315
  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/mcp.mjs +23 -0
  33. package/src/meaning.mjs +45 -6
  34. package/src/model.d.mts +7 -3
  35. package/src/model.mjs +19 -6
  36. package/src/money.d.mts +18 -0
  37. package/src/money.mjs +124 -0
  38. package/src/plain-contract.mjs +18 -2
  39. package/src/read.d.mts +11 -0
  40. package/src/read.mjs +40 -6
  41. package/src/review-comment.d.mts +16 -0
  42. package/src/review-comment.mjs +145 -0
  43. package/src/say-less.mjs +1432 -0
  44. package/src/system.mjs +153 -44
  45. package/src/target-cs.mjs +39 -34
  46. package/src/target-elixir.mjs +40 -30
  47. package/src/target-go.mjs +41 -36
  48. package/src/target-java.mjs +34 -27
  49. package/src/target-kotlin.mjs +43 -35
  50. package/src/target-py.mjs +57 -55
  51. package/src/target-result.d.mts +48 -0
  52. package/src/target-result.mjs +112 -0
  53. package/src/target-rust.mjs +42 -38
  54. package/src/target-scala.mjs +45 -35
  55. package/src/target-ts.mjs +37 -45
  56. package/src/target-types.mjs +41 -5
  57. package/src/target-util.mjs +55 -2
  58. package/src/trace-cli.mjs +58 -0
  59. package/src/trace-fs.mjs +76 -0
  60. package/src/trace.mjs +261 -0
  61. package/src/translate.d.mts +3 -0
  62. package/src/translate.mjs +62 -32
  63. package/src/why-cli.mjs +31 -0
  64. package/src/why.d.mts +28 -0
  65. package/src/why.mjs +532 -0
  66. package/src/write-steps.mjs +22 -5
package/src/system.mjs CHANGED
@@ -298,12 +298,79 @@ function urlArg(call) {
298
298
  return args[0];
299
299
  }
300
300
 
301
+ /** [, METHOD] for a call such as `axios.delete(…)` / `http.get(…)` in a step shown as code, else null. */
302
+ function httpOfCode(calls) {
303
+ for (const call of calls) {
304
+ const path = calleePath(call.callee) || [];
305
+ if (path.length === 2 && /^(?:axios|http|https|client|api|request|superagent|ky|got|\$http|httpClient|HttpClient|requests|session)$/i.test(path[0]) && /^(get|post|put|patch|delete|head)$/i.test(path[1])) return [null, path[1].toUpperCase()];
306
+ }
307
+ return null;
308
+ }
309
+
301
310
  const EVENT_PUBLISH = /^(emit|publish|publishEvent|sendToQueue|enqueue|basic_publish|produce|dispatch)$/;
302
311
  const EVENT_SUBSCRIBE = /\.(on|once|addListener|subscribe|consume|listen|handle)\(\s*(['"`])([^'"`]+)\2\s*,\s*(?:(?:async\s*)?(?:function\b|\(|[\w$]+\s*=>)|((?:this\.|self\.)?[\w$]+)\s*[,)])/g;
303
312
  const EVENT_DECORATOR = /@(OnEvent|EventPattern|MessagePattern|KafkaListener|RabbitListener|SqsListener|JmsListener|StreamListener|Subscribe|EventHandler|Consumer)\s*\(\s*(?:\{?\s*)?(?:(?:topics|queues|destination|value|pattern|event)\s*[:=]\s*)?(?:\[\s*)?(['"])([^'"]+)\2/g;
304
313
  /** Names any emitter uses (a stream's 'error', a socket's 'close'): matching them across files would be a guess. */
305
314
  const GENERIC_EVENTS = new Set(['error', 'close', 'end', 'data', 'finish', 'open', 'message', 'connect', 'connection', 'request', 'response', 'listening', 'drain', 'pipe', 'unpipe', 'readable', 'timeout', 'abort', 'change', 'click', 'input', 'submit', 'load', 'ready', 'exit', 'mount', 'start', 'stop', 'done', 'update', 'success', 'fail', 'progress', 'headers', 'upgrade', 'secureConnection', 'disconnect', 'reconnect']);
306
315
 
316
+ /** The HTTP routes this app handles: [{ member, method, segs, path }]. (Next.js route files included.) */
317
+ function routesIn(model, isDefaultExport) {
318
+ const routes = [];
319
+ for (const m of model.members) {
320
+ if (!m.route) continue;
321
+ const r = m.route.match(/^(\w+)\s+(.*)$/);
322
+ if (r) routes.push({ member: m, method: r[1].toUpperCase(), segs: routeSegs(r[2]), path: r[2] });
323
+ }
324
+ // Next.js route files: app/api/orders/[id]/route.ts exports GET, POST, …; pages/api/orders.ts handles any method.
325
+ for (const m of model.members) {
326
+ if (m.route || m.owner) continue;
327
+ const app = m.file.match(/(?:^|\/)app\/(.*?)\/?route\.(?:ts|js|tsx|jsx|mjs)$/);
328
+ if (app && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(m.name)) routes.push({ member: m, method: m.name, segs: routeSegs('/' + app[1].replace(/\([^)]*\)\/?/g, '')), path: '/' + app[1] });
329
+ const pages = m.file.match(/(?:^|\/)pages\/(api\/.*?)(?:\/index)?\.(?:ts|js|tsx|jsx)$/);
330
+ if (pages && isDefaultExport(m)) routes.push({ member: m, method: 'ANY', segs: routeSegs('/' + pages[1]), path: '/' + pages[1] });
331
+ }
332
+ return routes;
333
+ }
334
+
335
+ /** Who listens for each event or queue name: Map(name -> [{ member, how }]). */
336
+ function listenersIn(model, sources, membersOf) {
337
+ const listeners = new Map();
338
+ const addListener = (name, member, how) => { if (!member) return; const l = listeners.get(name) ?? listeners.set(name, []).get(name); if (!l.some((x) => x.member === member)) l.push({ member, how }); };
339
+ for (const f of model.files) {
340
+ const src = sources.get(f.path);
341
+ if (!src || !/\.(on|once|addListener|subscribe|consume|listen|handle)\(|@\w+(Listener|Pattern|Event|Handler)\b|@Subscribe|@Consumer|new\s+Worker\(/.test(src)) continue;
342
+ const ms = membersOf.get(f.path) || [];
343
+ for (const m of src.matchAll(EVENT_SUBSCRIBE)) {
344
+ if (GENERIC_EVENTS.has(m[3])) continue;
345
+ const line = lineAt(src, m.index);
346
+ // The handler: a function written right there (an item since it has no name of its own), or one named.
347
+ const handler = m[4] ? (ms.find((x) => x.name === m[4].replace(/^(this|self)\./, '') && !x.callback) ?? null) : ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0];
348
+ addListener(m[3], handler, m[1]);
349
+ }
350
+ for (const m of src.matchAll(/new\s+Worker\(\s*(['"`])([^'"`]+)\1\s*,/g)) {
351
+ const line = lineAt(src, m.index);
352
+ addListener(m[2], ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0], 'worker');
353
+ }
354
+ for (const m of src.matchAll(EVENT_DECORATOR)) {
355
+ const line = lineAt(src, m.index);
356
+ addListener(m[3], ms.filter((x) => x.lines[0] > line && x.lines[0] <= line + 6).sort((a, b) => a.lines[0] - b.lines[0])[0], m[1]);
357
+ }
358
+ }
359
+ return listeners;
360
+ }
361
+
362
+ /** `const emails = new Queue('emails')`: Map(`file|emails` -> 'emails'). */
363
+ // `const emails = new Queue('emails')` then `emails.add(…)`: the queue's name.
364
+ function queueNamesIn(model, sources) {
365
+ const queueNames = new Map();
366
+ for (const f of model.files) {
367
+ const src = sources.get(f.path);
368
+ if (!src || !/new\s+Queue\(/.test(src)) continue;
369
+ for (const m of src.matchAll(/(?:\b(?:const|let|var)\s+|this\.)([\w$]+)\s*=\s*new\s+Queue\(\s*(['"`])([^'"`]+)\2/g)) queueNames.set(`${f.path}|${m[1]}`, m[3]);
370
+ }
371
+ return queueNames;
372
+ }
373
+
307
374
  // ── Linking ──────────────────────────────────────────────────────────────────────────────────────────
308
375
 
309
376
  /**
@@ -711,49 +778,9 @@ export function linkSystem(model, files) {
711
778
  };
712
779
 
713
780
  // ── Routes and listeners ──
714
- const routes = [];
715
- for (const m of model.members) {
716
- if (!m.route) continue;
717
- const r = m.route.match(/^(\w+)\s+(.*)$/);
718
- if (r) routes.push({ member: m, method: r[1].toUpperCase(), segs: routeSegs(r[2]), path: r[2] });
719
- }
720
- // Next.js route files: app/api/orders/[id]/route.ts exports GET, POST, …; pages/api/orders.ts handles any method.
721
- for (const m of model.members) {
722
- if (m.route || m.owner) continue;
723
- const app = m.file.match(/(?:^|\/)app\/(.*?)\/?route\.(?:ts|js|tsx|jsx|mjs)$/);
724
- if (app && /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/.test(m.name)) routes.push({ member: m, method: m.name, segs: routeSegs('/' + app[1].replace(/\([^)]*\)\/?/g, '')), path: '/' + app[1] });
725
- const pages = m.file.match(/(?:^|\/)pages\/(api\/.*?)(?:\/index)?\.(?:ts|js|tsx|jsx)$/);
726
- if (pages && topOf(m.file).get(m.name)?.[0] === m && jsExp(m.file).def === m.name) routes.push({ member: m, method: 'ANY', segs: routeSegs('/' + pages[1]), path: '/' + pages[1] });
727
- }
728
- const listeners = new Map();
729
- const addListener = (name, member, how) => { if (!member) return; const l = listeners.get(name) ?? listeners.set(name, []).get(name); if (!l.some((x) => x.member === member)) l.push({ member, how }); };
730
- for (const f of model.files) {
731
- const src = sources.get(f.path);
732
- if (!src || !/\.(on|once|addListener|subscribe|consume|listen|handle)\(|@\w+(Listener|Pattern|Event|Handler)\b|@Subscribe|@Consumer|new\s+Worker\(/.test(src)) continue;
733
- const ms = membersOf.get(f.path) || [];
734
- for (const m of src.matchAll(EVENT_SUBSCRIBE)) {
735
- if (GENERIC_EVENTS.has(m[3])) continue;
736
- const line = lineAt(src, m.index);
737
- // The handler: a function written right there (an item since it has no name of its own), or one named.
738
- const handler = m[4] ? (ms.find((x) => x.name === m[4].replace(/^(this|self)\./, '') && !x.callback) ?? null) : ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0];
739
- addListener(m[3], handler, m[1]);
740
- }
741
- for (const m of src.matchAll(/new\s+Worker\(\s*(['"`])([^'"`]+)\1\s*,/g)) {
742
- const line = lineAt(src, m.index);
743
- addListener(m[2], ms.filter((x) => x.lines[0] >= line && x.lines[0] <= line + 2).sort((a, b) => a.lines[0] - b.lines[0])[0], 'worker');
744
- }
745
- for (const m of src.matchAll(EVENT_DECORATOR)) {
746
- const line = lineAt(src, m.index);
747
- addListener(m[3], ms.filter((x) => x.lines[0] > line && x.lines[0] <= line + 6).sort((a, b) => a.lines[0] - b.lines[0])[0], m[1]);
748
- }
749
- }
750
- // `const emails = new Queue('emails')` then `emails.add(…)`: the queue's name.
751
- const queueNames = new Map();
752
- for (const f of model.files) {
753
- const src = sources.get(f.path);
754
- if (!src || !/new\s+Queue\(/.test(src)) continue;
755
- for (const m of src.matchAll(/(?:\b(?:const|let|var)\s+|this\.)([\w$]+)\s*=\s*new\s+Queue\(\s*(['"`])([^'"`]+)\2/g)) queueNames.set(`${f.path}|${m[1]}`, m[3]);
756
- }
781
+ const routes = routesIn(model, (m) => topOf(m.file).get(m.name)?.[0] === m && jsExp(m.file).def === m.name);
782
+ const listeners = listenersIn(model, sources, membersOf);
783
+ const queueNames = queueNamesIn(model, sources);
757
784
 
758
785
  // ── Walk every step of every member ──
759
786
  const seen = new Set();
@@ -765,7 +792,8 @@ export function linkSystem(model, files) {
765
792
  if (!nd.expr) continue;
766
793
  const calls = callsIn(nd.expr);
767
794
  if (!calls.length) continue;
768
- const http = HTTP_SAYS.exec(nd.text || '');
795
+ // (A step shown as code still sends its request: an HTTP client's get/post/… names the method.)
796
+ const http = HTTP_SAYS.exec(nd.text || '') || (nd.explained === false ? httpOfCode(calls) : null);
769
797
  let httpDone = false;
770
798
  for (const call of calls) {
771
799
  const path = calleePath(call.callee);
@@ -819,6 +847,87 @@ export function linkSystem(model, files) {
819
847
  return model;
820
848
  }
821
849
 
850
+ // ── Service facts: what an app offers and what it calls, for linking ACROSS repositories ─────────────
851
+
852
+ /** Paths every service has: linking them across repositories would be a guess, not a fact. */
853
+ export const GENERIC_PATHS = new Set(['/', '/health', '/healthz', '/health/live', '/health/ready', '/ready', '/readyz', '/live', '/livez', '/status', '/metrics', '/ping', '/version', '/info', '/favicon.ico', '/robots.txt']);
854
+
855
+ /**
856
+ * The path an HTTP call reaches once its base address is set. `${ORDERS_URL}/api/orders` reaches /api/orders on
857
+ * whatever ORDERS_URL names (base 'computed'); 'http://orders:8080/api/orders' reaches it on host orders:8080.
858
+ * null when the path itself is worked out when the code runs.
859
+ */
860
+ function requestTarget(e) {
861
+ const u = urlOf(e);
862
+ if (u.segs) return { path: u.path, segs: u.segs, base: 'this app' };
863
+ let text = null;
864
+ if (e?.kind === 'template') text = e.parts.map((p) => (typeof p === 'string' ? p : PLACEHOLDER)).join('');
865
+ else if (e?.kind === 'literal' && e.type === 'text') text = String(e.value);
866
+ else if (e?.kind === 'literal' && e.interpolated) text = String(e.value).replace(/\$\{[^}]*\}|\$\w+|#\{[^}]*\}|\{[^}]*\}/g, PLACEHOLDER);
867
+ else if (e?.kind === 'binary' && e.op === '+') {
868
+ const parts = [];
869
+ const flat = (x) => { if (x.kind === 'binary' && x.op === '+') { flat(x.left); flat(x.right); } else parts.push(x); };
870
+ flat(e);
871
+ text = parts.map((x) => (x.kind === 'literal' && x.type === 'text' ? String(x.value) : PLACEHOLDER)).join('');
872
+ }
873
+ if (text == null) return null;
874
+ let base;
875
+ const abs = text.match(/^[a-z][a-z0-9+.-]*:\/\/([^/]*)(.*)$/i);
876
+ if (abs) { if (abs[1].includes(PLACEHOLDER)) base = 'computed'; else base = abs[1]; text = abs[2] || '/'; }
877
+ else if (text.startsWith(PLACEHOLDER)) { base = 'computed'; text = text.slice(PLACEHOLDER.length); }
878
+ else return null;
879
+ if (!text.startsWith('/') || text.slice(1).startsWith(PLACEHOLDER) && text.length === 1 + PLACEHOLDER.length) return null;
880
+ const path = text.replace(/[?#].*$/s, '');
881
+ const segs = path.split('/').filter(Boolean).map((s) => (s.includes(PLACEHOLDER) ? '*' : s));
882
+ return { path: '/' + segs.map((s) => (s === '*' ? ':value' : s)).join('/'), segs, base };
883
+ }
884
+
885
+ /**
886
+ * What this app offers other apps (routes it handles, events it listens for) and what it asks of them (HTTP
887
+ * requests, events it publishes), each with its member and line. Read from the same steps linkSystem walks, with
888
+ * the same matchers; nothing is guessed: a request whose path is worked out when it runs is left out with a reason.
889
+ * { routes, listeners, requests, publishes, unknown }
890
+ */
891
+ export function serviceFacts(model, files) {
892
+ const sources = new Map(files.map((f) => [f.path, String(f.source ?? '')]));
893
+ const membersOf = new Map();
894
+ for (const m of model.members) (membersOf.get(m.file) ?? membersOf.set(m.file, []).get(m.file)).push(m);
895
+ const at = (m, line) => ({ member: m.id, label: m.label, file: m.file, line: line ?? m.lines?.[0] ?? null, lines: m.lines ?? null });
896
+ const routes = routesIn(model, (m) => !m.owner && !m.callback && jsExports(sources.get(m.file) || '').def === m.name)
897
+ .map((r) => ({ method: r.method, path: r.path, segs: r.segs, ...at(r.member) }));
898
+ const listeners = [];
899
+ for (const [event, ls] of listenersIn(model, sources, membersOf)) if (event.trim()) for (const x of ls) listeners.push({ event, how: x.how, ...at(x.member) });
900
+ const queueNames = queueNamesIn(model, sources);
901
+ const requests = [], publishes = [], unknown = [];
902
+ for (const m of model.members) {
903
+ for (const nd of m.flow?.nodes || []) {
904
+ if (!nd.expr) continue;
905
+ const http = HTTP_SAYS.exec(nd.text || '');
906
+ let httpDone = false;
907
+ for (const call of callsIn(nd.expr)) {
908
+ const path = calleePath(call.callee);
909
+ if (!path) continue;
910
+ if (http && !httpDone && /^(fetch|get|post|put|patch|delete|head|request|Get|Post|Put|Patch|Delete|Head|NewRequest|NewRequestWithContext|\w+Async|\w+ForObject|\w+ForEntity|exchange)$/.test(path.at(-1))) {
911
+ httpDone = true;
912
+ const t = requestTarget(urlArg(call));
913
+ if (t) requests.push({ method: http[1], path: t.path, segs: t.segs, base: t.base, ...at(m, nd.line) });
914
+ else unknown.push({ ...at(m, nd.line), call: `${http[1]} request`, why: urlOf(urlArg(call)).why ?? 'the path is worked out when it runs' });
915
+ continue;
916
+ }
917
+ const last = path.at(-1);
918
+ const queue = path.length === 2 && /^(add|addBulk)$/.test(last) ? queueNames.get(`${m.file}|${path[0]}`) : null;
919
+ if (queue || (EVENT_PUBLISH.test(last) && call.args?.[0]?.kind === 'literal' && call.args[0].type === 'text')) {
920
+ const name = queue ?? String(call.args[0].value);
921
+ if (name.trim() && !GENERIC_EVENTS.has(name)) publishes.push({ event: name, how: queue ? 'queue' : last, ...at(m, nd.line) });
922
+ }
923
+ }
924
+ }
925
+ }
926
+ return { routes, listeners, requests, publishes, unknown };
927
+ }
928
+
929
+ export { segsMatch };
930
+
822
931
  // ── The app's map: which areas call which ────────────────────────────────────────────────────────────
823
932
 
824
933
  /** An area: a file's folder, at most two levels deep ("src/orders"), or "(top)" for files at the top. */
package/src/target-cs.mjs CHANGED
@@ -2,32 +2,35 @@
2
2
  // static method (using the same exprToCSharp translator the codegen uses), calls every test case
3
3
  // with typed literal arguments, and prints the results as one JSON line. It runs through a
4
4
  // throwaway `dotnet` console project (scaffold + `dotnet run`), so a live C# run grades real
5
- // compiled + executed code. Returns null (skip cleanly) when no usable .NET SDK exists.
6
- import { spawnSync } from 'node:child_process';
5
+ // compiled + executed code.
6
+ //
7
+ // Results are honest (see target-result.mjs): a missing toolchain, a compile failure, a crash, or a
8
+ // timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
9
+ // translate is refused ('not-translated'). Money inputs are C# decimal, never double.
7
10
  import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
11
  import { join } from 'node:path';
9
12
  import { tmpdir } from 'node:os';
10
13
  import { exprToCSharp } from './expr.mjs';
11
- import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
14
+ import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
12
15
 
13
- const CS_TYPE = { number: 'double', bool: 'bool', string: 'string' };
16
+ const CS_TYPE = { number: 'double', bool: 'bool', string: 'string', money: 'decimal' };
17
+ const CS_RUN = { translate: exprToCSharp, target: 'C#', dialect: 'csharp' };
18
+ const CS_RUNTIME = /Unhandled exception/i;
14
19
 
15
20
  // Scaffold a bare console project in `dir`, overwrite Program.cs with `source`, and run it.
16
- // Returns stdout, or null on any failure. A bare console app has no external packages, so the
17
- // implicit restore is offline.
21
+ // Returns { ok, stdout } or { ok: false, failure }. A bare console app has no external packages,
22
+ // so the implicit restore is offline.
18
23
  function dotnetRun(dir, source) {
19
24
  const proj = join(dir, 'app');
20
25
  const env = { ...process.env, DOTNET_CLI_TELEMETRY_OPTOUT: '1', DOTNET_NOLOGO: '1', DOTNET_SKIP_FIRST_TIME_EXPERIENCE: '1' };
21
- const mk = spawnSync('dotnet', ['new', 'console', '-o', proj], { encoding: 'utf8', timeout: 120000, env });
22
- if (mk.status !== 0) return null;
26
+ const mk = spawnStep('dotnet', ['new', 'console', '-o', proj], { timeout: 120000, env }, (r) => classifySpawn(r, { tool: 'dotnet new', phase: 'compile' }));
27
+ if (!mk.ok) return mk;
23
28
  writeFileSync(join(proj, 'Program.cs'), source);
24
- const run = spawnSync('dotnet', ['run', '--project', proj, '-c', 'Release'], { encoding: 'utf8', timeout: 240000, env });
25
- if (run.status !== 0) return null;
26
- return run.stdout;
29
+ return spawnStep('dotnet', ['run', '--project', proj, '-c', 'Release'], { timeout: 240000, env }, (r) => classifySpawn(r, { tool: 'dotnet', phase: 'build+run', runtimePattern: CS_RUNTIME }));
27
30
  }
28
31
 
29
32
  // The emitted C# source (also usable for display / `gen`-parity).
30
- export function emitCSharpModule(ast, cases = buildCases(ast)) {
33
+ export function emitCSharpModule(ast, cases = prepareRun(ast, CS_RUN).cases, plans = plansFor(ast, exprToCSharp, 'C#')) {
31
34
  const L = [
32
35
  'using System;',
33
36
  'using System.Collections.Generic;',
@@ -35,18 +38,17 @@ export function emitCSharpModule(ast, cases = buildCases(ast)) {
35
38
  'using System.Text;',
36
39
  'class ThunderTarget {',
37
40
  ];
38
- const typesByDec = {};
39
- for (const d of ast.decisions || []) {
40
- const names = inputNames(d);
41
- const types = inferInputTypes(ast, d);
42
- typesByDec[d.name] = types;
43
- const params = names.map((n) => `${CS_TYPE[types[n]] || 'string'} ${n}`).join(', ');
44
- L.push(` static string ${d.name}(${params}) {`);
45
- for (const r of d.rules || []) {
46
- let cond; try { cond = exprToCSharp(r.when, { inputs: names }); } catch { cond = 'false'; }
47
- L.push(` if (${cond}) return ${strLit(r.result)};`);
41
+ if ([...plans.values()].some((p) => p.refused)) {
42
+ L.push(' // IL-GEN-001: a rule Thunder could not translate throws instead of guessing.');
43
+ L.push(' static bool ThunderUntranslated(string message) => throw new NotImplementedException(message);');
44
+ }
45
+ for (const p of plans.values()) {
46
+ const params = p.names.map((n) => `${CS_TYPE[p.types[n]] || 'string'} ${n}`).join(', ');
47
+ L.push(` static string ${p.decision.name}(${params}) {`);
48
+ for (const { rule: r, code, message } of p.rules) {
49
+ L.push(` if (${code ?? `ThunderUntranslated(${strLit(message)})`}) return ${strLit(r.result)};`);
48
50
  }
49
- L.push(` return ${d.default == null ? 'null' : strLit(d.default)};`, ' }');
51
+ L.push(` return ${p.decision.default == null ? 'null' : strLit(p.decision.default)};`, ' }');
50
52
  }
51
53
  L.push(' static string J(string s) {');
52
54
  L.push(' if (s == null) return "null";');
@@ -58,10 +60,9 @@ export function emitCSharpModule(ast, cases = buildCases(ast)) {
58
60
  L.push(' static void Main() {');
59
61
  L.push(' var outp = new List<KeyValuePair<string,string>>();');
60
62
  for (const c of cases) {
61
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
62
- if (!dec) continue;
63
- const types = typesByDec[c.fn];
64
- const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
63
+ const p = plans.get(c.fn);
64
+ if (!p) continue;
65
+ const argList = p.names.map((n) => argLit(c, p, n, litFor)).join(', ');
65
66
  L.push(` outp.Add(new KeyValuePair<string,string>(${strLit(c.key)}, ${c.fn}(${argList})));`);
66
67
  }
67
68
  L.push(' var sb = new StringBuilder("{"); bool first = true;');
@@ -80,19 +81,23 @@ export function csharpAvailable() {
80
81
  try {
81
82
  const src = 'using System; class ThunderTarget { static void Main(){ Console.WriteLine("{\\"ok\\":\\"1\\"}"); } }';
82
83
  const out = dotnetRun(dir, src);
83
- return !!out && /"ok"/.test(out);
84
+ return out.ok && /"ok"/.test(out.stdout);
84
85
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
85
86
  });
86
87
  }
87
88
 
88
- // Run every decision test case through generated, compiled C#. Returns { "Test / case": actual }
89
- // or null when no usable .NET SDK is present.
89
+ // Run every decision test case through generated, compiled C#. Returns { status: 'ok', results }
90
+ // or a whole-run { status: 'error', kind, message }.
90
91
  export function runCSharpTarget(ast) {
91
- if (!csharpAvailable()) return null;
92
- const cases = buildCases(ast);
92
+ if (!csharpAvailable()) return runFailure('missing-toolchain', 'No usable .NET SDK (dotnet new + dotnet run) on this machine.');
93
+ const { plans, cases, refused } = prepareRun(ast, CS_RUN);
94
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
93
95
  const dir = mkdtempSync(join(tmpdir(), 'tl-cs-'));
94
96
  try {
95
- const out = dotnetRun(dir, emitCSharpModule(ast, cases));
96
- return out == null ? null : parseLastJsonObject(out);
97
+ const out = dotnetRun(dir, emitCSharpModule(ast, cases, plans));
98
+ if (!out.ok) return out.failure;
99
+ const parsed = parseLastJsonObject(out.stdout);
100
+ if (!parsed) return runFailure('runtime-error', 'dotnet ran but printed no results.');
101
+ return finishRun({ cases, parsed, refused, target: 'C#' });
97
102
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
98
103
  }
@@ -2,51 +2,57 @@
2
2
  // function using the SAME expression translator the codegen uses (exprToElixir), then runs the test
3
3
  // cases through a real `elixir` child process and returns actual outputs, so a live Elixir run
4
4
  // grades real executed code. Elixir function names must start lowercase, so each decision `Foo`
5
- // becomes `d_Foo`. Returns null (skip cleanly) when the elixir runtime is unavailable.
6
- import { spawnSync } from 'node:child_process';
5
+ // becomes `d_Foo`.
6
+ //
7
+ // Results are honest (see target-result.mjs): a missing runtime, a compile failure, a crash, or a
8
+ // timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
9
+ // translate is refused ('not-translated'). Elixir has no exact Money wiring yet, so a rule that
10
+ // compares Money is refused rather than run as a float.
7
11
  import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
12
  import { join } from 'node:path';
9
13
  import { tmpdir } from 'node:os';
10
14
  import { exprToElixir } from './expr.mjs';
11
- import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
15
+ import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
12
16
 
13
- // Write `source` to a .exs file in `dir` and run it. Returns stdout, or null on any failure.
17
+ const ELIXIR_RUN = { translate: exprToElixir, target: 'Elixir', dialect: 'elixir' };
18
+ const ELIXIR_RUNTIME = /\*\* \((?!CompileError|SyntaxError|TokenMissingError)\w/;
19
+ // Elixir strings interpolate `#{`, so a message literal escapes it.
20
+ const exStr = (s) => strLit(s).replace(/#\{/g, '\\#{');
21
+
22
+ // Write `source` to a .exs file in `dir` and run it. Returns { ok, stdout } or { ok: false, failure }.
14
23
  function elixirRun(dir, source) {
15
24
  const f = join(dir, 'main.exs');
16
25
  writeFileSync(f, source);
17
26
  const env = { ...process.env };
18
- const r = spawnSync('elixir', [f], { encoding: 'utf8', timeout: 120000, env });
19
- if (r.status !== 0) return null;
20
- return r.stdout;
27
+ return spawnStep('elixir', [f], { timeout: 120000, env }, (r) => classifySpawn(r, { tool: 'elixir', phase: 'build+run', runtimePattern: ELIXIR_RUNTIME }));
21
28
  }
22
29
 
23
30
  // The emitted Elixir source (also usable for display / `gen`-parity).
24
- export function emitElixirModule(ast, cases = buildCases(ast)) {
31
+ export function emitElixirModule(ast, cases = prepareRun(ast, ELIXIR_RUN).cases, plans = plansFor(ast, exprToElixir, 'Elixir')) {
25
32
  const L = ['defmodule ThunderTarget do'];
26
- const typesByDec = {};
27
- for (const d of ast.decisions || []) {
28
- const names = inputNames(d);
29
- typesByDec[d.name] = inferInputTypes(ast, d);
30
- L.push(` def d_${d.name}(${names.join(', ')}) do`);
33
+ if ([...plans.values()].some((p) => p.refused)) {
34
+ L.push(' # IL-GEN-001: a rule Thunder could not translate raises instead of guessing.');
35
+ L.push(' def thunder_untranslated(message), do: raise(message)');
36
+ }
37
+ for (const p of plans.values()) {
38
+ L.push(` def d_${p.decision.name}(${p.names.join(', ')}) do`);
31
39
  L.push(' cond do');
32
- for (const r of d.rules || []) {
33
- let cond; try { cond = exprToElixir(r.when, { inputs: names }); } catch { cond = 'false'; }
34
- L.push(` ${cond} -> ${strLit(r.result)}`);
40
+ for (const { rule: r, code, message } of p.rules) {
41
+ L.push(` ${code ?? `thunder_untranslated(${exStr(message)})`} -> ${strLit(r.result)}`);
35
42
  }
36
- L.push(` true -> ${d.default == null ? 'nil' : strLit(d.default)}`);
43
+ L.push(` true -> ${p.decision.default == null ? 'nil' : strLit(p.decision.default)}`);
37
44
  L.push(' end');
38
45
  L.push(' end');
39
46
  }
40
47
  L.push('end');
41
48
  L.push('');
42
49
  L.push('pairs = [');
43
- cases.forEach((c) => {
44
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
45
- if (!dec) return;
46
- const types = typesByDec[c.fn];
47
- const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
50
+ for (const c of cases) {
51
+ const p = plans.get(c.fn);
52
+ if (!p) continue;
53
+ const argList = p.names.map((n) => argLit(c, p, n, litFor)).join(', ');
48
54
  L.push(` {${strLit(c.key)}, ThunderTarget.d_${c.fn}(${argList})},`);
49
- });
55
+ }
50
56
  L.push(']');
51
57
  // inspect/1 renders a binary as a valid JSON string for ordinary content (quotes/backslashes/
52
58
  // newlines escaped); nil becomes JSON null. parseLastJsonObject then reads the printed line.
@@ -61,19 +67,23 @@ export function elixirAvailable() {
61
67
  try {
62
68
  const src = 'IO.puts("{\\"ok\\":\\"1\\"}")';
63
69
  const out = elixirRun(dir, src);
64
- return !!out && /"ok"/.test(out);
70
+ return out.ok && /"ok"/.test(out.stdout);
65
71
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
66
72
  });
67
73
  }
68
74
 
69
- // Run every decision test case through generated, executed Elixir. Returns { "Test / case": actual }
70
- // or null when the elixir runtime is not present.
75
+ // Run every decision test case through generated, executed Elixir. Returns { status: 'ok', results }
76
+ // or a whole-run { status: 'error', kind, message }.
71
77
  export function runElixirTarget(ast) {
72
- if (!elixirAvailable()) return null;
73
- const cases = buildCases(ast);
78
+ if (!elixirAvailable()) return runFailure('missing-toolchain', 'No usable Elixir runtime on this machine.');
79
+ const { plans, cases, refused } = prepareRun(ast, ELIXIR_RUN);
80
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
74
81
  const dir = mkdtempSync(join(tmpdir(), 'tl-ex-'));
75
82
  try {
76
- const out = elixirRun(dir, emitElixirModule(ast, cases));
77
- return out == null ? null : parseLastJsonObject(out);
83
+ const out = elixirRun(dir, emitElixirModule(ast, cases, plans));
84
+ if (!out.ok) return out.failure;
85
+ const parsed = parseLastJsonObject(out.stdout);
86
+ if (!parsed) return runFailure('runtime-error', 'elixir ran but printed no results.');
87
+ return finishRun({ cases, parsed, refused, target: 'Elixir' });
78
88
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
79
89
  }
package/src/target-go.mjs CHANGED
@@ -1,30 +1,32 @@
1
1
  // Go target adapter. Emits a self-contained `package main` that defines each decision as a typed
2
2
  // func (using the same exprToGo translator the codegen uses), calls every test case with typed
3
3
  // literal arguments, and prints the results as one JSON line. It runs through `go run`, so a live
4
- // Go run grades real compiled + executed code. Returns null (skip cleanly) when no usable Go
5
- // toolchain exists.
6
- import { spawnSync } from 'node:child_process';
4
+ // Go run grades real compiled + executed code.
5
+ //
6
+ // Results are honest (see target-result.mjs): a missing toolchain, a compile failure, a crash, or a
7
+ // timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
8
+ // translate is refused ('not-translated'). Money inputs are int64 minor units, never floats.
7
9
  import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
8
10
  import { join } from 'node:path';
9
11
  import { tmpdir } from 'node:os';
10
12
  import { exprToGo } from './expr.mjs';
11
- import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
13
+ import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
12
14
 
13
- const GO_TYPE = { number: 'float64', bool: 'bool', string: 'string' };
15
+ const GO_TYPE = { number: 'float64', bool: 'bool', string: 'string', money: 'int64' };
16
+ const GO_RUN = { translate: exprToGo, target: 'Go', dialect: 'go' };
17
+ const GO_RUNTIME = /panic:|^exit status/m;
14
18
 
15
- // Write `source` to main.go in `dir` and `go run` it. Returns stdout, or null on any failure.
19
+ // Write `source` to main.go in `dir` and `go run` it. Returns { ok, stdout } or { ok: false, failure }.
16
20
  // GO111MODULE=off runs a single stdlib-only file with no go.mod; GOTOOLCHAIN=local avoids network.
17
21
  function goRun(dir, source) {
18
22
  const f = join(dir, 'main.go');
19
23
  writeFileSync(f, source);
20
24
  const env = { ...process.env, GO111MODULE: 'off', GOTOOLCHAIN: 'local', GOCACHE: join(dir, '.gocache'), GOFLAGS: '' };
21
- const r = spawnSync('go', ['run', f], { encoding: 'utf8', timeout: 180000, env });
22
- if (r.status !== 0) return null;
23
- return r.stdout;
25
+ return spawnStep('go', ['run', f], { timeout: 180000, env }, (r) => classifySpawn(r, { tool: 'go', phase: 'build+run', runtimePattern: GO_RUNTIME }));
24
26
  }
25
27
 
26
28
  // The emitted Go source (also usable for display / `gen`-parity).
27
- export function emitGoModule(ast, cases = buildCases(ast)) {
29
+ export function emitGoModule(ast, cases = prepareRun(ast, GO_RUN).cases, plans = plansFor(ast, exprToGo, 'Go')) {
28
30
  const L = [
29
31
  'package main',
30
32
  '',
@@ -35,18 +37,17 @@ export function emitGoModule(ast, cases = buildCases(ast)) {
35
37
  ')',
36
38
  '',
37
39
  ];
38
- const typesByDec = {};
39
- for (const d of ast.decisions || []) {
40
- const names = inputNames(d);
41
- const types = inferInputTypes(ast, d);
42
- typesByDec[d.name] = types;
43
- const params = names.map((n) => `${n} ${GO_TYPE[types[n]] || 'string'}`).join(', ');
44
- L.push(`func ${d.name}(${params}) string {`);
45
- for (const r of d.rules || []) {
46
- let cond; try { cond = exprToGo(r.when, { inputs: names }); } catch { cond = 'false'; }
47
- L.push(`\tif ${cond} {`, `\t\treturn ${strLit(r.result)}`, '\t}');
40
+ if ([...plans.values()].some((p) => p.refused)) {
41
+ L.push('// IL-GEN-001: a rule Thunder could not translate panics instead of guessing.');
42
+ L.push('func thunderUntranslated(message string) bool {', '\tpanic(message)', '}', '');
43
+ }
44
+ for (const p of plans.values()) {
45
+ const params = p.names.map((n) => `${n} ${GO_TYPE[p.types[n]] || 'string'}`).join(', ');
46
+ L.push(`func ${p.decision.name}(${params}) string {`);
47
+ for (const { rule: r, code, message } of p.rules) {
48
+ L.push(`\tif ${code ?? `thunderUntranslated(${strLit(message)})`} {`, `\t\treturn ${strLit(r.result)}`, '\t}');
48
49
  }
49
- L.push(`\treturn ${d.default == null ? '""' : strLit(d.default)}`, '}', '');
50
+ L.push(`\treturn ${p.decision.default == null ? '""' : strLit(p.decision.default)}`, '}', '');
50
51
  }
51
52
  // JSON-escape a string via the standard library, so the object we build is valid JSON.
52
53
  L.push('func j(s string) string {');
@@ -57,14 +58,14 @@ export function emitGoModule(ast, cases = buildCases(ast)) {
57
58
  L.push('func main() {');
58
59
  L.push('\tvar sb strings.Builder');
59
60
  L.push('\tsb.WriteString("{")');
60
- cases.forEach((c, idx) => {
61
- const dec = (ast.decisions || []).find((d) => d.name === c.fn);
62
- if (!dec) return;
63
- const types = typesByDec[c.fn];
64
- const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
65
- const sep = idx === 0 ? '' : ',';
66
- L.push(`\tsb.WriteString(${JSON.stringify(sep)} + j(${strLit(c.key)}) + ":" + j(${c.fn}(${argList})))`);
67
- });
61
+ let first = true;
62
+ for (const c of cases) {
63
+ const p = plans.get(c.fn);
64
+ if (!p) continue;
65
+ const argList = p.names.map((n) => argLit(c, p, n, litFor)).join(', ');
66
+ L.push(`\tsb.WriteString(${JSON.stringify(first ? '' : ',')} + j(${strLit(c.key)}) + ":" + j(${c.fn}(${argList})))`);
67
+ first = false;
68
+ }
68
69
  L.push('\tsb.WriteString("}")');
69
70
  L.push('\tfmt.Println(sb.String())');
70
71
  L.push('}');
@@ -77,19 +78,23 @@ export function goAvailable() {
77
78
  try {
78
79
  const src = 'package main\n\nimport "fmt"\n\nfunc main() {\n\tfmt.Println("{\\"ok\\":\\"1\\"}")\n}';
79
80
  const out = goRun(dir, src);
80
- return !!out && /"ok"/.test(out);
81
+ return out.ok && /"ok"/.test(out.stdout);
81
82
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
82
83
  });
83
84
  }
84
85
 
85
- // Run every decision test case through generated, compiled Go. Returns { "Test / case": actual }
86
- // or null when no usable Go toolchain is present.
86
+ // Run every decision test case through generated, compiled Go. Returns { status: 'ok', results }
87
+ // or a whole-run { status: 'error', kind, message }.
87
88
  export function runGoTarget(ast) {
88
- if (!goAvailable()) return null;
89
- const cases = buildCases(ast);
89
+ if (!goAvailable()) return runFailure('missing-toolchain', 'No usable Go toolchain (go run) on this machine.');
90
+ const { plans, cases, refused } = prepareRun(ast, GO_RUN);
91
+ if (!cases.length) return { status: 'ok', results: { ...refused } };
90
92
  const dir = mkdtempSync(join(tmpdir(), 'tl-go-'));
91
93
  try {
92
- const out = goRun(dir, emitGoModule(ast, cases));
93
- return out == null ? null : parseLastJsonObject(out);
94
+ const out = goRun(dir, emitGoModule(ast, cases, plans));
95
+ if (!out.ok) return out.failure;
96
+ const parsed = parseLastJsonObject(out.stdout);
97
+ if (!parsed) return runFailure('runtime-error', 'go ran but printed no results.');
98
+ return finishRun({ cases, parsed, refused, target: 'Go' });
94
99
  } finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
95
100
  }