@sublang/slc 0.16.7 → 0.16.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/verify.js CHANGED
@@ -23,6 +23,7 @@ import { existsSync } from 'node:fs';
23
23
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
24
24
  import { basename, dirname, join, resolve } from 'node:path';
25
25
  import { pathToFileURL } from 'node:url';
26
+ import { types as nodeTypes } from 'node:util';
26
27
  import { hashFile } from './hash.js';
27
28
  /**
28
29
  * The Boss-reply result key `gears2fsm` adds to every captain-invoking state's
@@ -1048,6 +1049,18 @@ function statePlaybookSignature(state) {
1048
1049
  state.textContext ?? null,
1049
1050
  ]);
1050
1051
  }
1052
+ /** Conservative synchronous check; no reached-context evidence is assumed. */
1053
+ export function checkGearsFsmConformance(gears, config, options = {}) {
1054
+ return gearsFsmConformance(gears, config, options);
1055
+ }
1056
+ /** Structural findings plus binding-local work for the shared bounded replay. */
1057
+ export function prepareGearsFsmConformance(gears, config, options = {}) {
1058
+ const literalChecks = new ReachedLiteralChildChecks();
1059
+ return {
1060
+ findings: gearsFsmConformance(gears, config, options, literalChecks),
1061
+ literalChecks,
1062
+ };
1063
+ }
1051
1064
  /** Exact action guards of Playbook 10's controller decision result. */
1052
1065
  export const CONTROLLER_ACTION_GUARDS = [
1053
1066
  'respond',
@@ -1148,7 +1161,7 @@ export function checkFsmChildSuspension(config) {
1148
1161
  * captain state's `result` map declares the Boss-reply suspension key with its
1149
1162
  * adjudicator contract (verification-1, verification-3; DR-009).
1150
1163
  */
1151
- export function checkGearsFsmConformance(gears, config, options = {}) {
1164
+ function gearsFsmConformance(gears, config, options = {}, reached) {
1152
1165
  const items = parseGearsItems(gears);
1153
1166
  const roleContract = inspectGearsRoleContract(gears);
1154
1167
  const controller = isControllerMachine(config);
@@ -1179,7 +1192,9 @@ export function checkGearsFsmConformance(gears, config, options = {}) {
1179
1192
  const binding = playbookBindings.find((candidate) => candidate.state === state);
1180
1193
  checked.set(item.prompt, binding === undefined
1181
1194
  ? 'has no inspectable invocation'
1182
- : literalPlaybookTextFinding(item.prompt, binding, initialContext));
1195
+ : reached === undefined
1196
+ ? literalPlaybookTextFinding(item.prompt, binding, initialContext)
1197
+ : reached.check(item, binding, initialContext));
1183
1198
  }
1184
1199
  return checked.get(item.prompt);
1185
1200
  };
@@ -1318,7 +1333,8 @@ export function checkGearsFsmConformance(gears, config, options = {}) {
1318
1333
  !matchedPlaybookStates.has(candidate) &&
1319
1334
  candidate.playbookIdContext === undefined &&
1320
1335
  candidate.playbookId === item.playbookId &&
1321
- literalFinding(item, candidate) === undefined);
1336
+ // Unproved pairs cannot establish sourceItem-less one-to-one binding.
1337
+ literalPlaybookTextFinding(item.prompt, playbookBindings.find((binding) => binding.state === candidate), initialContext) === undefined);
1322
1338
  if (state !== undefined)
1323
1339
  addPlaybookMatch(item, state);
1324
1340
  }
@@ -2441,13 +2457,19 @@ function boundedJsonSnippet(value, offset) {
2441
2457
  }
2442
2458
  /** Literal-child probes keep record containers and observe scalar paths only.
2443
2459
  * Virtual absent leaves do not add keys to unrelated typed records. */
