@sublang/slc 0.21.0 → 0.23.0-rc.13

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 (71) hide show
  1. package/README.md +47 -48
  2. package/dist/app.d.ts +1 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/app.js +14 -3
  5. package/dist/app.js.map +1 -1
  6. package/dist/check-report.d.ts +4 -0
  7. package/dist/check-report.d.ts.map +1 -0
  8. package/dist/check-report.js +35 -0
  9. package/dist/check-report.js.map +1 -0
  10. package/dist/cli.js +45 -1
  11. package/dist/cli.js.map +1 -1
  12. package/dist/cligent-agent.d.ts.map +1 -1
  13. package/dist/cligent-agent.js +37 -1
  14. package/dist/cligent-agent.js.map +1 -1
  15. package/dist/compilation-audit.d.ts +14 -0
  16. package/dist/compilation-audit.d.ts.map +1 -0
  17. package/dist/compilation-audit.js +67 -0
  18. package/dist/compilation-audit.js.map +1 -0
  19. package/dist/compiled-executor.js +1 -1
  20. package/dist/compiled-executor.js.map +1 -1
  21. package/dist/compiler-identity.d.ts +7 -0
  22. package/dist/compiler-identity.d.ts.map +1 -0
  23. package/dist/compiler-identity.js +48 -0
  24. package/dist/compiler-identity.js.map +1 -0
  25. package/dist/config.d.ts.map +1 -1
  26. package/dist/config.js +36 -13
  27. package/dist/config.js.map +1 -1
  28. package/dist/entry-module.d.ts.map +1 -1
  29. package/dist/entry-module.js +72 -3
  30. package/dist/entry-module.js.map +1 -1
  31. package/dist/errors.d.ts.map +1 -1
  32. package/dist/errors.js +6 -0
  33. package/dist/errors.js.map +1 -1
  34. package/dist/execution.d.ts +2 -0
  35. package/dist/execution.d.ts.map +1 -1
  36. package/dist/execution.js.map +1 -1
  37. package/dist/interpreter.d.ts +2 -0
  38. package/dist/interpreter.d.ts.map +1 -1
  39. package/dist/interpreter.js +1 -1
  40. package/dist/interpreter.js.map +1 -1
  41. package/dist/isolated-check.d.ts +3 -0
  42. package/dist/isolated-check.d.ts.map +1 -0
  43. package/dist/isolated-check.js +160 -0
  44. package/dist/isolated-check.js.map +1 -0
  45. package/dist/managed-compilation.d.ts +4 -0
  46. package/dist/managed-compilation.d.ts.map +1 -0
  47. package/dist/managed-compilation.js +385 -0
  48. package/dist/managed-compilation.js.map +1 -0
  49. package/dist/runner.d.ts +15 -6
  50. package/dist/runner.d.ts.map +1 -1
  51. package/dist/runner.js +106 -46
  52. package/dist/runner.js.map +1 -1
  53. package/dist/verification-worker.d.ts +2 -0
  54. package/dist/verification-worker.d.ts.map +1 -0
  55. package/dist/verification-worker.js +223 -0
  56. package/dist/verification-worker.js.map +1 -0
  57. package/dist/verify-coverage.d.ts +3 -0
  58. package/dist/verify-coverage.d.ts.map +1 -1
  59. package/dist/verify-coverage.js +461 -71
  60. package/dist/verify-coverage.js.map +1 -1
  61. package/dist/verify-source.d.ts +2 -0
  62. package/dist/verify-source.d.ts.map +1 -1
  63. package/dist/verify-source.js +55 -0
  64. package/dist/verify-source.js.map +1 -1
  65. package/dist/verify-typescript.js +2 -0
  66. package/dist/verify-typescript.js.map +1 -1
  67. package/dist/verify.d.ts +15 -1
  68. package/dist/verify.d.ts.map +1 -1
  69. package/dist/verify.js +382 -94
  70. package/dist/verify.js.map +1 -1
  71. package/package.json +5 -5
package/dist/verify.js CHANGED
@@ -6,9 +6,10 @@
6
6
  *
7
7
  * A compiled artifact is a judgment-produced program, so `slc` re-checks it
8
8
  * against its source. The GEARS↔FSM conformance check verifies that every GEARS
9
- * item the `text2gears` phase produced maps to exactly one FSM state carrying
10
- * that item's player binding and its prompt body verbatim, and that no FSM state
11
- * references an unknown item — so a `gears2fsm` result cannot silently drift from
9
+ * action item the `text2gears` phase produced maps to exactly one working FSM
10
+ * leaf with its actor binding and authored prompt or child-input template
11
+ * preserved. Declarative items map to no leaf, and every working leaf binds a
12
+ * known action item — so a `gears2fsm` result cannot silently drift from
12
13
  * its GEARS source (the [DR-005](../decisions/005-slc-self-hosting-meta-pipeline.md)
13
14
  * auditable GEARS-to-FSM mapping).
14
15
  *
@@ -19,10 +20,10 @@
19
20
  * for every compiled `playbook`. See specs/packages/verification.md.
20
21
  */
21
22
  import { randomUUID } from 'node:crypto';
23
+ import { importFreshArtifact } from '@sublang/playbook/artifact-environment';
22
24
  import { existsSync } from 'node:fs';
23
25
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
24
26
  import { basename, dirname, join, resolve } from 'node:path';
25
- import { pathToFileURL } from 'node:url';
26
27
  import { types as nodeTypes } from 'node:util';
27
28
  import { hashFile } from './hash.js';
28
29
  import { resolveCoverageBudget, } from './verify-coverage.js';