2444
- function literalScalarContext(base, values, reads) {
2460
+ function literalScalarContext(base, values, reads, virtualPresence = true, capture, structures, aliases, captureStructure) {
2445
2461
  let failure;
2462
+ const wrapped = new Map();
2446
2463
  const isRecord = (value) => typeof value === 'object' &&
2447
2464
  value !== null &&
2465
+ !nodeTypes.isProxy(value) &&
2448
2466
  (Object.getPrototypeOf(value) === Object.prototype ||
2449
2467
  Object.getPrototypeOf(value) === null);
2450
2468
  const wrap = (record, path, ancestors) => {
2469
+ if (nodeTypes.isProxy(record)) {
2470
+ failure ??= 'proxy record';
2471
+ return {};
2472
+ }
2451
2473
  if (path.length > 32 || ancestors.has(record)) {
2452
2474
  failure ??=
2453
2475
  path.length > 32
@@ -2455,6 +2477,10 @@ function literalScalarContext(base, values, reads) {
2455
2477
  : 'cyclic record reads';
2456
2478
  return record;
2457
2479
  }
2480
+ const prior = wrapped.get(record);
2481
+ if (prior !== undefined)
2482
+ return prior;
2483
+ capture?.(record);
2458
2484
  const seen = new Set([...ancestors, record]);
2459
2485
  const copy = Object.create(Object.getPrototypeOf(record));
2460
2486
  for (const key of Reflect.ownKeys(record)) {
@@ -2463,7 +2489,7 @@ function literalScalarContext(base, values, reads) {
2463
2489
  // source descriptor preventing a nested observational proxy.
2464
2490
  Object.defineProperty(copy, key, { ...descriptor, configurable: true });
2465
2491
  }
2466
- return new Proxy(copy, {
2492
+ const proxy = new Proxy(copy, {
2467
2493
  get(target, property) {
2468
2494
  const value = Reflect.get(target, property);
2469
2495
  if (typeof property !== 'string')
@@ -2475,15 +2501,32 @@ function literalScalarContext(base, values, reads) {
2475
2501
  reads?.add(field);
2476
2502
  if (Object.hasOwn(values, field))
2477
2503
  return values[field];
2504
+ if (value !== null && typeof value === 'object') {
2505
+ if (nodeTypes.isProxy(value)) {
2506
+ failure ??= 'proxy record';
2507
+ return value;
2508
+ }
2509
+ if (Array.isArray(value) || isRecord(value)) {
2510
+ if (structures !== undefined && !structures.has(field)) {
2511
+ structures.add(field);
2512
+ captureStructure?.(field);
2513
+ }
2514
+ }
2515
+ const alias = aliases?.get(value);
2516
+ if (alias !== undefined)
2517
+ return alias;
2518
+ }
2478
2519
  return isRecord(value) ? wrap(value, nested, seen) : value;
2479
2520
  },
2480
- has: () => true,
2521
+ has: (target, property) => virtualPresence || Reflect.has(target, property),
2481
2522
  });
2523
+ wrapped.set(record, proxy);
2524
+ return proxy;
2482
2525
  };
2483
2526
  return { context: wrap(base, [], new Set()), failure: () => failure };
2484
2527
  }
2485
2528
  /** Verify the FSM-owned composer; child inputs reach the bridge already rendered. */
2486
- function literalPlaybookTextFinding(prompt, binding, initial) {
2529
+ function literalPlaybookTextFinding(prompt, binding, initial, unproved) {
2487
2530
  const input = binding.invoke.input;
2488
2531
  // Only explicit quoted relay notation establishes required runtime slots.
2489
2532
  // Domain metavariables and inline-code examples remain literal template text.
@@ -2491,7 +2534,11 @@ function literalPlaybookTextFinding(prompt, binding, initial) {
2491
2534
  const token = /^> (?:[^<>\r\n]+: )?(<[^\s<>`]{1,60}>)$/.exec(line)?.[1];
2492
2535
  return token === undefined ? [] : [token];
2493
2536
  }));
2494
- const unresolvedRelay = (token) => `leaves quoted child-input relay ${token} unresolved`;
2537
+ const unresolvedRelay = (token) => {
2538
+ if (typeof input === 'function')
2539
+ unproved?.();
2540
+ return `leaves quoted child-input relay ${token} unresolved`;
2541
+ };
2495
2542
  if (typeof input !== 'function') {
2496
2543
  if (binding.state.text !== prompt)
2497
2544
  return 'does not preserve the complete GEARS child-input template';
@@ -2535,10 +2582,13 @@ function literalPlaybookTextFinding(prompt, binding, initial) {
2535
2582
  : undefined;
2536
2583
  };
2537
2584
  const text = probe(values);
2538
- if (text === undefined)
2585
+ if (text === undefined) {
2586
+ unproved?.();
2539
2587
  return 'has unsupported composition (input evaluation or literal identity changed)';
2588
+ }
2540
2589
  const matched = matchPromptBody(prompt, text, [...fields]);
2541
2590
  if (matched === null || matched.index !== 0 || matched.end !== text.length) {
2591
+ unproved?.();
2542
2592
  return 'does not preserve the complete GEARS child-input template';
2543
2593
  }
2544
2594
  const tokens = [...prompt.matchAll(PLACEHOLDER)].map((match) => match[0]);
@@ -2576,30 +2626,14 @@ function literalPlaybookTextFinding(prompt, binding, initial) {
2576
2626
  `«${field}:literal» $& $$ $\x60 $' ${[...new Set(tokens)].join(' ')}` +
2577
2627
  (multilineFields.has(field) ? `\n\n«${field}:second»` : ''),
2578
2628
  ]));
2579
- const render = (values) => {
2580
- // Only the source-defined standalone relay form owns empty-line removal.
2581
- const template = prompt
2582
- .split(/(?<=\n)/)
2583
- .filter((line) => {
2584
- const token = /^> (<[^\s<>`]{1,60}>)(?:\r?\n)?$/.exec(line)?.[1];
2585
- const mapped = token === undefined ? undefined : mapping.get(token);
2586
- return mapped === undefined || values[mapped.field] !== '';
2587
- })
2588
- .join('');
2589
- return template.replace(PLACEHOLDER, (token, offset) => {
2590
- const mapped = mapping.get(token);
2591
- if (mapped === undefined)
2592
- return token;
2593
- const value = values[mapped.field];
2594
- const lineStart = template.lastIndexOf('\n', offset - 1) + 1;
2595
- return template.startsWith('> ', lineStart)
2596
- ? value.replace(/\r?\n/g, (separator) => `${separator}> `)
2597
- : value;
2598
- });
2599
- };
2629
+ const fieldMapping = new Map([...mapping].map(([token, { field }]) => [token, field]));
2630
+ const render = (values) => renderLiteralChildTemplate(prompt, fieldMapping, (field) => values[field]);
2600
2631
  const composed = probe(payloads);
2601
2632
  if (composed === undefined || composed !== render(payloads)) {
2602
- return 'does not preserve literal substitutions and quoted continuation lines';
2633
+ return ('does not preserve literal substitutions and quoted continuation lines' +
2634
+ (composed === undefined
2635
+ ? ''
2636
+ : ` (${firstDifferenceDiagnostic(render(payloads), composed)})`));
2603
2637
  }
2604
2638
  const emptyFields = new Set();
2605
2639
  for (const line of prompt.split(/\r?\n/)) {
@@ -2615,11 +2649,644 @@ function literalPlaybookTextFinding(prompt, binding, initial) {
2615
2649
  };
2616
2650
  const emptyText = probe(values);
2617
2651
  if (emptyText === undefined || emptyText !== render(values)) {
2618
- return 'does not preserve source-defined empty standalone relay omission';
2652
+ return ('does not preserve source-defined empty standalone relay omission' +
2653
+ (emptyText === undefined
2654
+ ? ''
2655
+ : ` (${firstDifferenceDiagnostic(render(values), emptyText)})`));
2619
2656
  }
2620
2657
  }
2621
2658
  return undefined;
2622
2659
  }
2660
+ /** Exact whole-template renderer shared by initial and reached-case proofs. */
2661
+ function renderLiteralChildTemplate(prompt, mapping, valueOf) {
2662
+ if ([...mapping.values()].some((field) => {
2663
+ const value = valueOf(field);
2664
+ return value !== undefined && typeof value !== 'string';
2665
+ }))
2666
+ return undefined;
2667
+ const template = prompt
2668
+ .split(/(?<=\n)/)
2669
+ .filter((line) => {
2670
+ const token = /^> (<[^\s<>`]{1,60}>)(?:\r?\n)?$/.exec(line)?.[1];
2671
+ const field = token === undefined ? undefined : mapping.get(token);
2672
+ return (field === undefined ||
2673
+ (valueOf(field) !== undefined && valueOf(field) !== ''));
2674
+ })
2675
+ .join('');
2676
+ return template.replace(PLACEHOLDER, (token, offset) => {
2677
+ const field = mapping.get(token);
2678
+ if (field === undefined)
2679
+ return token;
2680
+ const value = (valueOf(field) ?? '');
2681
+ return template.startsWith('> ', template.lastIndexOf('\n', offset - 1) + 1)
2682
+ ? value.replace(/\r?\n/g, (separator) => `${separator}> `)
2683
+ : value;
2684
+ });
2685
+ }
2686
+ /** A finite provisional match. Omitted lines never constitute mapping evidence. */
2687
+ function reachedTemplateMatch(prompt, text, payloads, fixed) {
2688
+ const parts = [];
2689
+ for (const line of prompt.split(/(?<=\n)/)) {
2690
+ const chunk = [];
2691
+ let offset = 0;
2692
+ for (const match of line.matchAll(PLACEHOLDER)) {
2693
+ chunk.push({ literal: line.slice(offset, match.index) });
2694
+ chunk.push({ token: match[0], quoted: line.startsWith('> ') });
2695
+ offset = match.index + match[0].length;
2696
+ }
2697
+ chunk.push({ literal: line.slice(offset) });
2698
+ if (/^> <[^\s<>`]{1,60}>(?:\r?\n)?$/.test(line))
2699
+ parts.push({ optional: chunk });
2700
+ else
2701
+ parts.push(...chunk);
2702
+ }
2703
+ let attempts = 0;
2704
+ const walk = (remaining, offset, values) => {
2705
+ if (++attempts > 4096)
2706
+ return undefined;
2707
+ if (remaining.length === 0)
2708
+ return offset === text.length ? values : undefined;
2709
+ const [part, ...rest] = remaining;
2710
+ if ('literal' in part)
2711
+ return text.startsWith(part.literal, offset)
2712
+ ? walk(rest, offset + part.literal.length, values)
2713
+ : undefined;
2714
+ if ('optional' in part)
2715
+ return (walk([...part.optional, ...rest], offset, values) ??
2716
+ walk(rest, offset, values));
2717
+ const candidates = values.has(part.token)
2718
+ ? [values.get(part.token)]
2719
+ : fixed.has(part.token)
2720
+ ? [fixed.get(part.token)]
2721
+ : [part.token, ...payloads];
2722
+ for (const value of new Set(candidates)) {
2723
+ const rendered = part.quoted
2724
+ ? value.replace(/\r?\n/g, (separator) => `${separator}> `)
2725
+ : value;
2726
+ if (text.startsWith(rendered, offset)) {
2727
+ const found = walk(rest, offset + rendered.length, new Map([...values, [part.token, value]]));
2728
+ if (found !== undefined)
2729
+ return found;
2730
+ }
2731
+ }
2732
+ return undefined;
2733
+ };
2734
+ return walk(parts, 0, new Map());
2735
+ }
2736
+ function literalPathValue(context, field, records) {
2737
+ let value = context;
2738
+ for (const key of JSON.parse(field)) {
2739
+ if (value !== null && typeof value === 'object' && nodeTypes.isProxy(value))
2740
+ return null;
2741
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
2742
+ return undefined;
2743
+ const captured = records?.get(value);
2744
+ if (records !== undefined && captured === undefined)
2745
+ return null;
2746
+ const descriptor = captured === undefined
2747
+ ? Object.getOwnPropertyDescriptor(value, key)
2748
+ : Object.hasOwn(captured, key)
2749
+ ? captured[key]
2750
+ : undefined;
2751
+ if (descriptor === undefined)
2752
+ return undefined;
2753
+ if (!('value' in descriptor))
2754
+ return null; // An accessor is not absent evidence.
2755
+ value = descriptor.value;
2756
+ }
2757
+ return value;
2758
+ }
2759
+ /** Compare observed descriptor facts, without serializing arbitrary context. */
2760
+ function literalRecordsUnchanged(records) {
2761
+ return [...records].every(([record, before]) => {
2762
+ const keys = Reflect.ownKeys(record);
2763
+ const oldKeys = Reflect.ownKeys(before);
2764
+ return (keys.length === oldKeys.length &&
2765
+ keys.every((key, index) => {
2766
+ if (key !== oldKeys[index])
2767
+ return false;
2768
+ const old = Reflect.get(before, key);
2769
+ const current = Object.getOwnPropertyDescriptor(record, key);
2770
+ return [
2771
+ 'configurable',
2772
+ 'enumerable',
2773
+ 'writable',
2774
+ 'get',
2775
+ 'set',
2776
+ 'value',
2777
+ ].every((field) => Object.is(Reflect.get(old, field), Reflect.get(current, field)));
2778
+ }));
2779
+ });
2780
+ }
2781
+ /** Inspect only observed structured reads. No input accessor or JSON hook is run. */
2782
+ function literalJsonGraph(context, fields, records, mutation) {
2783
+ let nodes = 0;
2784
+ const aliases = new Map();
2785
+ const memo = new Map();
2786
+ const captured = new Map();
2787
+ const facts = new Map();
2788
+ const encodedLengths = new Map();
2789
+ const primitiveText = (value) => {
2790
+ if (typeof value === 'string' && Buffer.byteLength(value, 'utf8') > 65536)
2791
+ throw Error('structured encoding bound');
2792
+ return JSON.stringify(value);
2793
+ };
2794
+ const boundedText = (value) => {
2795
+ // Values here are detached JSON data only. Preflight repeated alias output
2796
+ // before stringify, so a small shared graph cannot expand beyond the cap.
2797
+ let bytes;
2798
+ if (value !== null && typeof value === 'object') {
2799
+ const keys = Object.keys(value);
2800
+ const array = Array.isArray(value);
2801
+ bytes = 2 + Math.max(0, keys.length - 1);
2802
+ for (const key of keys) {
2803
+ const child = Object.getOwnPropertyDescriptor(value, key).value;
2804
+ const size = child !== null && typeof child === 'object'
2805
+ ? encodedLengths.get(child)
2806
+ : Buffer.byteLength(primitiveText(child), 'utf8');
2807
+ if (size === undefined)
2808
+ throw Error('unproved structured encoding');
2809
+ bytes +=
2810
+ size +
2811
+ (array ? 0 : Buffer.byteLength(primitiveText(key), 'utf8') + 1);
2812
+ if (bytes > 65536)
2813
+ throw Error('structured encoding bound');
2814
+ }
2815
+ encodedLengths.set(value, bytes);
2816
+ }
2817
+ else
2818
+ bytes = Buffer.byteLength(primitiveText(value), 'utf8');
2819
+ if (bytes > 65536)
2820
+ throw Error('structured encoding bound');
2821
+ return JSON.stringify(value);
2822
+ };
2823
+ const visit = (value, ancestors, depth) => {
2824
+ if (depth > 32)
2825
+ throw Error('structured depth bound');
2826
+ if (++nodes > 128)
2827
+ throw Error('structured node bound');
2828
+ if (value !== null && typeof value === 'object') {
2829
+ if (nodeTypes.isProxy(value))
2830
+ throw Error('structured proxy');
2831
+ if (ancestors.has(value))
2832
+ throw Error('structured cycle');
2833
+ const prior = memo.get(value);
2834
+ if (prior !== undefined)
2835
+ return prior;
2836
+ }
2837
+ if (value === null ||
2838
+ typeof value === 'boolean' ||
2839
+ typeof value === 'string' ||
2840
+ (typeof value === 'number' && Number.isFinite(value))) {
2841
+ boundedText(value);
2842
+ return { value, encoded: value, leaves: [] };
2843
+ }
2844
+ if (typeof value !== 'object')
2845
+ throw Error('non-JSON structured value');
2846
+ const array = Array.isArray(value);
2847
+ const prototype = Object.getPrototypeOf(value);
2848
+ if (array
2849
+ ? prototype !== Array.prototype
2850
+ : prototype !== Object.prototype && prototype !== null)
2851
+ throw Error('structured prototype');
2852
+ const descriptors = Object.getOwnPropertyDescriptors(value);
2853
+ facts.set(value, { prototype, extensible: Object.isExtensible(value) });
2854
+ const keys = Reflect.ownKeys(descriptors);
2855
+ if (keys.some((key) => typeof key !== 'string'))
2856
+ throw Error('structured symbol key');
2857
+ if (keys.length > 129)
2858
+ throw Error('structured node bound');
2859
+ let dataKeys = keys;
2860
+ if (array) {
2861
+ const length = descriptors.length;
2862
+ if (!length ||
2863
+ !('value' in length) ||
2864
+ !Number.isInteger(length.value) ||
2865
+ length.value < 0 ||
2866
+ length.value > 128)
2867
+ throw Error('structured array length');
2868
+ dataKeys = Array.from({ length: length.value }, (_, index) => String(index));
2869
+ if (keys.length !== dataKeys.length + 1 ||
2870
+ dataKeys.some((key) => !Object.hasOwn(descriptors, key)))
2871
+ throw Error('structured array shape');
2872
+ }
2873
+ if (dataKeys.some((key) => !('value' in descriptors[key]) || !descriptors[key].enumerable))
2874
+ throw Error('structured descriptor');
2875
+ const clone = array ? [] : Object.create(prototype);
2876
+ // The encoding copy has no inherited hooks, including Array.prototype.toJSON.
2877
+ const encoded = array
2878
+ ? Object.setPrototypeOf([], null)
2879
+ : Object.create(null);
2880
+ const result = { value: clone, encoded, leaves: [] };
2881
+ memo.set(value, result);
2882
+ aliases.set(value, clone);
2883
+ captured.set(value, descriptors);
2884
+ const seen = new Set([...ancestors, value]);
2885
+ const encodedValues = new Map();
2886
+ for (const key of dataKeys) {
2887
+ const descriptor = descriptors[key];
2888
+ const item = mutation?.owner === value && mutation.key === key
2889
+ ? mutation.value
2890
+ : descriptor.value;
2891
+ const child = visit(item, seen, depth + 1);
2892
+ Object.defineProperty(clone, key, { ...descriptor, value: child.value });
2893
+ encodedValues.set(key, child.encoded);
2894
+ if (typeof descriptor.value === 'string')
2895
+ result.leaves.push({ owner: value, key });
2896
+ result.leaves.push(...child.leaves);
2897
+ }
2898
+ // Preserve control enumeration; sorting belongs only to the JSON copy.
2899
+ for (const key of [...dataKeys].sort())
2900
+ Object.defineProperty(encoded, key, {
2901
+ value: encodedValues.get(key),
2902
+ enumerable: true,
2903
+ configurable: true,
2904
+ writable: true,
2905
+ });
2906
+ if (array)
2907
+ Object.defineProperty(clone, 'length', descriptors.length);
2908
+ if (!Object.isExtensible(value))
2909
+ Object.preventExtensions(clone);
2910
+ boundedText(encoded);
2911
+ return result;
2912
+ };
2913
+ try {
2914
+ const values = new Map();
2915
+ for (const field of fields) {
2916
+ const original = literalPathValue(context, field, records);
2917
+ if (original === null || typeof original !== 'object')
2918
+ continue;
2919
+ const copied = visit(original, new Set(), 0);
2920
+ const leaves = copied.leaves.filter((leaf, index, all) => all.findIndex((other) => other.owner === leaf.owner && other.key === leaf.key) === index);
2921
+ values.set(field, {
2922
+ value: copied.value,
2923
+ text: boundedText(copied.encoded),
2924
+ leaves,
2925
+ });
2926
+ }
2927
+ for (const [record, descriptors] of captured)
2928
+ if (!records.has(record))
2929
+ records.set(record, descriptors);
2930
+ return { values, aliases, facts };
2931
+ }
2932
+ catch {
2933
+ return undefined;
2934
+ }
2935
+ }
2936
+ function literalJsonUnchanged(facts) {
2937
+ return [...facts].every(([value, before]) => Object.getPrototypeOf(value) === before.prototype &&
2938
+ Object.isExtensible(value) === before.extensible);
2939
+ }
2940
+ /** Invocation object identity prevents evidence sharing between sibling calls. */
2941
+ export class ReachedLiteralChildChecks {
2942
+ work = new Map();
2943
+ check(item, binding, initial) {
2944
+ let unproved = false;
2945
+ const finding = literalPlaybookTextFinding(item.prompt, binding, initial, () => {
2946
+ unproved = true;
2947
+ });
2948
+ if (!unproved || finding === undefined)
2949
+ return finding;
2950
+ if (!this.work.has(binding.invoke))
2951
+ this.work.set(binding.invoke, {
2952
+ item,
2953
+ binding,
2954
+ original: finding,
2955
+ mapping: new Map(),
2956
+ structured: new Set(),
2957
+ validated: false,
2958
+ cases: [],
2959
+ });
2960
+ return undefined;
2961
+ }
2962
+ pending() {
2963
+ return [...this.work.values()].some((work) => work.failure === undefined && !this.proved(work));
2964
+ }
2965
+ needs(invoke) {
2966
+ const work = this.work.get(invoke);
2967
+ return (work !== undefined && work.failure === undefined && !this.proved(work));
2968
+ }
2969
+ proved(work) {
2970
+ return work.validated;
2971
+ }
2972
+ mapped(work) {
2973
+ const required = work.item.prompt
2974
+ .split(/\r?\n/)
2975
+ .flatMap((line) => /^> (?:[^<>\r\n]+: )?(<[^\s<>`]{1,60}>)$/.exec(line)?.[1] ?? []);
2976
+ return (work.cases.length > 0 &&
2977
+ required.every((token) => work.mapping.has(token)));
2978
+ }
2979
+ observe(invoke, context, actual) {
2980
+ const work = this.work.get(invoke);
2981
+ if (work === undefined || work.failure !== undefined)
2982
+ return;
2983
+ const { binding, item } = work;
2984
+ const fields = new Set();
2985
+ const structures = new Set();
2986
+ const records = new Map();
2987
+ const jsonFacts = new Map();
2988
+ const observed = literalScalarContext(context, {}, fields, false, (record) => {
2989
+ if (!records.has(record))
2990
+ records.set(record, Object.getOwnPropertyDescriptors(record));
2991
+ }, structures, undefined, (field) => {
2992
+ const snapshot = literalJsonGraph(context, new Set([field]), records);
2993
+ for (const [value, facts] of snapshot?.facts ?? [])
2994
+ if (!jsonFacts.has(value))
2995
+ jsonFacts.set(value, facts);
2996
+ });
2997
+ const input = invocationInput(binding.invoke, observed.context);
2998
+ if (observed.failure() !== undefined ||
2999
+ new Set([...fields, ...structures]).size > 128) {
3000
+ work.failure =
3001
+ 'has unsupported composition (bounded scalar observation failed)';
3002
+ return;
3003
+ }
3004
+ if (!('value' in input) ||
3005
+ input.value.text !== actual.text ||
3006
+ input.value.stateId !== actual.stateId ||
3007
+ input.value.playbookId !== actual.playbookId ||
3008
+ typeof actual.text !== 'string' ||
3009
+ actual.stateId !== binding.state.stateId ||
3010
+ actual.playbookId !== binding.state.playbookId ||
3011
+ (binding.state.sourceItem !== undefined &&
3012
+ actual.sourceItem !== binding.state.sourceItem)) {
3013
+ work.failure =
3014
+ 'has unsupported composition (reached input or literal identity changed)';
3015
+ return;
3016
+ }
3017
+ if (!literalRecordsUnchanged(records) || !literalJsonUnchanged(jsonFacts)) {
3018
+ work.failure =
3019
+ 'has unsupported composition (observed structured context changed during input)';
3020
+ return;
3021
+ }
3022
+ const structured = literalJsonGraph(context, structures, records);
3023
+ const fieldText = (field, graph = structured) => work.structured.has(field)
3024
+ ? literalPathValue(context, field, records) === undefined
3025
+ ? undefined
3026
+ : (graph?.values.get(field)?.text ?? null)
3027
+ : literalPathValue(context, field, records);
3028
+ const payloads = [...fields].flatMap((field) => {
3029
+ const value = literalPathValue(context, field, records);
3030
+ return value === undefined
3031
+ ? ['']
3032
+ : typeof value === 'string'
3033
+ ? [value]
3034
+ : [];
3035
+ });
3036
+ payloads.push(...[...(structured?.values.values() ?? [])].map((value) => value.text));
3037
+ const influences = new Set();
3038
+ const acceptMapping = (token, field, json) => {
3039
+ const previous = work.mapping.get(token);
3040
+ if (previous === undefined && work.validated) {
3041
+ work.failure = `has an unproved late context substitution for ${token}`;
3042
+ return false;
3043
+ }
3044
+ if (previous !== undefined &&
3045
+ (previous !== field || work.structured.has(field) !== json)) {
3046
+ work.failure = `uses inconsistent context substitutions for ${token}`;
3047
+ return false;
3048
+ }
3049
+ work.mapping.set(token, field);
3050
+ if (json)
3051
+ work.structured.add(field);
3052
+ influences.add(field);
3053
+ return true;
3054
+ };
3055
+ const quotedRelays = new Set(item.prompt
3056
+ .split(/\r?\n/)
3057
+ .flatMap((line) => /^> (?:[^<>\r\n]+: )?(<[^\s<>`]{1,60}>)$/.exec(line)?.[1] ?? []));
3058
+ const probedStructures = new Set();
3059
+ for (const [field, value] of structured?.values ?? []) {
3060
+ if (probedStructures.has(value.value))
3061
+ continue;
3062
+ probedStructures.add(value.value);
3063
+ const leaf = value.leaves[0];
3064
+ if (leaf === undefined)
3065
+ continue;
3066
+ const variant = literalJsonGraph(context, structures, records, {
3067
+ ...leaf,
3068
+ value: sentinelFor(field),
3069
+ });
3070
+ const encoded = variant?.values.get(field)?.text;
3071
+ if (variant === undefined || encoded === undefined)
3072
+ continue;
3073
+ const result = invocationInput(binding.invoke, literalScalarContext(context, {}, undefined, false, undefined, undefined, variant.aliases).context);
3074
+ if (!('value' in result) ||
3075
+ typeof result.value.text !== 'string' ||
3076
+ result.value.text === actual.text ||
3077
+ !result.value.text.includes(encoded))
3078
+ continue;
3079
+ if (result.value.stateId !== binding.state.stateId ||
3080
+ result.value.playbookId !== binding.state.playbookId ||
3081
+ result.value.sourceItem !== actual.sourceItem) {
3082
+ work.failure = 'has unsupported composition (literal identity changed)';
3083
+ return;
3084
+ }
3085
+ const fixed = new Map([...work.mapping].map(([token, mapped]) => [
3086
+ token,
3087
+ String(fieldText(mapped, variant) ?? ''),
3088
+ ]));
3089
+ const matched = reachedTemplateMatch(item.prompt, result.value.text, [
3090
+ encoded,
3091
+ ...payloads,
3092
+ ...[...variant.values.values()].map((value) => value.text),
3093
+ ], fixed);
3094
+ if (matched === undefined) {
3095
+ work.failure =
3096
+ 'does not preserve the complete GEARS child-input template';
3097
+ return;
3098
+ }
3099
+ for (const [token, text] of matched) {
3100
+ if (text !== encoded)
3101
+ continue;
3102
+ if (!quotedRelays.has(token)) {
3103
+ work.failure = `has unsupported structured inline substitution for ${token}`;
3104
+ return;
3105
+ }
3106
+ if (!acceptMapping(token, field, true))
3107
+ return;
3108
+ }
3109
+ }
3110
+ for (const field of fields) {
3111
+ const marker = sentinelFor(field);
3112
+ const candidate = literalScalarContext(context, { [field]: marker }, undefined, false, undefined, undefined, work.structured.size > 0 ? structured?.aliases : undefined);
3113
+ const result = invocationInput(binding.invoke, candidate.context);
3114
+ if (candidate.failure() !== undefined ||
3115
+ !('value' in result) ||
3116
+ typeof result.value.text !== 'string')
3117
+ continue;
3118
+ const text = result.value.text;
3119
+ if (text === actual.text || !text.includes(marker))
3120
+ continue;
3121
+ if (result.value.stateId !== binding.state.stateId ||
3122
+ result.value.playbookId !== binding.state.playbookId ||
3123
+ result.value.sourceItem !== actual.sourceItem) {
3124
+ work.failure = 'has unsupported composition (literal identity changed)';
3125
+ return;
3126
+ } // A control-only read is not a relay.
3127
+ const fixed = new Map([...work.mapping].map(([token, mapped]) => [
3128
+ token,
3129
+ mapped === field ? marker : String(fieldText(mapped) ?? ''),
3130
+ ]));
3131
+ const matched = reachedTemplateMatch(item.prompt, text, [marker, ...payloads], fixed);
3132
+ if (matched === undefined) {
3133
+ work.failure =
3134
+ 'does not preserve the complete GEARS child-input template';
3135
+ return;
3136
+ }
3137
+ for (const [token, value] of matched) {
3138
+ if (value !== marker)
3139
+ continue;
3140
+ if (!acceptMapping(token, field, false))
3141
+ return;
3142
+ }
3143
+ }
3144
+ // Do not merge cases by read paths: a later mapping may reveal an unread
3145
+ // nonempty payload in an earlier context. Every actual case is validated.
3146
+ if (work.cases.length >= 64) {
3147
+ work.failure =
3148
+ 'has unsupported composition (too many pending reached cases)';
3149
+ return;
3150
+ }
3151
+ work.cases.push({
3152
+ context,
3153
+ text: actual.text,
3154
+ influences,
3155
+ structures,
3156
+ jsonFacts,
3157
+ records,
3158
+ });
3159
+ if (!this.mapped(work))
3160
+ return;
3161
+ for (const reached of work.cases) {
3162
+ if (!literalRecordsUnchanged(reached.records) ||
3163
+ !literalJsonUnchanged(reached.jsonFacts)) {
3164
+ work.failure =
3165
+ 'has unsupported composition (observed context changed before proof)';
3166
+ return;
3167
+ }
3168
+ const baseline = invocationInput(binding.invoke, literalScalarContext(reached.context, {}, undefined, false).context);
3169
+ if (!('value' in baseline) ||
3170
+ baseline.value.text !== reached.text ||
3171
+ baseline.value.stateId !== binding.state.stateId ||
3172
+ baseline.value.playbookId !== binding.state.playbookId ||
3173
+ baseline.value.sourceItem !== actual.sourceItem) {
3174
+ work.failure =
3175
+ 'has unsupported composition (reached input changed before proof)';
3176
+ return;
3177
+ }
3178
+ const graph = literalJsonGraph(reached.context, reached.structures, reached.records);
3179
+ const render = (values, json = graph) => renderLiteralChildTemplate(item.prompt, work.mapping, (field) => Object.hasOwn(values, field)
3180
+ ? values[field]
3181
+ : work.structured.has(field)
3182
+ ? literalPathValue(reached.context, field, reached.records) ===
3183
+ undefined
3184
+ ? undefined
3185
+ : (json?.values.get(field)?.text ?? null)
3186
+ : literalPathValue(reached.context, field, reached.records));
3187
+ const expected = render({});
3188
+ if (expected === undefined || reached.text !== expected) {
3189
+ work.failure =
3190
+ 'does not preserve the complete GEARS child-input template' +
3191
+ (expected === undefined
3192
+ ? ''
3193
+ : ` (${firstDifferenceDiagnostic(expected, reached.text)})`);
3194
+ return;
3195
+ }
3196
+ const verifyPayload = (values, empty) => {
3197
+ const candidate = literalScalarContext(reached.context, values, undefined, false, undefined, undefined, work.structured.size > 0 ? graph?.aliases : undefined);
3198
+ const result = invocationInput(binding.invoke, candidate.context);
3199
+ const expected = render(values);
3200
+ if (candidate.failure() === undefined &&
3201
+ 'value' in result &&
3202
+ result.value.stateId === binding.state.stateId &&
3203
+ result.value.playbookId === binding.state.playbookId &&
3204
+ result.value.sourceItem === actual.sourceItem &&
3205
+ result.value.text === expected)
3206
+ return true;
3207
+ const label = empty
3208
+ ? 'does not preserve source-defined empty standalone relay omission'
3209
+ : 'does not preserve literal substitutions and quoted continuation lines';
3210
+ work.failure =
3211
+ label +
3212
+ (expected !== undefined &&
3213
+ 'value' in result &&
3214
+ typeof result.value.text === 'string'
3215
+ ? ` (${firstDifferenceDiagnostic(expected, result.value.text)})`
3216
+ : '');
3217
+ return false;
3218
+ };
3219
+ const activeFields = [...new Set(work.mapping.values())].filter((field) => reached.influences.has(field));
3220
+ for (const field of new Set(work.mapping.values())) {
3221
+ if (!work.structured.has(field))
3222
+ continue;
3223
+ const value = graph?.values.get(field);
3224
+ if (value === undefined &&
3225
+ literalPathValue(reached.context, field, reached.records) !==
3226
+ undefined) {
3227
+ work.failure =
3228
+ 'has unsupported composition (structured JSON inspection failed)';
3229
+ return;
3230
+ }
3231
+ for (const leaf of value?.leaves ?? [])
3232
+ for (const literal of [
3233
+ '«structured» $& <payload>\nsecond',
3234
+ '«distinct» " \\ \r\nlast',
3235
+ ]) {
3236
+ const variant = literalJsonGraph(reached.context, reached.structures, reached.records, { ...leaf, value: literal });
3237
+ if (variant === undefined) {
3238
+ work.failure =
3239
+ 'has unsupported composition (structured JSON inspection failed)';
3240
+ return;
3241
+ }
3242
+ const result = invocationInput(binding.invoke, literalScalarContext(reached.context, {}, undefined, false, undefined, undefined, variant.aliases).context);
3243
+ if (!('value' in result) ||
3244
+ result.value.stateId !== binding.state.stateId ||
3245
+ result.value.playbookId !== binding.state.playbookId ||
3246
+ result.value.sourceItem !== actual.sourceItem ||
3247
+ result.value.text !== render({}, variant)) {
3248
+ work.failure =
3249
+ 'does not preserve canonical structured JSON substitutions';
3250
+ return;
3251
+ }
3252
+ }
3253
+ }
3254
+ const scalarFields = activeFields.filter((field) => !work.structured.has(field));
3255
+ // Perturb one mapped payload only: no other reached control/payload changes.
3256
+ for (const field of scalarFields) {
3257
+ const multiline = item.prompt.split(/\r?\n/).some((line) => {
3258
+ const token = /^> [^<>\r\n]*(<[^\s<>`]{1,60}>)$/.exec(line)?.[1];
3259
+ return token !== undefined && work.mapping.get(token) === field;
3260
+ });
3261
+ for (const value of [
3262
+ `«literal» $& $$ $\x60 $' ${[...work.mapping.keys()].join(' ')}${multiline ? '\n\nsecond\r\n\r\nlast' : ''}`,
3263
+ '',
3264
+ ]) {
3265
+ if (!verifyPayload({ [field]: value }, value === ''))
3266
+ return;
3267
+ }
3268
+ }
3269
+ if (!literalRecordsUnchanged(reached.records) ||
3270
+ !literalJsonUnchanged(reached.jsonFacts)) {
3271
+ work.failure =
3272
+ 'has unsupported composition (observed context changed during proof)';
3273
+ return;
3274
+ }
3275
+ // Removing several standalone relays must preserve authored separators too.
3276
+ if (!verifyPayload(Object.fromEntries(scalarFields.map((field) => [field, ''])), true))
3277
+ return;
3278
+ }
3279
+ work.validated = true;
3280
+ work.cases = []; // Descriptor facts have passed; release stopped actor contexts.
3281
+ }
3282
+ findings() {
3283
+ return [...this.work.values()].flatMap((work) => work.failure !== undefined || !this.proved(work)
3284
+ ? [
3285
+ `${work.item.id}: FSM playbook text ${work.failure ?? work.original}`,
3286
+ ]
3287
+ : []);
3288
+ }
3289
+ }
2623
3290
  /** Findings when a composed prompt does not preserve the domain body (verification-5). */
2624
3291
  function bodyFindings(state, composed, substituted, reads, turn) {
2625
3292
  if (matchPromptBody(state.prompt, composed, reads, substituted) !== null) {
@@ -2705,7 +3372,7 @@ import { fileURLToPath } from 'node:url';
2705
3372
 
2706
3373
  import { describe, expect, it } from 'vitest';
2707
3374
 
2708
- import { checkGearsFsmConformance, findConcurrentRoleSets, findMachineConfig } from ${sourceString(opts.verifyModule)};
3375
+ import { checkGearsFsmConformanceAsync, fsmCoverageTestTimeout } from ${sourceString(opts.verifyModule)};
2709
3376
  import * as fsm from ${sourceString(opts.fsmModule)};
2710
3377
 
2711
3378
  const SCHEMA_FINDINGS: readonly string[] = ${JSON.stringify(opts.schemaFindings ?? [], null, 2)};
@@ -2715,20 +3382,20 @@ describe(${sourceString(`${opts.basename}: GEARS↔FSM conformance`)}, () => {
2715
3382
  expect(SCHEMA_FINDINGS).toEqual([]);
2716
3383
  });
2717
3384
 
2718
- it('maps every GEARS item to a state with its player and verbatim prompt', () => {
3385
+ it('maps every GEARS item to a state with its player and verbatim prompt', async () => {
2719
3386
  const gears = readFileSync(
2720
3387
  fileURLToPath(new URL(${sourceString(opts.gearsFile)}, import.meta.url)),
2721
3388
  'utf8',
2722
3389
  );
2723
3390
  expect(
2724
- checkGearsFsmConformance(gears, findMachineConfig(fsm), {
2725
- concurrentRoleSets: findConcurrentRoleSets(fsm),
3391
+ await checkGearsFsmConformanceAsync(gears, fsm, {
3392
+ sourceText: readFileSync(fileURLToPath(new URL(${sourceString(opts.fsmSourceFile ?? opts.fsmModule.replace(/\.js$/, '.ts'))}, import.meta.url)), 'utf8'),
2726
3393
  ${opts.artifactSchema === undefined
2727
3394
  ? ''
2728
3395
  : `artifactSchema: ${opts.artifactSchema},`}
2729
3396
  }),
2730
3397
  ).toEqual([]);
2731
- });
3398
+ }, fsmCoverageTestTimeout(fsm));
2732
3399
  });
2733
3400
  `;
2734
3401
  }