@@ -1032,6 +1033,73 @@ function resultMap(value) {
1032
1033
  function isPlaybookItem(item) {
1033
1034
  return item.playbookId !== undefined || item.playbookIdContext !== undefined;
1034
1035
  }
1036
+ /**
1037
+ * A declarative item — a requirement or a test — has no unquoted `Captain
1038
+ * shall` line, so the parser assigns it no actor and no nested call; it maps to
1039
+ * no leaf (verification-71; DR-065).
1040
+ */
1041
+ export function isDeclarativeItem(item) {
1042
+ return item.actor === undefined && !isPlaybookItem(item);
1043
+ }
1044
+ function foldAsciiCase(id) {
1045
+ return id.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
1046
+ }
1047
+ /**
1048
+ * Resolves a leaf's `sourceItem` to the spelling of the GEARS item it cites:
1049
+ * an exact ID first, else the item whose ID equals it ignoring ASCII letter
1050
+ * case, so a machine compiled before lowercase package IDs keeps citing them
1051
+ * (verification-66; DR-065). Also reports IDs that differ only in case.
1052
+ */
1053
+ function gearsSourceItemResolver(items) {
1054
+ const exact = new Set(items.map((item) => item.id));
1055
+ const folded = new Map();
1056
+ for (const item of items) {
1057
+ const key = foldAsciiCase(item.id);
1058
+ const spellings = folded.get(key);
1059
+ // Count every heading: two items spelled alike collide as much as two
1060
+ // that differ in case.
1061
+ if (spellings === undefined)
1062
+ folded.set(key, [item.id]);
1063
+ else
1064
+ spellings.push(item.id);
1065
+ }
1066
+ const findings = [...folded.values()]
1067
+ .filter((spellings) => spellings.length > 1)
1068
+ .map((spellings) => `GEARS items ${spellings.join(', ')} have IDs equal ignoring ASCII letter case`);
1069
+ return {
1070
+ resolve: (sourceItem) => exact.has(sourceItem)
1071
+ ? sourceItem
1072
+ : (folded.get(foldAsciiCase(sourceItem))?.[0] ?? sourceItem),
1073
+ findings,
1074
+ };
1075
+ }
1076
+ /**
1077
+ * Machine syntax a declarative item must not carry: an action that lost its
1078
+ * acting clause is reported rather than read as a requirement (DR-065).
1079
+ */
1080
+ function declarativeItemFindings(item) {
1081
+ const findings = [];
1082
+ if (item.prompt !== '') {
1083
+ findings.push(`GEARS item ${item.id} has a prompt blockquote but no \`Captain shall\` acting clause`);
1084
+ }
1085
+ if (item.result !== undefined && item.resultFindings === undefined) {
1086
+ findings.push(`GEARS item ${item.id} declares Results metadata but no \`Captain shall\` acting clause`);
1087
+ }
1088
+ return findings;
1089
+ }
1090
+ /**
1091
+ * Package-form findings that need no consumer FSM: item IDs equal ignoring
1092
+ * ASCII letter case and declarative items carrying action syntax. Run at the
1093
+ * producer boundary so the phase that can still edit the GEARS repairs them
1094
+ * (verification-68; DR-065).
1095
+ */
1096
+ export function checkGearsPackageContract(gears) {
1097
+ const items = parseGearsItems(gears);
1098
+ return [
1099
+ ...gearsSourceItemResolver(items).findings,
1100
+ ...items.filter(isDeclarativeItem).flatMap(declarativeItemFindings),
1101
+ ];
1102
+ }
1035
1103
  function gearsPlaybookSignature(item) {
1036
1104
  return item.playbookIdContext === undefined
1037
1105
  ? JSON.stringify(['static', item.playbookId, item.prompt])
@@ -1157,16 +1225,28 @@ export function checkFsmChildSuspension(config) {
1157
1225
  }
1158
1226
  /**
1159
1227
  * Checks GEARS↔FSM conformance and returns human-readable findings (empty when
1160
- * conformant): every GEARS item maps to one state with the same player and the
1161
- * prompt verbatim, every captain state references a known item, and every
1228
+ * conformant): every GEARS action item maps to one state with the same player
1229
+ * and the prompt verbatim, a declarative item maps to none, every captain state
1230
+ * cites a known action item ignoring ASCII letter case, and every
1162
1231
  * captain state's `result` map declares the Boss-reply suspension key with its
1163
- * adjudicator contract (verification-1, verification-3; DR-009).
1232
+ * adjudicator contract (verification-1, verification-3, verification-71,
1233
+ * verification-66; DR-009, DR-065).
1164
1234
  */
1165
1235
  function gearsFsmConformance(gears, config, options = {}, reached) {
1166
1236
  const items = parseGearsItems(gears);
1237
+ // Every comparison below reads a state's sourceItem in its GEARS item's own
1238
+ // spelling; the original playbook bindings stay for reached-input replay,
1239
+ // which compares the FSM's own spelling with the runtime input.
1240
+ const citation = gearsSourceItemResolver(items);
1167
1241
  const roleContract = inspectGearsRoleContract(gears);
1168
1242
  const controller = isControllerMachine(config);
1169
- const captainBindings = enumerateCaptainBindings(config);
1243
+ const captainBindings = enumerateCaptainBindings(config).map((binding) => ({
1244
+ ...binding,
1245
+ state: {
1246
+ ...binding.state,
1247
+ sourceItem: citation.resolve(binding.state.sourceItem),
1248
+ },
1249
+ }));
1170
1250
  const states = captainBindings.map(({ state }) => state);
1171
1251
  const controllerNearMisses = captainBindings.flatMap(({ state, pinActor }) => {
1172
1252
  if (!pinActor ||
@@ -1182,7 +1262,10 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1182
1262
  .filter(({ pinActor }) => pinActor)
1183
1263
  .map(({ state }) => state));
1184
1264
  const playbookBindings = enumeratePlaybookBindings(config);
1185
- const playbookStates = playbookBindings.map(({ state }) => state);
1265
+ const playbookStates = playbookBindings.map(({ state }) => state.sourceItem === undefined
1266
+ ? state
1267
+ : { ...state, sourceItem: citation.resolve(state.sourceItem) });
1268
+ const playbookBindingOf = new Map(playbookStates.map((state, index) => [state, playbookBindings[index]]));
1186
1269
  const initialContext = initialMachineContext(config);
1187
1270
  const literalChecks = new Map();
1188
1271
  const literalFinding = (item, state) => {
@@ -1190,7 +1273,7 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1190
1273
  if (checked === undefined)
1191
1274
  literalChecks.set(state, (checked = new Map()));
1192
1275
  if (!checked.has(item.prompt)) {
1193
- const binding = playbookBindings.find((candidate) => candidate.state === state);
1276
+ const binding = playbookBindingOf.get(state);
1194
1277
  checked.set(item.prompt, binding === undefined
1195
1278
  ? 'has no inspectable invocation'
1196
1279
  : reached === undefined
@@ -1199,8 +1282,11 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1199
1282
  }
1200
1283
  return checked.get(item.prompt);
1201
1284
  };
1202
- const scriptStates = enumerateScriptStates(config);
1203
- const findings = [];
1285
+ const scriptStates = enumerateScriptStates(config).map((state) => ({
1286
+ ...state,
1287
+ sourceItem: citation.resolve(state.sourceItem),
1288
+ }));
1289
+ const findings = [...citation.findings];
1204
1290
  if (typeof config.meta === 'object' &&
1205
1291
  config.meta !== null &&
1206
1292
  Object.hasOwn(config.meta, 'playbook')) {
@@ -1335,11 +1421,17 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1335
1421
  candidate.playbookIdContext === undefined &&
1336
1422
  candidate.playbookId === item.playbookId &&
1337
1423
  // Unproved pairs cannot establish sourceItem-less one-to-one binding.
1338
- literalPlaybookTextFinding(item.prompt, playbookBindings.find((binding) => binding.state === candidate), initialContext) === undefined);
1424
+ literalPlaybookTextFinding(item.prompt, playbookBindingOf.get(candidate), initialContext) === undefined);
1339
1425
  if (state !== undefined)
1340
1426
  addPlaybookMatch(item, state);
1341
1427
  }
1342
1428
  for (const item of items) {
1429
+ if (isDeclarativeItem(item)) {
1430
+ // A requirement or test item maps to no leaf; only machine syntax that
1431
+ // belongs to an action is a finding (DR-065).
1432
+ findings.push(...declarativeItemFindings(item));
1433
+ continue;
1434
+ }
1343
1435
  if (isPlaybookItem(item)) {
1344
1436
  const matched = playbookMatchesByItem.get(item) ?? [];
1345
1437
  if (matched.length === 0) {
@@ -1442,6 +1534,8 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1442
1534
  }
1443
1535
  }
1444
1536
  const itemIds = new Set(items.map((item) => item.id));
1537
+ const declarativeItemIds = new Set(items.filter(isDeclarativeItem).map((item) => item.id));
1538
+ const declarativeCitation = (kind, state, id) => `${kind} ${state.stateId} cites declarative GEARS item ${id}, which has no \`Captain shall\` acting clause`;
1445
1539
  const playbookItemIds = new Set(playbookItems.map((item) => item.id));
1446
1540
  const scriptItemIds = new Set(items.filter((item) => item.actor === 'script').map((item) => item.id));
1447
1541
  for (const state of scriptStates) {
@@ -1450,6 +1544,9 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1450
1544
  if (!itemIds.has(state.sourceItem)) {
1451
1545
  findings.push(`FSM script state ${state.stateId} references unknown GEARS item ${state.sourceItem}`);
1452
1546
  }
1547
+ else if (declarativeItemIds.has(state.sourceItem)) {
1548
+ findings.push(declarativeCitation('FSM script state', state, state.sourceItem));
1549
+ }
1453
1550
  else if (!scriptItemIds.has(state.sourceItem)) {
1454
1551
  findings.push(`FSM script state ${state.stateId} realizes non-script GEARS item ${state.sourceItem}`);
1455
1552
  }
@@ -1458,6 +1555,9 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1458
1555
  if (state.sourceItem !== '' && !itemIds.has(state.sourceItem)) {
1459
1556
  findings.push(`FSM state ${state.stateId} references unknown GEARS item ${state.sourceItem}`);
1460
1557
  }
1558
+ else if (declarativeItemIds.has(state.sourceItem)) {
1559
+ findings.push(declarativeCitation('FSM state', state, state.sourceItem));
1560
+ }
1461
1561
  const bossReply = state.result[NEEDS_BOSS_REPLY];
1462
1562
  if (controller) {
1463
1563
  if (bossReply !== undefined) {
@@ -1483,6 +1583,10 @@ function gearsFsmConformance(gears, config, options = {}, reached) {
1483
1583
  findings.push(`FSM playbook state ${state.stateId} maps to ${matchedItems.length} GEARS playbook-call items (expected exactly one: ${matchedItems.join(', ')})`);
1484
1584
  }
1485
1585
  if (state.sourceItem !== undefined &&
1586
+ declarativeItemIds.has(state.sourceItem)) {
1587
+ findings.push(declarativeCitation('FSM playbook state', state, state.sourceItem));
1588
+ }
1589
+ else if (state.sourceItem !== undefined &&
1486
1590
  !playbookItemIds.has(state.sourceItem)) {
1487
1591
  findings.push(`FSM playbook state ${state.stateId} references unknown GEARS playbook item ${state.sourceItem}`);
1488
1592
  }
@@ -2675,6 +2779,10 @@ function literalScalarContext(base, values, reads, virtualPresence = true, captu
2675
2779
  };
2676
2780
  return { context: wrap(base, [], new Set()), failure: () => failure };
2677
2781
  }
2782
+ /** One diagnostic for every unproved expanded composition (verification-39). */
2783
+ const UNPROVED_CHILD_COMPOSITION = 'could not prove the complete expanded GEARS child-input composition; check literal text, relay substitution/quoting/omission, canonical compact JSON for structured relays, and comma-joined string lists';
2784
+ /** One invocation rendered an empty labelled relay line both ways (DR-067). */
2785
+ const MIXED_EMPTY_LABELLED_RELAYS = 'mixes kept and omitted empty labelled child-input relay lines';
2678
2786
  /** Verify the FSM-owned composer; child inputs reach the bridge already rendered. */
2679
2787
  function literalPlaybookTextFinding(prompt, binding, initial, unproved) {
2680
2788
  const input = binding.invoke.input;
@@ -2739,7 +2847,7 @@ function literalPlaybookTextFinding(prompt, binding, initial, unproved) {
2739
2847
  const matched = matchPromptBody(prompt, text, [...fields]);
2740
2848
  if (matched === null || matched.index !== 0 || matched.end !== text.length) {
2741
2849
  unproved?.();
2742
- return 'could not prove the complete expanded GEARS child-input composition; check literal text, relay substitution/quoting/omission, and canonical compact JSON for structured relays';
2850
+ return UNPROVED_CHILD_COMPOSITION;
2743
2851
  }
2744
2852
  const tokens = [...prompt.matchAll(PLACEHOLDER)].map((match) => match[0]);
2745
2853
  const mapping = new Map();
@@ -2807,22 +2915,40 @@ function literalPlaybookTextFinding(prompt, binding, initial, unproved) {
2807
2915
  }
2808
2916
  return undefined;
2809
2917
  }
2810
- /** Exact whole-template renderer shared by initial and reached-case proofs. */
2811
- function renderLiteralChildTemplate(prompt, mapping, valueOf) {
2918
+ /** A complete relay line of a child-input template, with its separator. */
2919
+ const STANDALONE_RELAY_LINE = /^> (<[^\s<>`]{1,60}>)(?:\r?\n)?$/;
2920
+ const LABELLED_RELAY_LINE = /^> [^<>\r\n]+: (<[^\s<>`]{1,60}>)(?:\r?\n)?$/;
2921
+ /** Exact whole-template renderer shared by initial and reached-case proofs.
2922
+ * An empty standalone relay line is always omitted; an empty labelled one is
2923
+ * kept with its label, or omitted too where a reached invocation does so. */
2924
+ function renderLiteralChildTemplate(prompt, mapping, valueOf, omitEmptyLabels = false) {
2812
2925
  if ([...mapping.values()].some((field) => {
2813
2926
  const value = valueOf(field);
2814
2927
  return value !== undefined && typeof value !== 'string';
2815
2928
  }))
2816
2929
  return undefined;
2817
- const template = prompt
2818
- .split(/(?<=\n)/)
2819
- .filter((line) => {
2820
- const token = /^> (<[^\s<>`]{1,60}>)(?:\r?\n)?$/.exec(line)?.[1];
2930
+ const empty = (token) => {
2821
2931
  const field = token === undefined ? undefined : mapping.get(token);
2822
- return (field === undefined ||
2823
- (valueOf(field) !== undefined && valueOf(field) !== ''));
2824
- })
2825
- .join('');
2932
+ return (field !== undefined &&
2933
+ (valueOf(field) === undefined || valueOf(field) === ''));
2934
+ };
2935
+ // Whether a labelled line is omitted after the last line kept with content.
2936
+ let trailing = false;
2937
+ const kept = prompt.split(/(?<=\n)/).filter((line) => {
2938
+ if (empty(STANDALONE_RELAY_LINE.exec(line)?.[1]))
2939
+ return false;
2940
+ if (omitEmptyLabels && empty(LABELLED_RELAY_LINE.exec(line)?.[1])) {
2941
+ trailing = true;
2942
+ return false;
2943
+ }
2944
+ if (!/^\r?\n$/.test(line))
2945
+ trailing = false;
2946
+ return true;
2947
+ });
2948
+ // The blank lines such an omission leaves at the end go with it (DR-067).
2949
+ const template = trailing
2950
+ ? kept.join('').replace(/(?:\r?\n)+$/, '')
2951
+ : kept.join('');
2826
2952
  return template.replace(PLACEHOLDER, (token, offset) => {
2827
2953
  const field = mapping.get(token);
2828
2954
  if (field === undefined)
@@ -2833,8 +2959,12 @@ function renderLiteralChildTemplate(prompt, mapping, valueOf) {
2833
2959
  : value;
2834
2960
  });
2835
2961
  }
2836
- /** A finite provisional match. Omitted lines never constitute mapping evidence. */
2837
- function reachedTemplateMatch(prompt, text, payloads, fixed) {
2962
+ /** A finite provisional match. Omitted lines never constitute mapping evidence.
2963
+ * With `omitLabels`, a labelled relay line may be absent as a standalone one
2964
+ * may, and the text may end where only blank lines and absent relay lines, one
2965
+ * of them labelled, follow a line's content (DR-067). The exact rendering is
2966
+ * decided by the reached-case validation, never by this match. */
2967
+ function reachedTemplateMatch(prompt, text, payloads, fixed, omitLabels = false) {
2838
2968
  const parts = [];
2839
2969
  for (const line of prompt.split(/(?<=\n)/)) {
2840
2970
  const chunk = [];
@@ -2844,12 +2974,15 @@ function reachedTemplateMatch(prompt, text, payloads, fixed) {
2844
2974
  chunk.push({ token: match[0], quoted: line.startsWith('> ') });
2845
2975
  offset = match.index + match[0].length;
2846
2976
  }
2847
- chunk.push({ literal: line.slice(offset) });
2848
- if (/^> <[^\s<>`]{1,60}>(?:\r?\n)?$/.test(line))
2849
- parts.push({ optional: chunk });
2977
+ chunk.push({ literal: line.slice(offset), blank: /^\r?\n$/.test(line) });
2978
+ if (STANDALONE_RELAY_LINE.test(line))
2979
+ parts.push({ optional: chunk, labelled: false });
2980
+ else if (omitLabels && LABELLED_RELAY_LINE.test(line))
2981
+ parts.push({ optional: chunk, labelled: true });
2850
2982
  else
2851
2983
  parts.push(...chunk);
2852
2984
  }
2985
+ const droppedTail = (rest) => rest.every((part) => 'optional' in part || ('literal' in part && part.blank)) && rest.some((part) => 'optional' in part && part.labelled);
2853
2986
  let attempts = 0;
2854
2987
  const walk = (remaining, offset, values) => {
2855
2988
  if (++attempts > 4096)
@@ -2857,10 +2990,18 @@ function reachedTemplateMatch(prompt, text, payloads, fixed) {
2857
2990
  if (remaining.length === 0)
2858
2991
  return offset === text.length ? values : undefined;
2859
2992
  const [part, ...rest] = remaining;
2860
- if ('literal' in part)
2861
- return text.startsWith(part.literal, offset)
2862
- ? walk(rest, offset + part.literal.length, values)
2993
+ if ('literal' in part) {
2994
+ if (text.startsWith(part.literal, offset))
2995
+ return walk(rest, offset + part.literal.length, values);
2996
+ const content = part.literal.replace(/\r?\n$/, '');
2997
+ return !part.blank &&
2998
+ content !== part.literal &&
2999
+ text.length === offset + content.length &&
3000
+ text.endsWith(content) &&
3001
+ droppedTail(rest)
3002
+ ? values
2863
3003
  : undefined;
3004
+ }
2864
3005
  if ('optional' in part)
2865
3006
  return (walk([...part.optional, ...rest], offset, values) ??
2866
3007
  walk(rest, offset, values));
@@ -2881,7 +3022,8 @@ function reachedTemplateMatch(prompt, text, payloads, fixed) {
2881
3022
  }
2882
3023
  return undefined;
2883
3024
  };
2884
- return walk(parts, 0, new Map());
3025
+ return (walk(parts, 0, new Map()) ??
3026
+ (text === '' && droppedTail(parts) ? new Map() : undefined));
2885
3027
  }
2886
3028
  function literalPathValue(context, field, records) {
2887
3029
  let value = context;
@@ -3035,7 +3177,10 @@ function literalJsonGraph(context, fields, records, mutation) {
3035
3177
  const encodedValues = new Map();
3036
3178
  for (const key of dataKeys) {
3037
3179
  const descriptor = descriptors[key];
3038
- const item = mutation?.owner === value && mutation.key === key
3180
+ const item = mutation !== undefined &&
3181
+ 'key' in mutation &&
3182
+ mutation.owner === value &&
3183
+ mutation.key === key
3039
3184
  ? mutation.value
3040
3185
  : descriptor.value;
3041
3186
  const child = visit(item, seen, depth + 1);
@@ -3045,6 +3190,25 @@ function literalJsonGraph(context, fields, records, mutation) {
3045
3190
  result.leaves.push({ owner: value, key });
3046
3191
  result.leaves.push(...child.leaves);
3047
3192
  }
3193
+ let length = dataKeys.length;
3194
+ if (array &&
3195
+ mutation !== undefined &&
3196
+ 'append' in mutation &&
3197
+ mutation.owner === value) {
3198
+ // A synthetic last element exists only on the copy and is no leaf of
3199
+ // the reached list; the encoding bound below still covers it.
3200
+ const key = String(length++);
3201
+ const last = dataKeys.at(-1);
3202
+ Object.defineProperty(clone, key, {
3203
+ enumerable: true,
3204
+ configurable: true,
3205
+ writable: true,
3206
+ ...(last === undefined ? {} : descriptors[last]),
3207
+ value: mutation.append,
3208
+ });
3209
+ encodedValues.set(key, mutation.append);
3210
+ dataKeys = [...dataKeys, key];
3211
+ }
3048
3212
  // Preserve control enumeration; sorting belongs only to the JSON copy.
3049
3213
  for (const key of [...dataKeys].sort())
3050
3214
  Object.defineProperty(encoded, key, {
@@ -3054,7 +3218,10 @@ function literalJsonGraph(context, fields, records, mutation) {
3054
3218
  writable: true,
3055
3219
  });
3056
3220
  if (array)
3057
- Object.defineProperty(clone, 'length', descriptors.length);
3221
+ Object.defineProperty(clone, 'length', {
3222
+ ...descriptors.length,
3223
+ value: length,
3224
+ });
3058
3225
  if (!Object.isExtensible(value))
3059
3226
  Object.preventExtensions(clone);
3060
3227
  boundedText(encoded);
@@ -3068,10 +3235,12 @@ function literalJsonGraph(context, fields, records, mutation) {
3068
3235
  continue;
3069
3236
  const copied = visit(original, new Set(), 0);
3070
3237
  const leaves = copied.leaves.filter((leaf, index, all) => all.findIndex((other) => other.owner === leaf.owner && other.key === leaf.key) === index);
3238
+ const list = literalStringListText(copied.value);
3071
3239
  values.set(field, {
3072
3240
  value: copied.value,
3073
3241
  text: boundedText(copied.encoded),
3074
3242
  leaves,
3243
+ ...(list === undefined ? {} : { list }),
3075
3244
  });
3076
3245
  }
3077
3246
  for (const [record, descriptors] of captured)
@@ -3083,10 +3252,43 @@ function literalJsonGraph(context, fields, records, mutation) {
3083
3252
  return undefined;
3084
3253
  }
3085
3254
  }
3255
+ /** Read the detached copy's own data only; no array method or hook is run. */
3256
+ function literalStringListText(value) {
3257
+ if (!Array.isArray(value))
3258
+ return undefined;
3259
+ let text = '';
3260
+ for (let index = 0; index < value.length; index++) {
3261
+ const item = Object.getOwnPropertyDescriptor(value, index)?.value;
3262
+ if (typeof item !== 'string')
3263
+ return undefined;
3264
+ text += index === 0 ? item : `, ${item}`;
3265
+ }
3266
+ return text;
3267
+ }
3086
3268
  function literalJsonUnchanged(facts) {
3087
3269
  return [...facts].every(([value, before]) => Object.getPrototypeOf(value) === before.prototype &&
3088
3270
  Object.isExtensible(value) === before.extensible);
3089
3271
  }
3272
+ /** A mapped structure's rendering: joined elements for a list, else JSON. */
3273
+ function reachedRelayText(work, field, graph) {
3274
+ const value = graph?.values.get(field);
3275
+ return work.lists.has(field) ? value?.list : value?.text;
3276
+ }
3277
+ /** The unmapped tokens a case leaves empty where an observed, unmapped empty
3278
+ * list may stand, or none. Waiting is never evidence: a pending case is
3279
+ * validated later, and only with each such token mapped to its empty list. */
3280
+ function awaitsReachedList(work, text, graph, valueOf) {
3281
+ const mapped = new Set(work.mapping.values());
3282
+ if (![...(graph?.values ?? [])].some(([field, value]) => value.list !== undefined &&
3283
+ value.leaves.length === 0 &&
3284
+ !mapped.has(field)))
3285
+ return [];
3286
+ const matched = reachedTemplateMatch(work.item.prompt, text, [''], new Map([...work.mapping].map(([token, field]) => [
3287
+ token,
3288
+ String(valueOf(field) ?? ''),
3289
+ ])), work.emptyLabels !== 'kept');
3290
+ return [...(matched ?? [])].flatMap(([token, value]) => value === '' && !work.mapping.has(token) ? [token] : []);
3291
+ }
3090
3292
  /** Invocation object identity prevents evidence sharing between sibling calls. */
3091
3293
  export class ReachedLiteralChildChecks {
3092
3294
  work = new Map();
@@ -3104,6 +3306,7 @@ export class ReachedLiteralChildChecks {
3104
3306
  original: finding,
3105
3307
  mapping: new Map(),
3106
3308
  structured: new Set(),
3309
+ lists: new Set(),
3107
3310
  validated: false,
3108
3311
  cases: [],
3109
3312
  });
@@ -3170,10 +3373,10 @@ export class ReachedLiteralChildChecks {
3170
3373
  return;
3171
3374
  }
3172
3375
  const structured = literalJsonGraph(context, structures, records);
3173
- const fieldText = (field, graph = structured) => work.structured.has(field)
3376
+ const fieldText = (field, graph = structured) => work.structured.has(field) || work.lists.has(field)
3174
3377
  ? literalPathValue(context, field, records) === undefined
3175
3378
  ? undefined
3176
- : (graph?.values.get(field)?.text ?? null)
3379
+ : (reachedRelayText(work, field, graph) ?? null)
3177
3380
  : literalPathValue(context, field, records);
3178
3381
  const payloads = [...fields].flatMap((field) => {
3179
3382
  const value = literalPathValue(context, field, records);
@@ -3183,22 +3386,33 @@ export class ReachedLiteralChildChecks {
3183
3386
  ? [value]
3184
3387
  : [];
3185
3388
  });
3186
- payloads.push(...[...(structured?.values.values() ?? [])].map((value) => value.text));
3389
+ payloads.push(...[...(structured?.values.values() ?? [])].map((value) => value.text),
3390
+ // A string list fills a slot as its joined elements, the empty list as
3391
+ // the empty string. A provisional candidate is never mapping evidence.
3392
+ ...[...(structured?.values.values() ?? [])].flatMap((value) => value.list ?? []));
3187
3393
  const influences = new Set();
3188
- const acceptMapping = (token, field, json) => {
3394
+ const acceptMapping = (token, field, kind) => {
3189
3395
  const previous = work.mapping.get(token);
3190
3396
  if (previous === undefined && work.validated) {
3191
3397
  work.failure = `has an unproved late context substitution for ${token}`;
3192
3398
  return false;
3193
3399
  }
3194
- if (previous !== undefined &&
3195
- (previous !== field || work.structured.has(field) !== json)) {
3400
+ const known = work.structured.has(field)
3401
+ ? 'json'
3402
+ : work.lists.has(field)
3403
+ ? 'list'
3404
+ : 'scalar';
3405
+ if ((previous !== undefined && (previous !== field || known !== kind)) ||
3406
+ // One field is relayed as canonical JSON or as a joined list, never both.
3407
+ (known !== 'scalar' && kind !== 'scalar' && known !== kind)) {
3196
3408
  work.failure = `uses inconsistent context substitutions for ${token}`;
3197
3409
  return false;
3198
3410
  }
3199
3411
  work.mapping.set(token, field);
3200
- if (json)
3412
+ if (kind === 'json')
3201
3413
  work.structured.add(field);
3414
+ if (kind === 'list')
3415
+ work.lists.add(field);
3202
3416
  influences.add(field);
3203
3417
  return true;
3204
3418
  };
@@ -3223,8 +3437,17 @@ export class ReachedLiteralChildChecks {
3223
3437
  const result = invocationInput(binding.invoke, literalScalarContext(context, {}, undefined, false, undefined, undefined, variant.aliases).context);
3224
3438
  if (!('value' in result) ||
3225
3439
  typeof result.value.text !== 'string' ||
3226
- result.value.text === actual.text ||
3227
- !result.value.text.includes(encoded))
3440
+ result.value.text === actual.text)
3441
+ continue;
3442
+ // Canonical JSON is tried first. Only a text not carrying it may relay a
3443
+ // list of strings as its elements joined by `, ` (DR-066).
3444
+ const joined = result.value.text.includes(encoded)
3445
+ ? undefined
3446
+ : value.list === undefined
3447
+ ? undefined
3448
+ : variant.values.get(field)?.list;
3449
+ if (!result.value.text.includes(encoded) &&
3450
+ (joined === undefined || !result.value.text.includes(joined)))
3228
3451
  continue;
3229
3452
  if (result.value.stateId !== binding.state.stateId ||
3230
3453
  result.value.playbookId !== binding.state.playbookId ||
@@ -3236,30 +3459,35 @@ export class ReachedLiteralChildChecks {
3236
3459
  token,
3237
3460
  String(fieldText(mapped, variant) ?? ''),
3238
3461
  ]));
3462
+ const relayed = joined ?? encoded;
3239
3463
  const matched = reachedTemplateMatch(item.prompt, result.value.text, [
3240
- encoded,
3464
+ relayed,
3241
3465
  ...payloads,
3242
3466
  ...[...variant.values.values()].map((value) => value.text),
3243
- ], fixed);
3467
+ ...(joined === undefined
3468
+ ? []
3469
+ : [...variant.values.values()].flatMap((value) => value.list ?? [])),
3470
+ ], fixed, work.emptyLabels !== 'kept');
3244
3471
  if (matched === undefined) {
3245
- work.failure =
3246
- 'could not prove the complete expanded GEARS child-input composition; check literal text, relay substitution/quoting/omission, and canonical compact JSON for structured relays';
3472
+ work.failure = UNPROVED_CHILD_COMPOSITION;
3247
3473
  return;
3248
3474
  }
3249
3475
  for (const [token, text] of matched) {
3250
- if (text !== encoded)
3476
+ if (text !== relayed)
3251
3477
  continue;
3252
- if (!quotedRelays.has(token)) {
3478
+ if (joined === undefined && !quotedRelays.has(token)) {
3253
3479
  work.failure = `has unsupported structured inline substitution for ${token}`;
3254
3480
  return;
3255
3481
  }
3256
- if (!acceptMapping(token, field, true))
3482
+ if (!acceptMapping(token, field, joined === undefined ? 'json' : 'list'))
3257
3483
  return;
3258
3484
  }
3259
3485
  }
3260
3486
  for (const field of fields) {
3261
3487
  const marker = sentinelFor(field);
3262
- const candidate = literalScalarContext(context, { [field]: marker }, undefined, false, undefined, undefined, work.structured.size > 0 ? structured?.aliases : undefined);
3488
+ const candidate = literalScalarContext(context, { [field]: marker }, undefined, false, undefined, undefined, work.structured.size + work.lists.size > 0
3489
+ ? structured?.aliases
3490
+ : undefined);
3263
3491
  const result = invocationInput(binding.invoke, candidate.context);
3264
3492
  if (candidate.failure() !== undefined ||
3265
3493
  !('value' in result) ||
@@ -3278,16 +3506,15 @@ export class ReachedLiteralChildChecks {
3278
3506
  token,
3279
3507
  mapped === field ? marker : String(fieldText(mapped) ?? ''),
3280
3508
  ]));
3281
- const matched = reachedTemplateMatch(item.prompt, text, [marker, ...payloads], fixed);
3509
+ const matched = reachedTemplateMatch(item.prompt, text, [marker, ...payloads], fixed, work.emptyLabels !== 'kept');
3282
3510
  if (matched === undefined) {
3283
- work.failure =
3284
- 'could not prove the complete expanded GEARS child-input composition; check literal text, relay substitution/quoting/omission, and canonical compact JSON for structured relays';
3511
+ work.failure = UNPROVED_CHILD_COMPOSITION;
3285
3512
  return;
3286
3513
  }
3287
3514
  for (const [token, value] of matched) {
3288
3515
  if (value !== marker)
3289
3516
  continue;
3290
- if (!acceptMapping(token, field, false))
3517
+ if (!acceptMapping(token, field, 'scalar'))
3291
3518
  return;
3292
3519
  }
3293
3520
  }
@@ -3305,6 +3532,7 @@ export class ReachedLiteralChildChecks {
3305
3532
  structures,
3306
3533
  jsonFacts,
3307
3534
  records,
3535
+ awaited: new Set(),
3308
3536
  });
3309
3537
  if (!this.mapped(work))
3310
3538
  return;
@@ -3326,24 +3554,67 @@ export class ReachedLiteralChildChecks {
3326
3554
  return;
3327
3555
  }
3328
3556
  const graph = literalJsonGraph(reached.context, reached.structures, reached.records);
3329
- const render = (values, json = graph) => renderLiteralChildTemplate(item.prompt, work.mapping, (field) => Object.hasOwn(values, field)
3557
+ const reachedValue = (field, json = graph) => work.structured.has(field) || work.lists.has(field)
3558
+ ? literalPathValue(reached.context, field, reached.records) ===
3559
+ undefined
3560
+ ? undefined
3561
+ : (reachedRelayText(work, field, json) ?? null)
3562
+ : literalPathValue(reached.context, field, reached.records);
3563
+ const render = (values, json, omitEmptyLabels) => renderLiteralChildTemplate(item.prompt, work.mapping, (field) => Object.hasOwn(values, field)
3330
3564
  ? values[field]
3331
- : work.structured.has(field)
3332
- ? literalPathValue(reached.context, field, reached.records) ===
3333
- undefined
3334
- ? undefined
3335
- : (json?.values.get(field)?.text ?? null)
3336
- : literalPathValue(reached.context, field, reached.records));
3337
- const expected = render({});
3565
+ : reachedValue(field, json), omitEmptyLabels);
3566
+ // One invocation keeps every empty labelled relay line or omits every
3567
+ // one (DR-067). The first text the two renderings tell apart fixes
3568
+ // which; a later text that follows the other one is a mixture.
3569
+ const owed = (text, values, json = graph) => {
3570
+ const kept = render(values, json, false);
3571
+ const omitted = render(values, json, true);
3572
+ if (kept === omitted)
3573
+ return kept;
3574
+ work.emptyLabels ??=
3575
+ text === omitted ? 'omitted' : text === kept ? 'kept' : undefined;
3576
+ const omits = work.emptyLabels === 'omitted';
3577
+ if (text === (omits ? kept : omitted))
3578
+ work.failure = MIXED_EMPTY_LABELLED_RELAYS;
3579
+ return omits ? omitted : kept;
3580
+ };
3581
+ const expected = owed(reached.text, {});
3582
+ if (work.failure !== undefined)
3583
+ return;
3338
3584
  if (expected === undefined || reached.text !== expected) {
3339
- work.failure =
3340
- 'could not prove the complete expanded GEARS child-input composition; check literal text, relay substitution/quoting/omission, and canonical compact JSON for structured relays';
3585
+ // An empty list establishes no mapping. Before any proof, its case
3586
+ // stays pending for a nonempty reached list, which then validates it.
3587
+ const awaited = expected === undefined || work.validated
3588
+ ? []
3589
+ : awaitsReachedList(work, reached.text, graph, reachedValue);
3590
+ for (const token of awaited)
3591
+ reached.awaited.add(token);
3592
+ if (awaited.length > 0)
3593
+ return;
3594
+ work.failure = UNPROVED_CHILD_COMPOSITION;
3341
3595
  return;
3342
3596
  }
3597
+ // Waiting was granted to an empty list alone. A token that turned out
3598
+ // to be anything else keeps the finding its case had without the wait.
3599
+ for (const token of reached.awaited) {
3600
+ const field = work.mapping.get(token);
3601
+ const value = field === undefined ? undefined : graph?.values.get(field);
3602
+ if (field === undefined ||
3603
+ !work.lists.has(field) ||
3604
+ value?.list !== '' ||
3605
+ value.leaves.length > 0) {
3606
+ work.failure = UNPROVED_CHILD_COMPOSITION;
3607
+ return;
3608
+ }
3609
+ }
3343
3610
  const verifyPayload = (values, empty) => {
3344
- const candidate = literalScalarContext(reached.context, values, undefined, false, undefined, undefined, work.structured.size > 0 ? graph?.aliases : undefined);
3611
+ const candidate = literalScalarContext(reached.context, values, undefined, false, undefined, undefined, work.structured.size + work.lists.size > 0
3612
+ ? graph?.aliases
3613
+ : undefined);
3345
3614
  const result = invocationInput(binding.invoke, candidate.context);
3346
- const expected = render(values);
3615
+ const expected = owed('value' in result ? result.value.text : undefined, values);
3616
+ if (work.failure !== undefined)
3617
+ return false;
3347
3618
  if (candidate.failure() === undefined &&
3348
3619
  'value' in result &&
3349
3620
  result.value.stateId === binding.state.stateId &&
@@ -3365,7 +3636,8 @@ export class ReachedLiteralChildChecks {
3365
3636
  };
3366
3637
  const activeFields = [...new Set(work.mapping.values())].filter((field) => reached.influences.has(field));
3367
3638
  for (const field of new Set(work.mapping.values())) {
3368
- if (!work.structured.has(field))
3639
+ const list = work.lists.has(field);
3640
+ if (!list && !work.structured.has(field))
3369
3641
  continue;
3370
3642
  const value = graph?.values.get(field);
3371
3643
  if (value === undefined &&
@@ -3375,30 +3647,49 @@ export class ReachedLiteralChildChecks {
3375
3647
  'has unsupported composition (structured JSON inspection failed)';
3376
3648
  return;
3377
3649
  }
3650
+ const holds = (mutation) => {
3651
+ const variant = literalJsonGraph(reached.context, reached.structures, reached.records, mutation);
3652
+ if (variant === undefined) {
3653
+ work.failure =
3654
+ 'has unsupported composition (structured JSON inspection failed)';
3655
+ return false;
3656
+ }
3657
+ const result = invocationInput(binding.invoke, literalScalarContext(reached.context, {}, undefined, false, undefined, undefined, variant.aliases).context);
3658
+ const expected = owed('value' in result ? result.value.text : undefined, {}, variant);
3659
+ if (work.failure !== undefined)
3660
+ return false;
3661
+ if ('value' in result &&
3662
+ result.value.stateId === binding.state.stateId &&
3663
+ result.value.playbookId === binding.state.playbookId &&
3664
+ result.value.sourceItem === actual.sourceItem &&
3665
+ result.value.text === expected)
3666
+ return true;
3667
+ work.failure = list
3668
+ ? 'does not preserve comma-joined string-list substitutions'
3669
+ : 'does not preserve canonical structured JSON substitutions';
3670
+ return false;
3671
+ };
3672
+ // Every string leaf, hence every element of a list, takes two values.
3378
3673
  for (const leaf of value?.leaves ?? [])
3379
- for (const literal of [
3380
- '«structured» $& <payload>\nsecond',
3381
- '«distinct» " \\ \r\nlast',
3382
- ]) {
3383
- const variant = literalJsonGraph(reached.context, reached.structures, reached.records, { ...leaf, value: literal });
3384
- if (variant === undefined) {
3385
- work.failure =
3386
- 'has unsupported composition (structured JSON inspection failed)';
3674
+ for (const literal of list
3675
+ ? [
3676
+ `«Element» $& $$ $\x60 $' ${[...work.mapping.keys()].join(' ')}`,
3677
+ '«Distinct» " \\ [x]',
3678
+ ]
3679
+ : ['«structured» $& <payload>\nsecond', '«distinct» " \\ \r\nlast'])
3680
+ if (!holds({ ...leaf, value: literal }))
3387
3681
  return;
3388
- }
3389
- const result = invocationInput(binding.invoke, literalScalarContext(reached.context, {}, undefined, false, undefined, undefined, variant.aliases).context);
3390
- if (!('value' in result) ||
3391
- result.value.stateId !== binding.state.stateId ||
3392
- result.value.playbookId !== binding.state.playbookId ||
3393
- result.value.sourceItem !== actual.sourceItem ||
3394
- result.value.text !== render({}, variant)) {
3395
- work.failure =
3396
- 'does not preserve canonical structured JSON substitutions';
3682
+ // Replacing elements never shows what stands between two of them, so
3683
+ // one reached element alone proves no separator, order or selection.
3684
+ // A further last element on the detached copy does, in every case;
3685
+ // its two values sort before and after ordinary text, in mixed case.
3686
+ const elements = list ? value?.leaves[0]?.owner : undefined;
3687
+ if (elements !== undefined)
3688
+ for (const append of ['!Appended " \\ $$', '«Appended» $& [y]'])
3689
+ if (!holds({ owner: elements, append }))
3397
3690
  return;
3398
- }
3399
- }
3400
3691
  }
3401
- const scalarFields = activeFields.filter((field) => !work.structured.has(field));
3692
+ const scalarFields = activeFields.filter((field) => !work.structured.has(field) && !work.lists.has(field));
3402
3693
  // Perturb one mapped payload only: no other reached control/payload changes.
3403
3694
  for (const field of scalarFields) {
3404
3695
  const multiline = item.prompt.split(/\r?\n/).some((line) => {
@@ -3534,7 +3825,7 @@ describe(${sourceString(`${opts.basename}: GEARS↔FSM conformance`)}, () => {
3534
3825
  expect(SCHEMA_FINDINGS).toEqual([]);
3535
3826
  });
3536
3827
 
3537
- it('maps every GEARS item to a state with its player and verbatim prompt', async () => {
3828
+ it('maps every GEARS action item to a state with its actor and preserved prompt', async () => {
3538
3829
  const gears = readFileSync(
3539
3830
  fileURLToPath(new URL(${sourceString(opts.gearsFile)}, import.meta.url)),
3540
3831
  'utf8',
@@ -3588,10 +3879,7 @@ export async function emitGearsFsmConformanceTest(opts) {
3588
3879
  * module cache.
3589
3880
  */
3590
3881
  export async function loadFsmModule(fsmPath) {
3591
- const resolved = resolve(fsmPath);
3592
- const url = pathToFileURL(resolved);
3593
- url.searchParams.set('v', await hashFile(resolved));
3594
- return import(url.href);
3882
+ return importFreshArtifact(resolve(fsmPath));
3595
3883
  }
3596
3884
  /**
3597
3885
  * Imports generated linked TypeScript for emission-time, standalone, or